def read(self): temperature = round((self.sensor.temperature - 5) * 1.8 + 32, 2) gas = self.sensor.gas humidity = round(self.sensor.humidity, 1) pressure = round(self.sensor.pressure, 2) altitude = round(self.sensor.altitude, 3) if humidity is not None and temperature is not None: self.r.set(self.key + '_temperature', temperature) self.r.set(self.key + '_humidity', humidity) self.r.set(self.key + '_gas', gas) self.r.set(self.key + '_pressure', pressure) self.r.set(self.key + '_altitude', altitude) readings = { 'temperature': temperature, 'humidity': humidity, 'pressure': pressure, 'gas': gas, 'altitude': altitude } self.r.set(self.key, json.dumps(readings)) # print('BME680:', readings) return readings else: Logger.log(LOG_LEVEL["error"], 'Failed to get reading [BME680]. Try again!')
def setup(test=False): from databases.Database import Database from logger.Logger import Logger from realms import Realm from config import REALMS, DATABASE from operations import Operation from Requests import Request from config import CREDENTIALS logger = Logger(os.getcwd(), "d") logger.log(msg="\n" * 3, timestamped=False, level_display=False) logger.log(msg="*" * 150, timestamped=False, level_display=False) logger.log(msg="*" * 65 + "Started new session!" + "*" * 65, timestamped=False, level_display=False) logger.log(msg="*" * 150, timestamped=False, level_display=False) db = Database(DATABASE, logger, test) request = Request(CREDENTIALS, db, logger) operation = Operation(db, logger) for realm_id in REALMS: realm = Realm(realm_id, db, logger, request) operation.realms.append(realm) operation.setLiveData(request) return operation, request
def trigger(self, value=None): try: if self.check_group(): self.trigger_count += 1 if self.trigger_count == 1: for action in self.actions: action.trigger(value) for sequence in self.sequences: sequence.update(value) else: if self.frequency == 'many': for action in self.actions: action.trigger(value) for sequence in self.sequences: sequence.update(value) else: self.trigger_count = 0 except Exception as e: Logger.log(LOG_LEVEL["error"], "Error triggering group {0} ".format(self.key), e) pass return
def check(self): while self.main_thread_running.is_set(): if self.system_ready.is_set(): super().check() try: if CRON_ENABLED: if pycron.is_now(self.schedule): self.trigger_active.set() super().trigger() else: self.trigger_active.clear() else: Logger.log( LOG_LEVEL["error"], "Error pycron not found." ) except: Logger.log( LOG_LEVEL["error"], "Error evaluating time trigger schedule." ) time.sleep(self.trigger_interval) else: time.sleep(2) return
def init(self): Logger.log( LOG_LEVEL["info"], 'Relay Worker {0}...\t\t\t\033[1;32m Initializing\033[0;0m'.format( self.key) ) self.gpio_pin = digitalio.DigitalInOut(self.pin_obj) self.gpio_pin.switch_to_output() # Close the relay by default, we use the pin state # we determined based on the config at init self.gpio_pin.value = self.pin_state_off time.sleep(0.1) # Feature to restore relay state in case of crash # or unexpected shutdown. This will check for last state # stored in redis and set relay accordingly if (self.config.get('restore_last_known_state', None) is not None and self.config.get( 'restore_last_known_state', False) is True): if self.r.get(self.key + '_state'): self.gpio_pin.value = self.pin_state_on Logger.log( LOG_LEVEL["info"], 'Restoring Relay \033[1;36m{0} On\033[0;0m'.format( self.key) ) # Logger.log( # LOG_LEVEL["info"], # 'Relay Worker {0}...\t\t\t\033[1;32m Ready\033[0;0m'.format(self.key) # ) return
def run(self): Logger.log( LOG_LEVEL["info"], 'Relay Worker {0}...\t\t\t\033[1;32m Online\033[0;0m'.format( self.key) ) return super().run()
def init(self): Logger.log( LOG_LEVEL["info"], 'LCD Display Worker...\t\t\t\033[1;32m Initializing\033[0;0m'. format(**self.config)) # prepare sensor on specified pin self.i2c = busio.I2C(board.SCL, board.SDA) if (self.model): if (self.model.lower() == 'rgb'): self.lcd = character_lcd.Character_LCD_RGB_I2C( self.i2c, self.columns, self.rows, self.address) elif (self.model.lower() == 'pcf'): self.lcd = character_lcd.Character_LCD_I2C( self.i2c, self.columns, self.rows, address=self.address, usingPCF=True) else: self.lcd = character_lcd.Character_LCD_I2C( self.i2c, self.columns, self.rows, self.address) else: self.lcd = character_lcd.Character_LCD_I2C(self.i2c, self.columns, self.rows, self.address) self.lcd.backlight = True self.lcd.clear() self.lcd.message = "MudPi\nGarden Online" time.sleep(2) self.lcd.clear() return
def init(self): Logger.log( LOG_LEVEL["info"], '{name} Relay Worker {0}...\t\t\033[1;32m Initializing\033[0;0m'. format(self.key)) self.api = self.api if self.api is not None else ArduinoApi(connection) self.pin_state_off = self.api.HIGH if self.config[ 'normally_open'] is not None and self.config[ 'normally_open'] else self.api.LOW self.pin_state_on = self.api.LOW if self.config[ 'normally_open'] is not None and self.config[ 'normally_open'] else self.api.HIGH self.api.pinMode(self.config['pin'], self.api.OUTPUT) # Close the relay by default, we use the pin state we determined based on the config at init self.api.digitalWrite(self.config['pin'], self.pin_state_off) time.sleep(0.1) # Feature to restore relay state in case of crash or unexpected shutdown. This will check for last state stored in redis and set relay accordingly if (self.config.get('restore_last_known_state', None) is not None and self.config.get('restore_last_known_state', False) is True): if (self.r.get(self.key + '_state')): self.api.digitalWrite(self.config['pin'], self.pin_state_on) Logger.log( LOG_LEVEL["warning"], 'Restoring Relay \033[1;36m{0} On\033[0;0m'.format( self.key)) self.relay_ready = True return
def init(self): try: self.camera = PiCamera( resolution=(self.resolutionX, self.resolutionY)) # Below we calibrate the camera for consistent imaging self.camera.framerate = 30 # Wait for the automatic gain control to settle time.sleep(2) # Now fix the values self.camera.shutter_speed = self.camera.exposure_speed self.camera.exposure_mode = 'off' g = self.camera.awb_gains self.camera.awb_mode = 'off' self.camera.awb_gains = g except Exception: self.camera = PiCamera() # Pubsub Listeners self.pubsub = self.r.pubsub() self.pubsub.subscribe(**{self.topic: self.handle_event}) Logger.log( LOG_LEVEL["info"], 'Camera Worker...\t\t\t\033[1;32m Ready\033[0;0m' ) return
def work(self): while self.main_thread_running.is_set(): if self.system_ready.is_set(): time.sleep(self.sleep_duration) # This is only ran after the main thread is shut down Logger.log(LOG_LEVEL["info"], "Worker Shutting Down...\t\033[1;32m Complete\033[0;0m")
def init(self): for control in self.config['controls']: if control.get('type', None) is not None: #Get the control from the controls folder {control name}_control.{ControlName}Control control_type = 'controls.pi.' + control.get('type').lower( ) + '_control.' + control.get('type').capitalize() + 'Control' imported_control = self.dynamic_import(control_type) #new_control = imported_control(control.get('pin'), name=control.get('name', control.get('type')), connection=self.connection, key=control.get('key', None)) # Define default kwargs for all control types, conditionally include optional variables below if they exist control_kwargs = { 'name': control.get('name', None), 'pin': int(control.get('pin')), 'key': control.get('key', None), 'topic': control.get('topic', None), 'resistor': control.get('resistor', None), 'edge_detection': control.get('edge_detection', None), 'debounce': control.get('debounce', None) } # optional control variables # add conditional control vars here... new_control = imported_control(**control_kwargs) new_control.init_control() self.controls.append(new_control) Logger.log( LOG_LEVEL["info"], '{type} Control {pin}...\t\t\t\033[1;32m Ready\033[0;0m'. format(**control)) return
def work(self): while self.main_thread_running.is_set(): if self.system_ready.is_set(): message = {'event': 'PiSensorUpdate'} readings = {} for sensor in self.sensors: result = sensor.read() readings[sensor.key] = result self.r.set(sensor.key, json.dumps(result)) #print(sensor.name, result) #Check for a critical water level from any float sensors if sensor.type == 'float': if sensor.critical: if result: pass #self.pump_ready.set() else: pass #self.pump_ready.clear() print(readings) message['data'] = readings self.r.publish(self.topic, json.dumps(message)) time.sleep(self.sleep_duration) time.sleep(2) #This is only ran after the main thread is shut down Logger.log( LOG_LEVEL["info"], "Pi Sensor Worker Shutting Down...\t\033[1;32m Complete\033[0;0m")
def work(self): delay_multiplier = 1 while self.main_thread_running.is_set(): if self.system_ready.is_set() and self.node_ready.is_set(): if not self.node_connected.is_set(): #Connection Broken - Reset Connection self.resetConnection() Logger.log(LOG_LEVEL["warning"], '\033[1;36m{name}\033[0;0m -> \033[1;33mTimeout!\033[0;0m \t\t\t\033[1;31m Connection Broken\033[0;0m'.format(**self.config)) time.sleep(30) else: # Node reconnection cycle if not self.node_connected.is_set(): # Random delay before connections to offset multiple attempts (1-5 min delay) random_delay = (random.randrange(30, self.config.get("max_reconnect_delay", 300)) * delay_multiplier) / 2 time.sleep(10) Logger.log(LOG_LEVEL["info"], '\033[1;36m'+str(self.config['name']) +'\033[0;0m -> Retrying in '+ '{0}s...'.format(random_delay)+'\t\033[1;33m Pending Reconnect\033[0;0m ') # Two separate checks for main thread event to prevent re-connections during shutdown if self.main_thread_running.is_set(): time.sleep(random_delay) if self.main_thread_running.is_set(): self.connection = self.connect() if self.connection is None: delay_multiplier += 1 if delay_multiplier > 6: delay_multiplier = 6 else: delay_multiplier = 1 # Main loop delay between cycles time.sleep(self.sleep_duration) # This is only ran after the main thread is shut down # Join all our sub threads for shutdown for thread in self.threads: thread.join() Logger.log(LOG_LEVEL["info"], ("{name} Shutting Down...\t\t\033[1;32m Complete\033[0;0m".format(**self.config))
def work(self): while self.main_thread_running.is_set(): if self.system_ready.is_set(): message = {'event': 'PiSensorUpdate'} readings = {} for sensor in self.sensors: result = sensor.read() if result is not None: readings[sensor.key] = result self.r.set(sensor.key, json.dumps(result)) # print(sensor.name, result) if bool(readings): print(readings) message['data'] = readings self.r.publish(self.topic, json.dumps(message)) time.sleep(self.sleep_duration) time.sleep(2) # This is only ran after the main thread is shut down Logger.log( LOG_LEVEL["info"], "Pi Sensor Worker Shutting Down...\t\033[1;32m Complete\033[0;0m" )
def run(self): Logger.log( LOG_LEVEL["info"], 'Pi Sensor Worker [' + str( len(self.sensors) ) + ' Sensors]...\t\t\033[1;32m Online\033[0;0m' ) return super().run()
def run(self): t = threading.Thread(target=self.work, args=()) t.start() Logger.log( LOG_LEVEL["info"], 'Node {name} Sensor Worker...\t\t\033[1;32m Online\033[0;0m'. format(**self.config)) return t
def run(self): t = threading.Thread(target=self.work, args=()) t.start() self.listener = threading.Thread(target=self.listen, args=()) self.listener.start() Logger.log(LOG_LEVEL["info"], 'Camera Worker...\t\t\t\033[1;32m Online\033[0;0m') return t
def run(self): t = threading.Thread(target=self.work, args=()) t.start() Logger.log( LOG_LEVEL["info"], 'Node Relay {0} Worker...\t\t\033[1;32m Online\033[0;0m'.format( self.key)) return t
def __init__(self): self.marketComparator = MarketComparator() self.market = Market() self.bithumb = BithumbConnector() self.bithumb_coin_market = BithumbConnector2() self.kraken = KrakenConnector() self.crypto_compare = CryptoCompareConnector() self.alert = SoundAlert() self.logger = Logger().get_logger()
def trigger(self, value=None): try: for action in self.sequence[self.current_step].get('actions', []): self.actions[action].trigger(value) self.step_triggered = True except Exception as e: Logger.log(LOG_LEVEL["error"], "Error triggering sequence action {0} ".format( self.key), e) pass return
def work(self): while self.main_thread_running.is_set(): if self.system_ready.is_set(): readings = {} for control in self.controls: result = control.read() readings[control.key] = result time.sleep(self.sleep_duration) #This is only ran after the main thread is shut down Logger.log( LOG_LEVEL["info"], "Pi Control Worker Shutting Down...\t\033[1;32m Complete\033[0;0m")
def run(self): for worker in self.workers: t = worker.run() self.threads.append(t) time.sleep(1) t = threading.Thread(target=self.work, args=()) t.start() if self.node_ready.is_set(): Logger.log(LOG_LEVEL["info"], str(self.config['name']) +' Node Worker '+ '[S: ' + str(len(self.config['sensors'])) + ']' + '[C: ' + str(len(self.config['controls'])) + ']...\t\033[1;32m Online\033[0;0m') else: Logger.log(LOG_LEVEL["info"], str(self.config['name']) +'...\t\t\t\t\033[1;33m Pending Reconnect\033[0;0m ') return t
def trigger(self, value=None): try: if self.group is None: # Trigger the actions of the trigger for action in self.actions: action.trigger(value) else: self.group.trigger() except Exception as e: Logger.log(LOG_LEVEL["error"], "Error triggering action {0} ".format(self.key), e) pass return
class SoundAlert: def __init__(self): self.logger = Logger().get_logger() # TODO : sound sur windows avec winsound, sur linux... ? def alert_buy(self): # winsound.PlaySound('sounds/sound.wav', winsound.SND_FILENAME) self.logger.info("ALERTE : BUY !") def alert_sell(self): # winsound.PlaySound('sounds/no.wav', winsound.SND_FILENAME) self.logger.info("ALERTE : SELL !")
def __init__(self, system_running, host='127.0.0.1', port=7002): self.port = int(port) self.host = host self.system_running = system_running self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.client_threads = [] try: self.sock.bind((self.host, self.port)) except socket.error as msg: Logger.log(LOG_LEVEL["error"], 'Failed to create socket. Error Code: ', str(msg[0]), ' , Error Message: ', msg[1]) sys.exit()
def handleMessage(self, message): data = message['data'] if data is not None: decoded_message = self.decodeMessageData(data) try: if decoded_message['event'] == 'Message': if decoded_message.get('data', None): self.addMessageToQueue( decoded_message['data'].get('message', ''), int(decoded_message['data'].get( 'duration', self.default_duration))) Logger.log( LOG_LEVEL["debug"], 'LCD Message Queued: \033[1;36m{0}\033[0;0m'. format(decoded_message['data'].get( 'message', '').replace("\\n", "\n"))) elif decoded_message['event'] == 'Clear': self.lcd.clear() Logger.log(LOG_LEVEL["debug"], 'Cleared the LCD Screen') elif decoded_message['event'] == 'ClearQueue': self.message_queue = [] Logger.log(LOG_LEVEL["debug"], 'Cleared the LCD Message Queue') except: Logger.log(LOG_LEVEL["error"], 'Error Decoding Message for LCD')
def init_sensor(self): #Initialize the sensor here (i.e. set pin mode, get addresses, etc) this gets called by the worker sensor_types = { '11': Adafruit_DHT.DHT11, '22': Adafruit_DHT.DHT22, '2302': Adafruit_DHT.AM2302 } if self.type in sensor_types: self.sensor = sensor_types[self.type] else: Logger.log(LOG_LEVEL["warning"], 'Sensor Model Error: Defaulting to DHT11') self.sensor = Adafruit_DHT.DHT11 return
def listen(self): self.sock.listen(0) # number of clients to listen for. Logger.log(LOG_LEVEL['info'], 'MudPi Server...\t\t\t\t\033[1;32m Online\033[0;0m ') while self.system_running.is_set(): try: client, address = self.sock.accept() client.settimeout(600) ip, port = client.getpeername() Logger.log( LOG_LEVEL['info'], 'Socket \033[1;32mClient {0}\033[0;0m from \033[1;32m{1} Connected\033[0;0m' .format(port, ip)) t = threading.Thread(target=self.listenToClient, args=(client, address, ip)) self.client_threads.append(t) t.start() except Exception as e: Logger.log(LOG_LEVEL['error'], e) time.sleep(1) pass self.sock.close() if len(self.client_threads > 0): for client in self.client_threads: client.join() Logger.log(LOG_LEVEL['info'], 'Server Shutdown...\t\t\t\033[1;32m Complete\033[0;0m')
def run(self): if self.node_ready: t = threading.Thread(target=self.work, args=()) t.start() Logger.log( LOG_LEVEL["info"], str(self.config['name']) + ' Node Worker [' + str(len(self.config['sensors'])) + ' Sensors]...\t\033[1;32m Online\033[0;0m') return t else: Logger.log(LOG_LEVEL["warning"], "Node Connection...\t\t\t\033[1;31m Failed\033[0;0m") return None
def init_sensor(self): self.sensors = DallasTemperature(self.pin, connection=self.connection) self.sensor_bus = self.sensors.getDeviceCount() # read data using pin specified pin Logger.log(LOG_LEVEL["debug"], "There are", self.sensor_bus, "devices connected on pin ", self.sensors.pin) self.addresses = [] for i in range(self.sensor_bus): self.addresses.append(self.sensors.getAddress(i)) Logger.log(LOG_LEVEL["debug"], "Their addresses", self.addresses) #I guess this is something with bit rates? TODO: Look this up self.sensors.setResolution(10)
def main(): Logger.initlogger("conf/logconf.ini") Logger.debug("logger init complete") Logger.error("this is a error log") Logger.warning("this is a warning log")