def _get_sensor_info(self, sensor_id): cur = self.__model.cursor() logging.info("Executing query") cur.execute( """SELECT * FROM SENSOR WHERE SENSOR.id = %s ;""", (sensor_id, )) rows = cur.fetchall() logging.info("Executed query") i = rows[0] sns = objects_pb2.SensorInfo( id=utils_pb2.SensorId(sensor_id=int(i[0]), ), name=i[1], controller_id=utils_pb2.ControllerId(controller_id=int(i[2]), ), status=i[4], sensor_type=i[6], company=i[7], ) if i[3] is None: sns.activation_date_null = True else: sns.activation_date_val = int(time.mktime(i[3].timetuple())) if i[5] is None: sns.deactivation_date_null = True else: sns.deactivation_date_val = int(time.mktime(i[5].timetuple())) return sns
def delete(self, _id, token): stub = objects_pb2_grpc.ObjectServiceStub(self.object) uc = utils_pb2.SensorId( sensor_id=_id, ) try: stub.DeleteSensor(uc) except Exception as e: log.error("Error handling {}".format(str(e))) return NotFound("Not found error").get_message() return DeleteOk("Sensor deleted").get_message()
def get(self, sensor_id, token): # data = { "code": 0, "msg": [] } stub = data_pb2_grpc.DataServiceStub(self.data_chan) id = utils_pb2.SensorId(sensor_id=sensor_id) parser = reqparse.RequestParser() parser.add_argument("from") parser.add_argument("limit") args = parser.parse_args() frm = args["from"] limit = args["limit"] lim = None if limit: if isinstance(limit, list) and len(limit) > 1: return InvalidRequest("Too many values to limit").get_message() try: lim = data_pb2.LimitQuery(limit=int(limit)) except ValueError: return InvalidRequest("Failed to parse \"limit\"").get_message() else: lim = data_pb2.LimitQuery(limit=0) if frm: if isinstance(frm, list) and len(frm) > 1: return InvalidRequest("too many values to \"from\"").get_message() try: dt = datetime.datetime.strptime(frm, "%Y-%m-%dT%H:%M:%S") frm = timeq_pb2.TimeQuery(timestamp=int(time.mktime(dt.timetuple()))) except ValueError: return InvalidRequest("Failed to parse \"from\" date time").get_message() else: frm = timeq_pb2.TimeQuery(timestamp_null=True) log.debug("from is {}".format(str(frm))) mq = data_pb2.TimeLimitedQuery(start=frm, limit=lim, sensor_id=id) data_resp = [] for i in stub.GetLimitedData(mq): # TODO: перерделать на нормальный подход val = None if i.value.HasField("strvalue"): val = i.value.strvalue if i.value.HasField("doublevalue"): val = i.value.doublevalue dt = { "sensor_id": sensor_id, "date": datetime.datetime.fromtimestamp(i.timestamp).strftime('%Y-%m-%d %H:%M:%S'), "value": val, "hash": base64.b64encode(i.hash).decode('UTF-8') } data_resp.append(dt) data["msg"] = data_resp return data, 200
def get(self, sensor_id, token=None): data = { "code": 0, "msg": [] } stub = data_pb2_grpc.DataServiceStub(self.data_chan) id = utils_pb2.SensorId(sensor_id=sensor_id) parser = reqparse.RequestParser() parser.add_argument("from") parser.add_argument("to") args = parser.parse_args() frm = args["from"] to = args["to"] if to: if isinstance(to, list) and len(to) > 1: return InvalidRequest("too many values to \"to\"").get_message() try: to = datetime.datetime.strptime(to, "%Y-%m-%dT%H:%M:%S") to = timeq_pb2.TimeQuery(timestamp=int(time.mktime(to.timetuple()))) except ValueError: return InvalidRequest("Failed to parse \"to\" date time").get_message() else: to = timeq_pb2.TimeQuery(timestamp_null=True) if frm: if isinstance(frm, list) and len(frm) > 1: return InvalidRequest("too many values to \"from\"").get_message() try: frm = datetime.datetime.strptime(frm, "%Y-%m-%dT%H:%M:%S") frm = timeq_pb2.TimeQuery(timestamp=int(time.mktime(frm.timetuple()))) except ValueError: return InvalidRequest("Failed to parse \"from\" date time").get_message() else: frm = timeq_pb2.TimeQuery(timestamp_null=True) mq = data_pb2.MeterQuery(low=frm, hight=to, sensor_id=id) data_resp = [] for i in stub.GetSensorData(mq): # TODO: перерделать на нормальный подход val = None if i.value.HasField("strvalue"): val = i.value.strvalue if i.value.HasField("doublevalue"): val = i.value.doublevalue dt = { "sensor_id": sensor_id, "date": datetime.datetime.fromtimestamp(i.timestamp).strftime('%Y-%m-%d %H:%M:%S'), "value": val, "hash": base64.b64encode(i.hash).decode('UTF-8') } data_resp.append(dt) data["msg"] = data_resp return data, 200
def get(self, sensor_id, token=None): stats = { "code": 0, "msg": { "month": 0, "prev_month": 0, "prev_year": 0 }, } stub = stats_pb2_grpc.StatsServiceStub(self.stats_chan) id = utils_pb2.SensorId(sensor_id=sensor_id) rsp = stub.GetSensorStat(id) stats_resp = { "month": rsp.current_month, "prev_month": rsp.prev_year_month, "prev_year": rsp.prev_year_average, } stats["msg"] = stats_resp return stats, 200
def GetUsersInfo(self, request, context): logging.info("starting to process") cur = self.__model.cursor() user_id = request.user_id logging.info("Executing query user id = {}".format(user_id)) cur.execute( """SELECT * FROM OBJECTS LEFT JOIN CONTROLLERS ON CONTROLLERS.object_id = OBJECTS.id LEFT JOIN SENSOR ON SENSOR.controller_id = CONTROLLERS.id WHERE user_id = %s ;""", (user_id, )) rows = cur.fetchall() logging.info("Executed query") logging.info(rows) uinf = objects_pb2.UserInfoH( id=utils_pb2.UserId(user_id=int(user_id), ), objects=[], ) controllers = {} controllers_l = defaultdict(list) sensors = {} objects = {} objects_l = defaultdict(list) for i in rows: logging.debug("loaded: {}".format(i)) if (i[0] not in objects) and (i[0] is not None): objects[i[0]] = objects_pb2.ObjectInfo( id=utils_pb2.ObjectId(object_id=int(i[0]), ), name=i[1], user_id=utils_pb2.UserId(user_id=int(i[2]), ), address=i[3], controllers=[]) if i[0] is not None: obct = objects[i[0]] if not i[0] in uinf.objects: logging.debug("object found") if (i[4] not in controllers) and (i[4] is not None): ctrl = objects_pb2.ControllerInfo( id=utils_pb2.ControllerId(controller_id=int(i[4]), ), name=i[5], object_id=utils_pb2.ObjectId(object_id=int(i[6]), ), meta=i[7], status=i[9], mac=i[10], controller_type=i[12], sensors=[]) if i[8] is None: ctrl.activation_date_null = True else: ctrl.activation_date_val = int( time.mktime(i[8].timetuple())) if i[11] is None: ctrl.deactivation_date_null = True else: ctrl.deactivation_date_val = int( time.mktime(i[11].timetuple())) controllers[i[4]] = ctrl if (i[4] is not None) and (i[0] is not None): ctrl = controllers[i[4]] if not ctrl in objects_l[i[0]]: logging.debug("controller found") objects_l[i[0]].append(ctrl) if (i[13] not in sensors) and (i[13] is not None): ssr = objects_pb2.SensorInfo( id=utils_pb2.SensorId(sensor_id=int(i[13]), ), name=i[14], controller_id=utils_pb2.ControllerId(controller_id=int( i[15]), ), status=i[17], sensor_type=i[19], company=i[20]) if i[16] is None: ssr.activation_date_null = True else: ssr.activation_date_val = int( time.mktime(i[16].timetuple())) if i[18] is None: ssr.deactivation_date_null = True else: ssr.deactivation_date_val = int( time.mktime(i[18].timetuple())), sensors[i[13]] = ssr if (i[13] is not None) and (i[4] is not None): snsor = sensors[i[13]] if not snsor in controllers_l[i[4]]: logging.debug("sensor found") controllers_l[i[4]].append(snsor) for ctr, vals in controllers_l.items(): controllers[ctr].sensors.extend(vals) for ob, vals in objects_l.items(): objects[ob].controllers.extend(vals) uinf.objects.extend(objects.values()) logging.debug("ending") logging.debug(MessageToJson(uinf)) return uinf
def _get_controller_info(self, controller_id): cur = self.__model.cursor() logging.info("Executing query") cur.execute( """SELECT * FROM CONTROLLERS LEFT JOIN SENSOR ON SENSOR.controller_id = CONTROLLERS.id WHERE CONTROLLERS.id = %s ;""", (controller_id, )) rows = cur.fetchall() logging.info("Executed query") i = rows[0] object_id = None if i[2] is not None: object_id = utils_pb2.ObjectId(object_id=int(i[2]), ) ctrl = objects_pb2.ControllerInfo(id=utils_pb2.ControllerId( controller_id=int(i[0]), ), name=i[1], object_id=object_id, meta=i[3], status=i[5], mac=i[6], controller_type=i[8], sensors=[]) if i[4] is None: ctrl.activation_date_null = True else: ctrl.activation_date_val = int(time.mktime(i[4].timetuple())) if i[7] is None: ctrl.deactivation_date_null = True else: ctrl.deactivation_date_val = int(time.mktime(i[11])) sensors = {} snsor = None for i in rows: logging.debug("loaded: {}".format(i)) if (i[9] not in sensors) and (i[9] is not None): ssr = objects_pb2.SensorInfo( id=utils_pb2.SensorId(sensor_id=int(i[9]), ), name=i[10], controller_id=utils_pb2.ControllerId(controller_id=int( i[11]), ), status=i[13], sensor_type=i[15], company=i[16]) if i[12] is None: ssr.activation_date_null = True else: ssr.activation_date_val = int( time.mktime(i[12].timetuple())) if i[14] is None: ssr.deactivation_date_null = True else: ssr.deactivation_date_val = int( time.mktime(i[14].timetuple())) sensors[i[13]] = ssr if i[13] is not None: snsor = sensors[i[13]] if snsor is not None: ctrl.sensors.extend([ snsor, ]) return ctrl
def get_sensor_info(self, sensor_id): sid = utils_pb2.SensorId( sensor_id=sensor_id, ) return self._objects_stub.GetSensorInfo(sid)
def get_sensor_info(self, data): sid = utils_pb2.SensorId(sensor_id=data["sensor_id"], ) return self._objects_stub.GetSensorInfo(sid)