Пример #1
0
    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
Пример #2
0
 def post(self, controller_id, token):
     data = request.get_json()
     data_cleaned = controller_activate_schema.load(data)
     data_cleaned = data_cleaned.data
     stub = objects_pb2_grpc.ObjectServiceStub(self.object)
     # {
     #  "id":
     #  "name":
     #  "meta":
     #  "object_id":
     # }
     object_id = utils_pb2.ObjectId(object_id=data_cleaned["object_id"])
     controllerid = utils_pb2.ControllerId(controller_id=controller_id)
     uc = objects_pb2.ControllerActivate(
         id=controllerid,
         name=data_cleaned["name"],
         meta=data_cleaned["meta"],
         object_id=object_id,
     )
     try:
         rsp = stub.ActivateController(uc)
     except Exception as e:
         log.error("Error handling {}".format(str(e)))
         return NotFound("Not found error").get_message()
     rspr = Relations.collect_controller_info(rsp)
     sensors = Relations.collect_controller_relations(
         rsp, self.data_chan, self.stats_chan)
     sensors = Listed(sensors)
     kwargs = dict(controllers=Listed([
         rspr,
     ]), sensors=sensors)
     final = ObjList(**kwargs)
     return final.get_message()
Пример #3
0
 def delete(self, controller_id, token):
     stub = objects_pb2_grpc.ObjectServiceStub(self.object)
     uc = utils_pb2.ControllerId(controller_id=controller_id, )
     try:
         rsp = stub.DeactivateController(uc)
     except Exception as e:
         log.error("Error handling {}".format(str(e)))
         return NotFound("Not found error").get_message()
     rsp = Relations.collect_controller_info(rsp)
     return rsp.get_message()
Пример #4
0
 def get(self, controller_id, token):
     stats = {
         "code": 0,
         "msg": {
             "month": 0,
             "prev_month": 0,
             "prev_year": 0
         },
     }
     stub = stats_pb2_grpc.StatsServiceStub(self.stats_chan)
     id = utils_pb2.ControllerId(controller_id=controller_id)
     rsp = stub.GetControllerStat(id)
     stats["msg"]["month"] = rsp.current_month
     stats["msg"]["prev_month"] = rsp.prev_year_month
     stats["msg"]["prev_year"] = rsp.prev_year_average
     return stats, 200
Пример #5
0
 def get(self, _id, token):
     stub = objects_pb2_grpc.ObjectServiceStub(self.object)
     include = request.args.getlist("include")
     log.info("some shitty log {}".format(include))
     uu = utils_pb2.ControllerId(controller_id=_id)
     try:
         rsp = stub.GetControllerInfo(uu)
     except Exception as e:
         log.error("Error handling {}".format(str(e)))
         return NotFound("Not found error").get_message()
     sensors = Relations.collect_controller_relations(
         rsp, self.data_chan, self.stats_chan)
     sensors = Listed(sensors)
     kwargs = {}
     if include:
         if 'sensors' in include:
             kwargs['sensors'] = sensors
     else:
         kwargs = dict(sensors=sensors)
     return ObjList(**kwargs).get_message()
Пример #6
0
    def get(self, controller_id, token):
        stub = objects_pb2_grpc.ObjectServiceStub(self.object)
        log.info("some shitty log")
        uu = utils_pb2.ControllerId(controller_id=controller_id)
        try:
            rsp = stub.GetControllerInfo(uu)
        except Exception as e:
            log.error("Error handling {}".format(str(e)))
            return NotFound("Not found error").get_message()

        def sensor(ssr):
            rs = SensorInfo(ssr.id.sensor_id, ssr.name, None, None,
                            ssr.sensor_type, ssr.company)
            if ssr.HasField("deactivation_date_val"):
                rs.deactivation_date = ssr.deactivation_date_val
            if ssr.HasField("activation_date_val"):
                rs.activation_date = ssr.activation_date_val
            return rs

        uo = Listed([sensor(i) for i in rsp.sensors])
        return uo.get_message()
Пример #7
0
    def GetControllerStat(self, request, context):
        stub = objects_pb2_grpc.ObjectServiceStub(self.objects)
        logging.info("some shitty log")
        controller_id = request.controller_id
        uu = utils_pb2.ControllerId(controller_id=controller_id)
        try:
            rsp = stub.GetControllerInfo(uu)
        except Exception as e: 
            logging.error("Error handling {}".format(str(e)))
            return NotFound("Not found error").get_message()

        uo = [i.id for i in rsp.sensors]
        curmnth_sm, prev_curmnth_sm, y_c_month_sm = 0, 0, 0
        for i in uo:
            curmnth, prev_curmnth, y_c_month = self.get_sensor_stats(i)
            curmnth_sm += curmnth
            prev_curmnth_sm += prev_curmnth
            y_c_month_sm += y_c_month
        return stats_pb2.ControllerStat(current_month = curmnth_sm,
                                    prev_year_month=prev_curmnth_sm,
                                    prev_year_average=y_c_month_sm)
Пример #8
0
    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
Пример #9
0
    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