def verify(self): try: Plant.get(Plant.localhost == True) return True except Exception as e: logger.warning(e) return False
def simulate(self): target = Plant.get(Plant.localhost == True) source = Plant.get(Plant.name == 'marta') for sensor in Sensor.select(): logger.info(sensor.name) PlantSimulate().run(target, sensor, source) logger.info('finished')
def get_plant_sensor_data_high_ever(sensor, p_uuid, mode): configuration = True if mode == 'high' else False plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) return json.dumps(get_sensor_data_high_low(plant, sensor, configuration))
def get_plant_count(p_uuid, sensor): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) sensor_data_set = SensorData.select() \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) return json.dumps({'count': sensor_data_set.count()})
def update_current_plant_host(): local = Plant.get(Plant.localhost == True) if not local.host: host = Plant.get(Plant.host == True) host.host = False host.save() local.host = True local.save() MeshDedicatedDispatch().update('host', local.uuid) return json.dumps({'info': 'processing'})
def remove(self, mode, plant): if mode not in ['remove', 'activate', 'deactivate']: raise ValueError('remove mode not valid') if not plant.localhost: daemon = MeshNetwork() # Plant.active == True, for target in list(Plant.select().where(Plant.localhost == False, Plant.role == 'master')): initial = {'mode': mode, 'destination': {'uuid': str(plant.uuid), 'ip': plant.ip, 'relation': 'master'}} daemon.remove(1, 1, target, initial=initial) status = self.get(120) if status == 1: logger.info('successful') else: logger.info('could not reach host') local = Plant.get(localhost=True) if plant.role != 'master' and plant.role == str(local.uuid): daemon.remove(2, 1, plant) status = self.get(120) if status == 1: logger.info('successful') else: logger.info('could not reach host') if mode == 'remove': local = Plant.get(localhost=True) for slave in list(Plant.select().where(Plant.role == str(plant.uuid))): slave.role = str(local.uuid) slave.save() from models.sensor import SensorData, SensorStatus, SensorCount, SensorSatisfactionValue, SensorDataPrediction from models.plant import PlantNetworkUptime for model in [PlantNetworkUptime, SensorData, SensorStatus, SensorCount, SensorSatisfactionValue, SensorDataPrediction]: model.delete().where(model.plant == plant).execute() plant.delete_instance() elif mode == 'activate': plant.active = True plant.save() elif mode == 'deactivate': plant.active = False plant.save() else: logger.error('not supported mode') return True else: return False
def get_plant_sensor_data(p_uuid, sensor): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) sensor_data_set = SensorData.select(SensorData.value, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .order_by(SensorData.created_at.asc()) content = list(sensor_data_set) return json.dumps(content)
def plant_responsible(p_uuid): # GET: select: email, wizard, username, full, default (full) responsible = Plant.get(uuid=p_uuid).person if request.method == 'GET': responsible = model_to_dict(responsible) responsible['uuid'] = str(responsible['uuid']) data, code = get_data(required=PLANT_RESPONSIBLE_GET, restrictive=True) if code == 400: return data_formatting(400) selector = data['select'] collection = {} for selected in selector: if selected != 'full': used = [selected, 'uuid'] else: used = list(responsible.keys()) output = {} for key in used: if key not in ['id', 'preset']: output[key] = responsible[key] if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output) else: data, code = get_data(required=PLANT_RESPONSIBLE_POST, restrictive=True) if code == 400: return data_formatting(400) if data['email'] != '' and data['name'] != '': responsible = Person.get(Person.email**data['email'], Person.name**data['name']) elif data['uuid'] != '': responsible = Person.get(uuid=data['uuid']) plant = Plant.get(uuid=p_uuid) plant.person = responsible plant.save() return data_formatting()
def run(): result = VariousTools.offline_check('ledbar', hardware=True, pins=[0, 1, 2, 3, 4, 5], mcp=True) if result: sensor = Sensor.get(Sensor.name == 'moisture') plant = Plant.get(localhost=True) status = SensorStatus.get(SensorStatus.sensor == sensor, SensorStatus.plant == plant) bus = 1 gpio_count = 16 address = 0x20 mcp = MCP230XX_GPIO(bus, address, gpio_count) # green color port: 2, 1 # yellow color port: 4, 3 # red color port: 6, 5 led = 0 for i in [['threat', 6, 5], ['cautioning', 4, 3], ['optimum', 2, 1]]: if status.level.label == i[0]: led = i[2] if status.status is True else i[1] pins = [0, 1, 2, 3, 4, 5] for pin in pins: mcp.setup(pin, mcp.OUT) for i in range(0, led - 1): mcp.output(i, 0) # Pin Low time.sleep(round((1.35**i) / 10, 3)) for i in range(5, led - 2, -1): mcp.output(i, 1) # Pin High time.sleep(round((1.35**i) / 10, 3))
def update_plant_purge(): from mesh_network.dedicated import MeshDedicatedDispatch target = Plant.get(uuid=request.form['uuid']) MeshDedicatedDispatch().remove('remove', target) return json.dumps(True)
def get_current_satifaction(): output = {} sensors = Sensor.select() for plant in Plant.select(): host = None if plant.role != 'master': host = Plant.get(Plant.uuid == plant.role) statuses = [] for sensor in sensors: selected = plant if sensor.name not in slave_supported and host is not None: selected = host status = SensorStatus.get(SensorStatus.sensor == sensor, SensorStatus.plant == selected) inserted = 1 if status.level.label == 'threat': inserted = 3 elif status.level.label == 'cautioning': inserted = 2 statuses.append(inserted) maximum = max(statuses) label = 'optimum' if maximum == 3: label = 'threat' elif maximum == 2: label = 'cautioning' output[str(plant.uuid)] = {'streak': plant.sat_streak, 'name': label} return json.dumps(output)
def run(samples=10): GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) GPIO.setup(4, GPIO.OUT) GPIO.output(4, True) time.sleep(1) values = [] for i in range(0, samples): values.append(mcp3002().read_pct(0, 1)) time.sleep(.2) print(values) GPIO.output(4, False) average = sum(values) / float(len(values)) if average != 0: toolchain = ToolChainSensor() plant = Plant.get(localhost=True) moisture = { 'sensor': Sensor.get(Sensor.name == 'moisture'), 'plant': plant, 'value': average } if toolchain.insert_data(moisture): toolchain.set_hardware(moisture)
def host_verification(response): if 'host' not in request.cookies: from mesh_network.dedicated import MeshDedicatedDispatch from models.plant import Plant local = Plant.get(localhost=True) if not local.host: host = Plant.get(host=True) host.host = False host.save() local.host = True local.save() MeshDedicatedDispatch().update('host', local.uuid) response.set_cookie('host', 'easteregg', max_age=5 * 60) return response
def run(): plant = Plant.get(localhost=True) # PARSE PARAMETERS temperature = { 'sensor': Sensor.select().where(Sensor.name == 'temperature')[0], 'plant': plant } humidity = { 'sensor': Sensor.select().where(Sensor.name == 'humidity')[0], 'plant': plant } if temperature['sensor'].model == humidity['sensor'].model: sensor = Adafruit_DHT.DHT22 if temperature[ 'sensor'].model == 'DHT22' else Adafruit_DHT.DHT11 pin = 26 # FETCH DATA FROM SENSOR humidity['value'], temperature['value'] = Adafruit_DHT.read_retry( sensor, pin) if humidity is not None and temperature is not None: toolchain = ToolChainSensor() if toolchain.insert_data(temperature): toolchain.set_hardware(temperature) if toolchain.insert_data(humidity): toolchain.set_hardware(humidity)
def update_plant_location(p_uuid): plant = Plant.get(Plant.uuid == p_uuid) plant.location = request.form['new'].lower() plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return json.dumps({'info': 1})
def get_sensor_staus_online(p_uuid): plant = Plant.get(Plant.uuid == p_uuid) uptimes = PlantNetworkUptime.select() \ .where(PlantNetworkUptime.plant == plant) output = {} summary = 0 for uptime in uptimes: output[uptime.status.name] = [0, uptime.overall, uptime.current] summary += uptime.overall for key, uptime in output.items(): print(type(output[key][1])) output[key][0] = round(output[key][1] / summary * 100) if output[key][1] != 0 else 0 if output == {}: output = {'online': [0, 0.0, 0.0], 'offline': [0, 0.0, 0.0]} if plant.localhost: output = {'online': [100, 1, 1], 'offline': [100, 1, 1]} return json.dumps(output)
def update_plant_notification_duration(p_uuid): _, _, hours = time_request_from_converter(request.form) plant = Plant.get(Plant.uuid == p_uuid) plant.interval = int(hours) plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return json.dumps({'info': 1})
def get_responsible_full_dataset(p_uuid): responsible = Plant.get(Plant.uuid == UUID(p_uuid)).person responsible = model_to_dict(responsible) responsible['uuid'] = str(responsible['uuid']) del responsible['id'] del responsible['preset'] return json.dumps(responsible)
def update_plant_toggle(): from mesh_network.dedicated import MeshDedicatedDispatch target = Plant.get(uuid=request.form['uuid']) mode = 'deactivate' if target.active else 'active' MeshDedicatedDispatch().remove(mode, target) return json.dumps(True)
def update_plant_persistant_hold(p_uuid): _, minutes, _ = time_request_from_converter(request.form) plant = Plant.get(Plant.uuid == p_uuid) plant.persistant_hold = minutes / 5 plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return json.dumps({'info': 1})
def update_plant_connection_lost(p_uuid): _, minutes, _ = time_request_from_converter(request.form) plant = Plant.get(Plant.uuid == p_uuid) plant.connection_lost = int(minutes) plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return json.dumps({'info': 1})
def get_plant_data_selective(p_uuid, sensor, start, stop): plant = Plant.get(uuid=p_uuid) sensor = Sensor.get(name=sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(uuid=plant.role) dataset = SensorData.select(SensorData.value, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .order_by(SensorData.created_at.desc()) \ .offset(start) \ .limit(stop - start) \ .dicts() dataset = list(dataset) return json.dumps(dataset)
def host(): if request.method == 'GET': plant = Plant.get(host=True) data, code = get_data(required=HOST_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) selector = data['select'] print('Host: {}'.format(str(selector))) collection = {} # output = {} for selected in selector: output = [] if selected == 'full': output = model_to_dict(plant) output['timestamp'] = output['created_at'].timestamp() output['uuid'] = str(output['uuid']) del output['id'] del output['person'] del output['created_at'] if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output) else: local = Plant.get(localhost=True) if not local.host: host = Plant.get(host=True) host.host = False host.save() local.host = True local.save() MeshDedicatedDispatch().update('host', local.uuid) return data_formatting()
def get_plant_sensor_prediction(p_uuid, sensor): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) sensor_prediction_set = SensorDataPrediction.select(SensorDataPrediction.value, SensorDataPrediction.time) \ .where(SensorDataPrediction.plant == plant) \ .where(SensorDataPrediction.sensor == sensor) \ .order_by(SensorDataPrediction.created_at.asc()) \ .dicts() sensor_prediction_set = list(sensor_prediction_set) for prediction in sensor_prediction_set: prediction['timestamp'] = prediction['time'].timestamp() del prediction['time'] return json.dumps(sensor_prediction_set)
def new_data(self, sensor, plant=None): from models.plant import Plant if plant is None: plant = Plant.get(localhost=True) daemon = MeshNetwork() for target in list(Plant.select().where(Plant.active == True, Plant.localhost == False, Plant.role == 'master')): daemon.deliver(1, sub=1, recipient=target, sensor=sensor, origin=plant)
def get_plant_sensor_data_after(p_uuid, sensor, until): sensor = Sensor.get(Sensor.name == sensor) plant = Plant.get(Plant.uuid == p_uuid) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) date_time = datetime.datetime.fromtimestamp(until + 1) sensor_data_set = SensorData.select(SensorData.value, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .where(SensorData.created_at > date_time) \ .order_by(SensorData.created_at.asc()) \ .dicts() sensor_data_set = list(sensor_data_set) return json.dumps(sensor_data_set)
def get_latest_dataset(p_uuid, s_uuid): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == s_uuid) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) sd = SensorData.select(SensorData.value, SensorData.persistant, fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('timestamp')) \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .order_by(SensorData.created_at.desc()) \ .limit(1) \ .dicts() selected = list(sd)[0] return json.dumps(selected)
def get_plant_current_sensor_data(p_uuid, sensor): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == sensor) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(Plant.uuid == UUID(plant.role)) latest = SensorData.select() \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .order_by(SensorData.created_at.desc())[0] latest = model_to_dict(latest) del latest['id'] del latest['plant'] del latest['sensor'] return json.dumps(latest, default=json_util.default)
def create_plant(data): try: Plant.get(Plant.ip == data['ip']) except: from models.mesh import MeshObject discovered = MeshObject.get(ip=data['ip']) plant = Plant() plant.name = data['name'].lower() plant.location = data['location'] plant.species = data['species'] plant.interval = data['interval'] plant.person = Person.get(Person.email == data['email']) plant.ip = data['ip'] plant.sat_streak = 0 if 'uuid' in data: plant.uuid = data['uuid'] if 'persistant_hold' in data: plant.persistant_hold = data['persistant_hold'] if not discovered.master: if 'role' not in data: master = Plant.get(localhost=True) else: master = Plant.get(uuid=data['role']) plant.role = str(master.uuid) plant.save() local_plant = Plant.get(Plant.localhost == True) for model in [SensorStatus, SensorCount, SensorSatisfactionValue, PlantNetworkUptime]: copy_model_instance_from_localhost(plant, model, model.plant == local_plant) for count in list(SensorCount.select().where(SensorCount.plant == plant)): count.count = 0 count.save() for uptime in list(PlantNetworkUptime.select().where(PlantNetworkUptime.plant == plant)): uptime.overall = 0 uptime.current = 0 uptime.save() return plant
def get_plant_intervals(p_uuid): plant = Plant.get(Plant.uuid == p_uuid) return json.dumps({ 'connection_lost': plant.connection_lost, 'non_persistant': int(plant.persistant_hold * 5 / 60 / 24), 'notification': plant.interval })