def sensor(s_uuid): # GET: select: range, unit, full, default (full) try: sensor = Sensor.get(uuid=s_uuid) except Exception: sensor = Sensor.get(name=s_uuid) data, code = get_data(required=SENSOR_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(sensor) del output['id'] output['uuid'] = str(output['uuid']) elif selected == 'range': output = {'max_value': sensor.max_value, 'min_value': sensor.min_value} else: output = {selected: model_to_dict(sensor)[selected]} if len(selector) > 1: collection[selected] = output if len(collection.keys()) != 0: output = collection return data_formatting(data=output)
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_sensor_overall(s_uuid): sensor = Sensor.get(Sensor.uuid == s_uuid) sensor = model_to_dict(sensor) del sensor['id'] sensor['uuid'] = str(sensor['uuid']) return json.dumps(sensor)
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_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 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_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 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_plant_sensor_data_high_today(sensor, p_uuid, mode, if_no_data_days_before): 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)) target = datetime.datetime.combine(datetime.date.today(), datetime.datetime.min.time()) if if_no_data_days_before == 'yes': data = None while data is None: data = get_sensor_data_high_low(plant, sensor, configuration, target) target = target - datetime.timedelta(days=1) elif if_no_data_days_before == 'no': data = get_sensor_data_high_low(plant, sensor, configuration, target) return json.dumps(data)
def get_plant_sensor_range(p_uuid, sensor): sensor = Sensor.get(Sensor.name == sensor) plant = Plant.get(Plant.uuid == p_uuid) ranges = SensorSatisfactionValue.select() \ .where(SensorSatisfactionValue.plant == plant) \ .where(SensorSatisfactionValue.sensor == sensor) output = {} for spectrum in ranges: 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 } return json.dumps(output)
def get(self): sensors = self.data['sensor'] plant = Plant.select().where(Plant.localhost == True)[0] for sensor in sensors: sensors[sensor]['raw'] = Sensor.get(Sensor.name == sensor) sensors[sensor]['name'] = sensors[sensor]['raw'].name unit = sensors[sensor]['raw'].unit sensors[sensor]['unit'] = re.sub(r'(?!%)\W+', '', unit)[0] order = SensorData.created_at.desc() r_sen = sensors[sensor]['raw'] sensors[sensor]['value'] = SensorData.select()\ .where(SensorData.plant == plant)\ .where(SensorData.sensor == r_sen)\ .order_by(order)[0].value self.data['sensor'] = sensors return self
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 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 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 get_sensor_unit(sensor): sensor = Sensor.get(Sensor.name == sensor) return json.dumps({'unit': sensor.unit})
def get_sensor_range(sensor): sensor = Sensor.get(Sensor.name == sensor) return json.dumps({'max': sensor.max_value, 'min': sensor.min_value})
import pymongo from pymongo import MongoClient from models.sensor import SensorData, Sensor from models.plant import Plant from bson import ObjectId import datetime client = MongoClient('bilalmahmoud.de') db = client.pot # for asset in SensorData.select(): # asset.delete_instance() temperature = Sensor.get(Sensor.name == 'temperature') humidity = Sensor.get(Sensor.name == 'humidity') light = Sensor.get(Sensor.name == 'light') moisture = Sensor.get(Sensor.name == 'moisture') plant = Plant.get(Plant.name == 'marta') i = 0 for asset in db.SensorData.find({ "_id": { '$gt': ObjectId("57e954100000000000000000") } }).sort("_id", pymongo.ASCENDING): if asset['p'] == 'm': if asset['s'] == 't': sensor = temperature elif asset['s'] == 'h': sensor = humidity
def run(busnumber=1, tsl_adress=0x39): ambiance_lowbyte = 0 ambiance_highbyte = 0 ambiance = 0 ir_lowbyte = 0 ir_highbyte = 0 ir = 0 ratio = 0 lux = 0 i2c_bus = smbus.SMBus(busnumber) i2c_bus.write_byte_data(tsl_adress, 0x80, 0x03) i2c_bus.write_byte_data(tsl_adress, 0x81, 0x12) # 16X gain proceeding = False pointer = 0 while not proceeding: ambiance_lowbyte = i2c_bus.read_byte_data(tsl_adress, 0x8c) ambiance_highbyte = i2c_bus.read_byte_data(tsl_adress, 0x8d) ambiance = (ambiance_highbyte * 256) + ambiance_lowbyte ir_lowbyte = i2c_bus.read_byte_data(tsl_adress, 0x8e) ir_highbyte = i2c_bus.read_byte_data(tsl_adress, 0x8f) ir = (ir_highbyte * 256) + ir_lowbyte if (ambiance >= 65535 or ir >= 65535) and pointer == 0: i2c_bus.write_byte_data(tsl_adress, 0x81, 0x02) # 1X gain else: proceeding = True pointer += 1 if pointer > 1: ambiance *= 16 # scaling 1X to 16X ir *= 16 # scaling 1X to 16X if ambiance == 0: ratio = 0 else: ratio = ir / float(ambiance) # calculations according to the datasheet if 0 < ratio <= 0.50: lux = 0.0304 * ambiance - 0.062 * ambiance * (ratio**1.4) elif 0.50 < ratio <= 0.61: lux = 0.0224 * ambiance - 0.031 * ir elif 0.61 < ratio <= 0.80: lux = 0.0128 * ambiance - 0.0153 * ir elif 0.80 < ratio <= 1.3: lux = 0.00146 * ambiance - 0.00112 * ir else: lux = 0 plant = Plant.get(localhost=True) toolchain = ToolChainSensor() light = { 'sensor': Sensor.get(name='light'), 'plant': plant, 'value': lux } if toolchain.insert_data(light): toolchain.set_hardware(light)
'(206-208) time elapsed: {}'.format(datetime.datetime.now() - between)) if sd.count() > 1000: between = datetime.datetime.now() data['prediction'] = self.predict(data, sd) logger.debug( '(210-212) time elapsed: {}'.format(datetime.datetime.now() - between)) between = datetime.datetime.now() self.insert_database(data) logger.debug( '(213-215) time elapsed: {}'.format(datetime.datetime.now() - between)) if __name__ == '__main__': from models.plant import Plant from models.sensor import Sensor data = {} data['plant'] = Plant.get(Plant.name == 'marta') data['sensor'] = Sensor.get(Sensor.name == 'light') print(data['sensor']) SensorDataForecast().run(data) print('done') data['sensor'] = Sensor.get(Sensor.name == 'humidity') SensorDataForecast().run(data) print('done') data['sensor'] = Sensor.get(Sensor.name == 'moisture') SensorDataForecast().run(data)
print('doing some other stuff') hardware_collection = { 'led_traffic_light': all_sensors, 'led_bar': ['moisture'], 'display': ['temperature', 'humidity'], 'mailer': all_sensors, 'water_pump': ['moisture'] } for hardware, values in hardware_collection.items(): current = SensorHardware(label=hardware, function='execute_' + hardware) current.save() for sensor in values: sensor = Sensor.get(name=sensor) c = SensorHardwareConnector(hardware=current, sensor=sensor) c.save() def isfloat(text): try: return float(input(text)) except: print('try again') return isfloat(text) for level in ['threat', 'cautioning', 'optimum']: if SensorSatisfactionLevel.select()\ .where(SensorSatisfactionLevel.label == level)\
def __init__(self): self.sensor = Sensor.get(name='moisture') self.plant = Plant.get(localhost=True) data = {'plant': self.plant, 'sensor': self.sensor} self.collection = ToolChainSensor().get_sensor_satification_value(data)
if predicted.count() == 0: data, saved = self.__retrieve_data(target, source, sensor) data = data.order_by(SensorData.created_at.asc()) forecast = SensorDataForecast() information = {'plant': target, 'sensor': sensor} information['prediction'] = forecast.predict(information, data) forecast.insert_database(information) predicted = SensorDataPrediction.select().where(SensorDataPrediction.plant == target, SensorDataPrediction.sensor == sensor) \ .order_by(SensorDataPrediction.created_at.asc()) \ .limit(1) for sample in predicted: if sample.time <= datetime.datetime.now(): released = True ToolChainSensor().insert_data({'sensor': sensor, 'plant': target, 'value': sample.value}, prediction=False) logger.info('inserting') # insert hardware? -- test if DUMMYPLANT hardware? sample.delete_instance() else: released = False logger.info('too early to insert') return released if __name__ == '__main__': from models.sensor import Sensor PlantSimulate().run(Plant.get(Plant.name == 'thomas'), Sensor.get(Sensor.name == 'temperature'))