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 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 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_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_sensor_data_high_low(plant, sensor, configuration, target=None): mode = SensorData.created_at.asc( ) if configuration is False else SensorData.created_at.desc() dataset = SensorData.select(SensorData.value.alias('v'), fn.CAST(Clause(fn.strftime('%s', SensorData.created_at), SQL('AS INT'))).alias('t')) \ .where(SensorData.plant == plant) \ .where(SensorData.sensor == sensor) \ .order_by(mode) if target is not None: dataset = dataset.where(SensorData.created_at >= target) dataset = dataset.limit(1).dicts() if dataset.count() == 0: return None data = list(dataset)[0] return data
def plant_sensor(p_uuid, s_uuid): # GET: select: latest, prediction, data, current, range, extreme, message # GET: max: Boolean (extreme) # GET: ever: Boolean (extreme) # GET: backlog: Boolean (extreme) # GET: start: Integer (data) # GET: stop: Integer (data) # GET: count: Boolean (data) plant = Plant.get(uuid=p_uuid) try: sensor = Sensor.get(uuid=s_uuid) except Exception: sensor = Sensor.get(name=s_uuid) if plant.role != 'master' and sensor.name not in slave_supported: plant = Plant.get(uuid=plant.role) data, code = get_data(required=PLANT_SENSOR_GET, restrictive=True) if code == 400: return data_formatting(400) selector = data['select'] maximum = data['max'] backlog = data['backlog'] start = data['start'] stop = data['stop'] ever = data['ever'] collection = {} for selected in selector: if selected == 'timespan': start = datetime.datetime.min if start <= 0 else datetime.datetime.fromtimestamp( start) stop = datetime.datetime.max if stop >= 253402297200 else datetime.datetime.fromtimestamp( stop) if selected in [ 'latest', 'current', 'extreme', 'data', 'count', 'timespan' ]: data = 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.asc()) \ .dicts() elif selected in ['prediction']: data = SensorDataPrediction.select(SensorDataPrediction.value, fn.CAST(Clause(fn.strftime('%s', SensorDataPrediction.time), SQL('AS INT'))).alias('timestamp')) \ .where(SensorDataPrediction.plant == plant) \ .where(SensorDataPrediction.sensor == sensor) \ .order_by(SensorDataPrediction.created_at.asc()) \ .dicts() elif selected in ['range']: data = SensorSatisfactionValue.select() \ .where(SensorSatisfactionValue.plant == plant) \ .where(SensorSatisfactionValue.sensor == sensor) if selected in ['latest', 'current']: data = data.order_by(SensorData.created_at.desc()).limit(1) output = list(data)[0] elif selected == 'prediction': output = list(data) elif selected == 'range': output = {} for spectrum in data: output[spectrum.level.name_color] = { 'max': spectrum.max_value, 'min': spectrum.min_value } if spectrum.level.name_color == 'red': output[spectrum.level.name_color] = { 'max': sensor.max_value, 'min': sensor.min_value } elif selected == 'extreme': target = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()) if backlog and not ever: output = None while output is None: output = get_sensor_data_high_low(plant, sensor, maximum, target) target = target - datetime.timedelta(days=1) else: if ever: target = None output = get_sensor_data_high_low(plant, sensor, maximum, target) elif selected == 'count': output = data.count() elif selected == 'timespan': data = data.where(SensorData.created_at > start, SensorData.created_at < stop) output = list(data) else: data = data.order_by( SensorData.created_at.desc()).offset(start).limit(stop - start) output = list(data) if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output)
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()