def day_night(): if request.method == 'GET': data, code = get_data(required=DAYNIGHT_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) selector = data['select'] collection = {} for selected in selector: output = [] if selected == 'full': for daynight in DayNightTime.select(): dn = model_to_dict(daynight) dn['uuid'] = str(dn['uuid']) output.append(dn) 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=DAYNIGHT_POST, restrictive=True) if code == 400: return data_formatting(400) for day_night in DayNightTime.select(): day_night.stop = data['stop'] day_night.start = data['start'] day_night.ledbar = data['ledbar'] day_night.display = data['display'] day_night.generalleds = data['generalleds'] day_night.notification = data['notification'] day_night.pump = data['pump'] day_night.save() for slave in list(Plant.select().where(Plant.role != 'master')): information = {'min': data['start'], 'max': data['stop']} MeshDedicatedDispatch().slave_update(0, information, slave) MeshDedicatedDispatch().update('day night time', DayNightTime.select()[0].uuid) return data_formatting()
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 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 update_responsible(): person = Person.get(Person.uuid == request.form['uuid']) person.name = request.form['name'] person.email = request.form['email'] person.save() MeshDedicatedDispatch().update('person', person.uuid) return json.dumps({'info': 'success'})
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 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 update_plant_responsible(p_uuid): plant = Plant.get(Plant.uuid == p_uuid) person = Person.get(Person.email == request.form['email'], Person.name == request.form['name']) plant.person = person plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return json.dumps({'info': 1})
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 update_slave_master(): from mesh_network.dedicated import MeshDedicatedDispatch from models.plant import Plant slave = Plant.get(uuid=request.form['slave']) local = Plant.get(localhost=True) if request.form['target'] == slave.role: return json.dumps(False) target = Plant.get(uuid=request.form['target']) if slave.role == str(local.uuid): MeshDedicatedDispatch().slave_update(1, {'uuid': target.uuid, 'ip': target.ip}, slave) slave.role = str(target.uuid) slave.save() MeshDedicatedDispatch().update('slave host change', slave.uuid, target=target) return json.dumps(True)
def update_day_night(): data = deepcopy(request.form) for day_night in DayNightTime.select(): day_night.stop = data['stop'] day_night.start = data['start'] day_night.ledbar = data['ledbar'] day_night.display = data['display'] day_night.generalleds = data['generalleds'] day_night.notification = data['notification'] day_night.save() for slave in list(Plant.select().where(Plant.role != 'master')): logger.info('executing slave update') information = {'min': data['start'], 'max': data['stop']} MeshDedicatedDispatch().slave_update(0, information, slave) MeshDedicatedDispatch().update('day night time', DayNightTime.select()[0].uuid) return json.dumps({'info': 'success'})
def update_responsible_wizard(): wizards = Person.select().where(Person.wizard == True) for old in wizards: old.wizard = False old.save() person = Person.get(Person.uuid == request.form['replacement']) person.wizard = True person.save() MeshDedicatedDispatch().update('person', person.uuid) return json.dumps({'info': 'success'})
def update_notification_message(): data = request.form preset, _ = MessagePreset.get_or_create(name=data['name'], defaults={'message': data['text']}) preset.message = data['text'] preset.save() if data['responsible'] is True: plant = Plant.get(Plant.uuid == data['plant']) plant.person.preset = preset plant.person.save() MeshDedicatedDispatch().update('message', preset.uuid) return json.dumps({'info': 'success'})
def update_plant_ranges(p_uuid): plant = Plant.get(Plant.uuid == p_uuid) sensor = Sensor.get(Sensor.name == request.form['sensor'].lower()) level_yellow = SensorSatisfactionLevel.get( SensorSatisfactionLevel.name_color == 'yellow') level_green = SensorSatisfactionLevel.get( SensorSatisfactionLevel.name_color == 'green') value_yellow = SensorSatisfactionValue.get( SensorSatisfactionValue.plant == plant, SensorSatisfactionValue.sensor == sensor, SensorSatisfactionValue.level == level_yellow) value_green = SensorSatisfactionValue.get( SensorSatisfactionValue.plant == plant, SensorSatisfactionValue.sensor == sensor, SensorSatisfactionValue.level == level_green) value_yellow.min_value = int(request.form.getlist('data[]')[0]) value_green.min_value = int(request.form.getlist('data[]')[1]) value_green.max_value = int(request.form.getlist('data[]')[2]) value_yellow.max_value = int(request.form.getlist('data[]')[3]) value_green.save() value_yellow.save() MeshDedicatedDispatch().update('plant satisfaction level', plant.uuid) if sensor.name == 'moisture' and plant.role != 'master': logger.info('executing slave update') information = { 'min': value_yellow.min_value, 'max': value_yellow.max_value } MeshDedicatedDispatch().slave_update(2, information, plant) return json.dumps({'info': 'success'})
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 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 message(m_uuid): # GET: select: message, full, default (full) if request.method == 'GET': message = MessagePreset.get(uuid=m_uuid) data, code = get_data(required=MESSAGE_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) selector = data['select'] collection = {} for selected in selector: if selected == 'full': output = model_to_dict(message) del output['id'] del output['created_at'] output['uuid'] = str(output['uuid']) else: output = {'message': message.message} 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=MESSAGE_POST, restrictive=True) if code == 400: return data_formatting(400) preset = MessagePreset.get(uuid=m_uuid) preset.message = data['message'] preset.name = data['heading'] preset.save() if data['person']: plant = Plant.get(uuid=data['plant']) plant.person.preset = preset plant.person.save() MeshDedicatedDispatch().update('message', preset.uuid) return data_formatting()
def create_plant_register(): plant = create_plant(request.form) MeshDedicatedDispatch().register(plant) return json.dumps({'name': plant.name, 'info': 'registered'})
def messages(): if request.method == 'GET': # GET: select: minimal, normal, detailed, extensive, default (normal) # GET: dict: Boolean data, code = get_data(required=MESSAGES_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) mode = data['dict'] selector = data['select'] selectable = ['minimal', 'normal', 'detailed', 'extensive'] messages = MessagePreset.select().dicts() collection = {} for selected in selector: output = [] for message in list(messages): used = [] if selected in selectable: used.append('uuid') if selected in selectable[1:]: used.append('name') if selected in selectable[2:]: used.append('created_at') if selected in selectable[3:]: used.append('message') data = [] if not mode else {} for use in used: if isinstance(message[use], UUID): message[use] = str(message[use]) if not mode: data.append(message[use]) else: data[use] = message[use] output.append(data) 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=MESSAGES_PUT, restrictive=True) if code == 400: return data_formatting(400) for message in MessagePreset.select(): if message.name == data['heading']: return data_formatting(304) msg = MessagePreset() msg.name = data['heading'] msg.message = data['message'] msg.save() if data['person']: plant = Plant.get(uuid=data['plant']) plant.person.preset = msg plant.person.save() MeshDedicatedDispatch().update('message', msg.uuid) return data_formatting()
def insert_data(self, data, mesh=True, prediction=True): """ dict of data: 'sensor': object of sensor 'value': value - float 'plant': current selected plant """ start = datetime.datetime.now() current_entries = SensorData.select()\ .where(SensorData.sensor == data['sensor'])\ .count() persistant = False data['value'] = round(data['value'], 2) sensor_db = SensorData() sensor_db.value = data['value'] sensor_db.plant = data['plant'] sensor_db.sensor = data['sensor'] sensor_db.persistant = False sensor_db.save() last_entry = self.get_second_last_entry(sensor_db, data['plant']) last_value = last_entry.value if last_entry is not None else data[ 'value'] offset = abs(data['value'] - last_value) if offset >= data['sensor'].persistant_offset: persistant = True elif current_entries > 6: persistant = self.persistant_evaluation(data['plant'], data['sensor']) sensor_db.persistant = persistant sensor_db.save() self.delete_non_persistant_overflow(data['sensor'], data['plant']) logger.debug('{} - {} persistant: {}'.format(data['plant'].name, data['sensor'].name, persistant)) if persistant: data['satisfaction'] = self.modify_sensor_status(data, mesh) self.mail_evaluation(data) if prediction: SensorDataForecast().run(data) if mesh: from mesh_network.dedicated import MeshDedicatedDispatch MeshDedicatedDispatch().new_data(data['sensor'], plant=data['plant']) if data['plant'].localhost: print('slave data') slaves = Plant.select().where( Plant.role == str(data['plant'].uuid)) slaves = list(slaves) for slave in slaves: print('slaved') MeshDedicatedDispatch().slave_data( slave, data['sensor']) logger.debug('time elapsed: {}'.format(datetime.datetime.now() - start)) return persistant
from mesh_network.dedicated import MeshDedicatedDispatch from models.plant import Plant target = Plant.get(name='gertrud') MeshDedicatedDispatch().remove('remove', target)
def plant(p_uuid): if request.method == 'GET': # GET: select: intervals, created_at, type/species, survived, location, full, default (full) data, code = get_data(required=PLANT_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) collection = {} selector = data['select'] for selected in selector: plant = list( Plant.select( Plant, fn.CAST( Clause(fn.strftime('%s', Plant.created_at), SQL('AS INT'))).alias('created_at')).where( Plant.uuid == p_uuid).dicts())[0] plant['uuid'] = str(plant['uuid']) if selected not in ['full', 'intervals', 'survived']: output = {selected: plant[selected]} elif selected in ['intervals']: output = { 'connection_lost': plant['connection_lost'], 'non_persistant': int(plant['persistant_hold'] * 5 / 60 / 24), 'notification': plant['interval'] } elif selected in ['survived']: difference = datetime.datetime.now( ) - datetime.datetime.fromtimestamp(plant['created_at']) output = float(difference.days + round((difference.seconds // 3600) / 24, 1)) else: output = plant if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output) elif request.method == 'POST': # POST: replace: name, type, location, ranges, responsible # POST: mode: add, reset, online, offline # POST: new: DATA data, code = get_data(required=PLANT_POST, restrictive=True) if code == 400: return data_formatting(400) keys = list(data.keys()) if data['mode'] == '': mode = 'add' if 'satisfaction' in keys else 'offline' else: mode = data['mode'].lower() plant = Plant.get(uuid=p_uuid) if data['name'] != '': plant.name = data['name'] if data['species'] != '': plant.species = data['species'] if data['location'] != '': plant.location = data['location'] if data['ranges']: try: sensor = Sensor.get(name=data['sensor']) except Exception: try: sensor = Sensor.get(uuid=data['sensor']) except Exception: return data_formatting(400) level_yellow = SensorSatisfactionLevel.get( SensorSatisfactionLevel.name_color == 'yellow') level_green = SensorSatisfactionLevel.get( SensorSatisfactionLevel.name_color == 'green') value_yellow = SensorSatisfactionValue.get( SensorSatisfactionValue.plant == plant, SensorSatisfactionValue.sensor == sensor, SensorSatisfactionValue.level == level_yellow) value_green = SensorSatisfactionValue.get( SensorSatisfactionValue.plant == plant, SensorSatisfactionValue.sensor == sensor, SensorSatisfactionValue.level == level_green) value_yellow.min_value = int(request.form.getlist('range[]')[0]) value_green.min_value = int(request.form.getlist('range[]')[1]) value_green.max_value = int(request.form.getlist('range[]')[2]) value_yellow.max_value = int(request.form.getlist('range[]')[3]) value_green.save() value_yellow.save() MeshDedicatedDispatch().update('plant satisfaction level', plant.uuid) if sensor.name == 'moisture' and plant.role != 'master': # logger.info('executing slave update') information = { 'min': value_yellow.min_value, 'max': value_yellow.max_value } MeshDedicatedDispatch().slave_update(2, information, plant) if data['responsible']: person = Person.get(email=data['email'], name=data['firstname']) plant.person = person plant.save() if data['satisfaction']: if mode == 'add': plant.sat_streak += 1 else: plant.sat_streak = 1 if data['alive']: counterpart = 'online' if mode == 'offline' else 'offline' status = PlantNetworkStatus.get(name=mode) counterpart = PlantNetworkStatus.get(name=counterpart) if plant.role == 'master': return data_formatting() status = PlantNetworkUptime.get(plant=plant, status=status) counterpart = PlantNetworkUptime.get(plant=plant, status=counterpart) if counterpart.current != 0: counterpart.current = 0 counterpart.save() status.current += 1 status.overall += 1 status.save() if data['notification']: _, _, hours = time_request_from_converter(data) plant.interval = int(round(hours)) if data['connection-lost']: _, minutes, _ = time_request_from_converter(data) plant.connection_lost = int(round(minutes)) if data['non-persistant']: _, minutes, _ = time_request_from_converter(data) plant.persistant_hold = int(round(minutes / 5)) plant.save() MeshDedicatedDispatch().update('plant', plant.uuid) return data_formatting()
def plants(): # GET: select: minimal, normal, detailed, extensive, master, satisfaction, default (normal) # GET: dict: Boolean if request.method == 'GET': data, code = get_data(required=PLANTS_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) selector = data['select'] mode = data['dict'] root_plants = Plant.select().dicts() collection = {} for selected in selector: plants = root_plants.where( Plant.role == 'master') if selected == 'master' else root_plants plants = list(plants) output = [] if selected not in ['satisfaction', 'sensorsatisfaction']: for plant in plants: used = [] if selected in [ 'minimal', 'normal', 'detailed', 'extensive', 'master' ]: used.append('uuid') if selected in [ 'normal', 'detailed', 'extensive', 'master' ]: used.append('name') if selected in ['detailed', 'extensive', 'master']: used.append('role') used.append('localhost') if selected in ['extensive', 'master']: used.append('active') data = [] if not mode else {} for use in used: if isinstance(plant[use], UUID): plant[use] = str(plant[use]) if not mode: data.append(plant[use]) else: data[use] = plant[use] output.append(data) elif selected in ['satisfaction', 'sensorsatisfaction']: output = {} sensors = Sensor.select() for plant in plants: host = None if plant['role'] != 'master': host = Plant.get(Plant.uuid == plant['role']) if selected == 'satisfaction': statuses = [] else: output[str(plant['uuid'])] = {} for sensor in sensors: target = Plant.get(uuid=plant['uuid']) if sensor.name not in slave_supported and host is not None: target = host status = SensorStatus.get( SensorStatus.sensor == sensor, SensorStatus.plant == target) if selected == 'satisfaction': inserted = 1 if status.level.label == 'threat': inserted = 3 elif status.level.label == 'cautioning': inserted = 2 statuses.append(inserted) else: if status.level.label not in output[str( plant['uuid'])]: output[str( plant['uuid'])][status.level.label] = [] output[str( plant['uuid'])][status.level.label].append({ 'name': sensor.name, 'uuid': str(sensor.uuid) }) if selected == 'satisfaction': 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 } if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output) else: # PUT: register: true data, code = get_data(required=PLANTS_PUT, restrictive=True) if code == 400: return data_formatting(400) register = data['register'] plants = list(Plant.select(Plant.ip == data['ip']).dicts()) discovered = MeshObject.get(ip=data['ip']) if plants.count() == 0: return data_formatting(304) plant = Plant() plant.name = data['name'] plant.location = data['location'] plant.species = data['species'] plant.interval = data['interval'] plant.person = Person.get(email=data['email']) plant.ip = data['ip'] plant.sat_streak = 0 if data['uuid'] != '': plant.uuid = data['uuid'] if data['persistant_hold'] != '': plant.persistant_hold = data['persistant_hold'] if not discovered.master: if data['role'] == '': master = Plant.get(localhost=True) else: master = Plant.get(uuid=data['role']) plant.role = str(master.uuid) plant.save() local_plant = Plant.get(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() if register: MeshDedicatedDispatch().register(plant) return data_formatting()
def person(r_uuid): # GET: select: full, default (full) # POST: replaceable: email, name, wizard # DELETE person = Person.get(uuid=r_uuid) if request.method == 'GET': data, code = get_data(required=PERSON_GET, restrictive=True, hardmode=True) if code == 400: return data_formatting(400) selector = data['select'] collection = {} for selected in selector: if selected == 'full': output = model_to_dict(person) del output['id'] del output['preset'] output['uuid'] = str(output['uuid']) if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output) elif request.method == 'POST': data, code = get_data(required=PERSON_POST, restrictive=True) if code == 400: return data_formatting(400) if data['name'] != '': person.name = data['name'] if data['email'] != '': person.email = data['email'] if data['wizard'] is not None: if data['wizard']: wizards = Person.filter(wizard=True) for old in wizards: old.wizard = False old.save() person.wizard = data['wizard'] person.save() MeshDedicatedDispatch().update('person', person.uuid) return data_formatting() else: if Person.select().where(Person.uuid == r_uuid).count() > 0: Person.get(uuid=r_uuid).delete_instance() else: return data_formatting(304) return data_formatting()