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 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 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_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 alive(self): from models.plant import Plant from models.plant import PlantNetworkStatus from models.plant import PlantNetworkUptime daemon = MeshNetwork() online = PlantNetworkStatus.select().where(PlantNetworkStatus.name == 'online') offline = PlantNetworkStatus.select().where(PlantNetworkStatus.name == 'offline') masters = Plant.select().where(Plant.localhost == False, Plant.role == 'master', Plant.active == True) masters = list(masters) plants = deepcopy(masters) local = Plant.get(localhost=True) slaves = Plant.select().where(Plant.localhost == False, Plant.role == str(local.uuid)) plants.extend(list(slaves)) for plant in plants: daemon.alive(plant, 1) status = self.get(5) online_dataset = None offline_dataset = None options = [[online, online_dataset, [1]], [offline, offline_dataset, [254, 255]]] for i in options: i[1] = None i[1], _ = PlantNetworkUptime.get_or_create(plant=plant, status=i[0], defaults={'overall': 0, 'current': 0}) if status in i[2]: i[1].current += 1 i[1].overall += 1 i[1].save() if plant.role != 'master': data = urllib.parse.urlencode({}).encode('ascii') for master in masters: req = urllib.request.Request('http://{}:2902/update/plant/{}/alive/{}/add'.format(master.ip, str(plant.uuid), i[1].status.name), data) try: with urllib.request.urlopen(req) as response: response.read().decode('utf8') except Exception as e: logger.warning('{} - {}: {}'.format(plant.name, master.name, e)) for dataset in options: if dataset[0] != i[0] and i[1].current != 0: i[1].current = 0 i[1].save()
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(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 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 get_plants_name_extended(): plants = Plant.select(Plant.uuid, Plant.name, Plant.role, Plant.localhost, Plant.active).dicts() plants = list(plants) for plant in plants: plant['uuid'] = str(plant['uuid']) return json.dumps(plants)
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 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 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 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 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 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 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_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 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 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_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 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_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_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 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_plants_master(): plants = Plant.select(Plant.ip, Plant.localhost, Plant.name, Plant.uuid).where(Plant.role == 'master').dicts() plants = list(plants) for plant in plants: plant['uuid'] = str(plant['uuid']) return json.dumps(plants)