def post(self, userId): data = json.loads(self.request.body.decode("utf-8")) sensor = Sensor(None, data['type'], 0, []) sensor.name = data['name'] sensor.gis = (data['lat'], data['lng']) sensor_id = self.__sensors_repo.create(sensor) self.__users_repo.add_sensor_id(userId, str(sensor_id)) self.set_status(201)
def __update_zwave_sensor(self, sensor: Sensor): new_value = self.__zwave_device.get_sensor_value(sensor.id) self.__logger.info("New value for sensor with id {0} is {1}: ".format( sensor.id, new_value)) if None is not new_value: sensor.value = round(new_value, 1) sensor.last_updated = calendar.timegm(datetime.now().timetuple()) self.__sensors_repo.set_sensor(sensor) dispatcher.send(SensorUpdateEvent.NAME, event=SensorUpdateEvent(sensor))
def register(self, jrequest, jresponse): assert isinstance(jrequest, JsonRpcRequest) assert isinstance(jresponse, JsonRpcResponse) jresponse.setId() request = jrequest.request assert isinstance(request, Request) if len(request.params) < 3: raise InvalidParams( "method=register&x=y&z=w&moduleId=mid&sensorId=sid&sensorName=mysensor where x is product field, y is product string, z is serial field, is serial string" ) assert request.params.items()[0][0] == "method" assert request.params.items()[0][1] == "register" (product_name_field, product_name_string) = request.params.items()[1] (serial_number_field, serial_number_string) = request.params.items()[2] assert isinstance(product_name_field, str) product_name_field = unicode(product_name_field) assert isinstance(product_name_field, unicode) assert isinstance(serial_number_field, str) serial_number_field = unicode(serial_number_field) assert isinstance(serial_number_string, unicode) try: product_name_data = Data.prepare(product_name_field, product_name_string) serial_number_data = Data.prepare(serial_number_field, serial_number_string) module_id_string = request.get("moduleId") assert len(module_id_string) > 0 sensor_id_string = request.get("sensorId") assert len(sensor_id_string) > 0 module_id_data = Data.prepare("moduleId", request.get("moduleId")) sensor_id_data = Data.prepare("sensorId", request.get("sensorId")) existing_sensor = Sensor.getByProductNameSerialNumberModuleIdSensorId( product_name_data, serial_number_data, module_id_data, sensor_id_data) raise EntityExists( "Equipment", { product_name_field: product_name_string, serial_number_field: serial_number_string, "moduleId": module_id_string, "sensorId": sensor_id_string }) except EntityNotFound: pass odenki_user = OdenkiUser.loadFromSession() assert isinstance(odenki_user, OdenkiUser) sensor_name = request.get("sensorName") if len(sensor_name) == 0: sensor_name = unicode(sensor_name) sensor_name_data = Data.prepare("sensorName", sensor_name) sensor = Sensor.create(product_name_data, serial_number_data, module_id_data, sensor_id_data, sensor_name_data, odenki_user) jresponse.addResult(sensor)
def put(self, id): self.set_status(200) sensor_data = json.loads(self.request.body.decode("utf-8")) self.__logging.info('Sensor data received: '.format( self.request.body.decode("utf-8"))) sensor = Sensor(id, sensor_data['type'], sensor_data['value'], None) event = Event(Event.TYPE_SENSOR_RECEIVED, sensor) self.__async_jobs.publish(event)
def callback(self, location: LocationEvent) -> None: current_coordonates = (location.get_latitude(), location.get_longitude()) distance_from_home = vincenty(self.__home_coordonates, current_coordonates).km phone_is_home = distance_from_home < self.HOME_RADIUS sensor = Sensor('phoneIsHome', Sensor.SensorType.PHONE_IS_HOME.value, False, phone_is_home) self.__sensors_repo.set_sensor(sensor)
def get_sensors(self) -> List[Sensor]: sensors_data = self.get(self.__REDIS_SENSORS_KEY) sensors = [] for sensor_data in sensors_data: # todo remove this hack after all sensors are updated last_updated = sensor_data[ 'last_updated'] if 'last_updated' in sensor_data else 0 sensor = Sensor(sensor_data['id'], sensor_data['type'], sensor_data['location'], sensor_data['value'], sensor_data['device_type'], last_updated) if 'properties' in sensor_data: sensor.properties = self.__get_sensor_properties( sensor_data['properties']) else: sensor.properties = self.__get_sensor_properties({}) sensors.append(sensor) return sensors
def listen(self, event: LocationEvent) -> None: current_coordonates = (event.get_latitude(), event.get_longitude()) distance_from_home = vincenty(self.__home_coordonates, current_coordonates).km phone_is_home = distance_from_home < self.HOME_RADIUS sensor = Sensor('phoneIsHome', Sensor.SensorType.PHONE_IS_HOME.value, False, phone_is_home, Sensor.DeviceType.ACTION.value, calendar.timegm(datetime.now().timetuple())) self.__sensors_repo.set_sensor(sensor)
def __get_sensor(self, sensor_components: list) -> Sensor: code, location, value = sensor_components if code not in self.SENSOR_TYPE_MAPPING: raise RuntimeError( 'Code with {0} not mapped with any sensor'.format(code)) if code == self.SENSOR_TYPE_SKIP: return None try: return Sensor(self.SENSOR_TYPE_MAPPING[code], float(value)) except ValueError as e: raise RuntimeError( 'Badly formatted sensor value: {0}, error: {1})'.format( value, e.message))
def register(self, jrequest, jresponse): assert isinstance(jrequest, JsonRpcRequest) assert isinstance(jresponse, JsonRpcResponse) jresponse.setId() request = jrequest.request assert isinstance(request, Request) if len(request.params) < 3: raise InvalidParams("method=register&x=y&z=w&moduleId=mid&sensorId=sid&sensorName=mysensor where x is product field, y is product string, z is serial field, is serial string") assert request.params.items()[0][0] == "method" assert request.params.items()[0][1] == "register" (product_name_field, product_name_string) = request.params.items()[1] (serial_number_field, serial_number_string) = request.params.items()[2] assert isinstance(product_name_field, str) product_name_field = unicode(product_name_field) assert isinstance(product_name_field, unicode) assert isinstance(serial_number_field, str) serial_number_field = unicode(serial_number_field) assert isinstance(serial_number_string, unicode) try: product_name_data = Data.prepare(product_name_field, product_name_string) serial_number_data = Data.prepare(serial_number_field, serial_number_string) module_id_string = request.get("moduleId") assert len(module_id_string) > 0 sensor_id_string = request.get("sensorId") assert len(sensor_id_string) > 0 module_id_data = Data.prepare("moduleId", request.get("moduleId")) sensor_id_data = Data.prepare("sensorId", request.get("sensorId")) existing_sensor = Sensor.getByProductNameSerialNumberModuleIdSensorId(product_name_data, serial_number_data, module_id_data, sensor_id_data) raise EntityExists("Equipment", {product_name_field:product_name_string, serial_number_field: serial_number_string, "moduleId":module_id_string, "sensorId":sensor_id_string}) except EntityNotFound: pass odenki_user = OdenkiUser.loadFromSession() assert isinstance(odenki_user, OdenkiUser) sensor_name = request.get("sensorName") if len(sensor_name) == 0: sensor_name = unicode(sensor_name) sensor_name_data = Data.prepare("sensorName", sensor_name) sensor = Sensor.create(product_name_data, serial_number_data, module_id_data, sensor_id_data, sensor_name_data, odenki_user) jresponse.addResult(sensor)
def get_sensors(self) -> List[Sensor]: sensors_data = self.get(self.__REDIS_SENSORS_KEY) sensors = [] for sensor_data in sensors_data: sensor = Sensor(sensor_data['id'], sensor_data['type'], sensor_data['location'], sensor_data['value']) if 'name' in sensor_data: sensor.name = sensor_data['name'] if 'communication_code' in sensor_data: sensor.communication_code = sensor_data['communication_code'] else: sensor.communication_code = (False, False) if 'last_updated' in sensor_data: sensor.last_updated = sensor_data['last_updated'] else: sensor.last_updated = 0 sensors.append(sensor) return sensors
def __process_sensor(self, sensor: Sensor, value): sensor.value = round(value, 3) sensor.last_updated = calendar.timegm(datetime.now().timetuple()) self.__sensors_repository.set_sensor(sensor) dispatcher.send(SensorUpdateEvent.NAME, event=SensorUpdateEvent(sensor))
"--days-behind", required=True, dest="days_behind", type=int, help="Days behind") args = vars(argparse.parse_args()) container = Container() datapoint_repository = container.datapoints_repository() start_date = datetime.today() - timedelta(days=args['days_behind']) for day_behind in range(args['days_behind'], 0, -1): start_date = datetime.today() - timedelta(days=day_behind) print('Calculating for date: ' + start_date.strftime('%m-%d-%Y')) request_url = config.darksky_url.format(int(start_date.timestamp())) response = requests.get(request_url) try: sensors_data = response.json()['hourly']['data'] except Exception: print("Error transforming to json") continue for sensor_data in sensors_data: for darksky_sensor_name, sensor_name in config.darksky_sensor_mapping.items( ): if darksky_sensor_name not in sensor_data: continue date = datetime.fromtimestamp(sensor_data['time']) sensor = Sensor(sensor_name, float(sensor_data[darksky_sensor_name])) datapoint_repository.update(DataSource.DARKSKY.value, date, [sensor])
def __process_sensor(self, sensor: Sensor, value): sensor.value = round(value, 3) self.__sensors_repository.set_sensor(sensor) self.__sensor_update_event.send(sensor)
import requests import config from model.Sensor import Sensor from container import Container from model.DataSource import DataSource argparse = argparse.ArgumentParser() argparse.add_argument("-d", "--days-behind", required=True, dest="days_behind", type=int, help="Days behind") args = vars(argparse.parse_args()) container = Container() datapoint_repository = container.datapoints_repository() start_date = datetime.today() - timedelta(days=args['days_behind']) for day_behind in range(args['days_behind'], 0, -1): start_date = datetime.today() - timedelta(days=day_behind) print('Calculating for date: ' + start_date.strftime('%m-%d-%Y')) for home_automation_sensor_name, sensor_name in config.home_automation_sensor_mapping.items(): literal_date = start_date.strftime('%m-%d-%Y') request = config.url.format(home_automation_sensor_name, literal_date, literal_date) response = requests.get(request) sensors_data = response.json()['data'] if not len(sensors_data) or len(sensors_data) < 130: continue for sensor_data in sensors_data: date = datetime.fromtimestamp(sensor_data['timestamp']) sensor = Sensor(sensor_name, float(sensor_data['value'])) datapoint_repository.update(DataSource.WEATHER_STATION.value, date, [sensor])