Ejemplo n.º 1
0
    def func(self, data):
        task_id = data['task_id']
        status = data['status']
        # success_list = data.get('success_list', [])
        # fail_list = data.get('fail_list', [])
        try:
            ret = gw.set_task_status(task_id, status)
            if not ret:
                raise Exception()
            with open("/tmp/success") as successfile:
                content = successfile.read()
                success_list = content.split('\n')
            with open("/tmp/fail") as failfile:
                content = failfile.read()
                fail_list = content.split('\n')
        except Exception as e:
            LOG.error(e.__str__())
            return

        # 上传执行状态
        send_data = {
            "task_id": task_id,
            "task_status": status,
            "success_list": success_list,
            "fail_list": fail_list
        }
        self.upload(send_data)
Ejemplo n.º 2
0
 def send_service(self, service_name, data, need_resp=False):
     path = ""
     for service in self.services:
         if service_name == service[0]:
             path = service[1]
             break
     if path:
         try:
             self.__client = socket(family=AF_UNIX)
             self.__client.connect(path)
             content = json.dumps(data)
             self.__client.send(content.encode('utf-8'))
             if need_resp:
                 resp = self.__client.recv(1024 * 1024)
                 if not resp:
                     raise Exception()
                 resp = resp.decode('utf-8')
                 LOG.info(resp)
                 content = json.loads(resp, encoding='utf-8')
         except Exception as e:
             LOG.error(e.__repr__())
             content = {'status': 500, 'msg': e.__repr__()}
         finally:
             self.__client.close()
             return content
Ejemplo n.º 3
0
    def post(self, cmd):
        try:
            request = self.request.body.decode('utf-8')
            request = json.loads(request)
            body = request["d"]
            if cmd == 'group':
                pass
            elif cmd == 'white_list':
                ret = gw.create_whitelist(body['url'], body['md5'])
                if ret:
                    LOG.info("white list create success")
                    resp_status = "ok"
                    resp_data = {"result": "ok"}
            elif cmd == 'check_code':
                gw.set_auth_key(body['check_code'])
                resp_status = "ok"
                resp_data = {"result": "ok"}

        except EpdException as e:
            LOG.error(e.__repr__())
            resp_status = "err",
            resp_data = {"msg": e.message}
        finally:
            upload = uplink.Upload()
            resp = {
                "id": request['id'],
                "from": request['from'],
                "status": resp_status,
                "command": request['command'],
                "d": resp_data
            }
            upload.send(resp, topic="dma/cmd/resp")
Ejemplo n.º 4
0
 def get_whitelist(self):
     try:
         with open(self.white_list_url, 'rb') as whitelistfile:
             content = whitelistfile.read()
             self.__whitelist = set(content.decode('utf-8').split('\n'))
             hash_obj = hashlib.md5()
             hash_obj.update(content)
             return str(hash_obj.hexdigest())
     except Exception as e:
         LOG.error("get white list failed: %s" % e.__str__())
         return ""
Ejemplo n.º 5
0
 def try_handler(self, service_name, data):
     ret = dl.send_service(service_name, data, need_resp=True)
     if ret['status'] != 'ok':
         if self.try_count:
             t = threading.Timer(5,
                                 self.try_handler,
                                 args=(service_name, data))
             t.start()
             self.try_count = self.try_count - 1
         else:
             LOG.error('%s service lost connection', service_name)
Ejemplo n.º 6
0
 def __init__(self, name):
     try:
         self.__name = name
         self.__config = ConfigParser()
         self.__config.read(os.path.join(PATH, "%s.ini" % name))
         for k, v in self.__config.items(name):
             self.__setattr__(k, v)
     except Exception as e:
         LOG.error(e.__repr__())
         self.__config.add_section(self.__name)
         self.save()
Ejemplo n.º 7
0
 def send(self, url, data):
     try:
         data = json.dumps(data).encode('utf-8')
         LOG.info(data)
         request = urllib.request.Request(url,
                                          data=data,
                                          headers={'token': token})
         resp = urllib.request.urlopen(request)
         content = resp.read().decode('utf-8')
         LOG.info("result:" + content)
         content = json.loads(content)
         return content
     except Exception as e:
         LOG.error(e.__str__())
Ejemplo n.º 8
0
 def handle(self):
     try:
         data = self.request.recv(1024)
         data = data.decode('utf-8')
         data = json.loads(data, encoding='utf-8')
         LOG.info("downlink recv: %s", data)
         HandleClass = self.route(data)
         handler = HandleClass()
         send_data = handler.func(data)
         if isinstance(send_data, dict):
             content = json.dumps(send_data)
             LOG.info("downlink send: %s", content)
             self.wfile.write(content.encode('utf-8'))
     except Exception as e:
         LOG.error('%s exception: data: %s', e.__str__(), str(data))
Ejemplo n.º 9
0
 def interval_timing(self):
     try:
         next_time = 3600
         host = self.get('server', 'host')
         resp = urllib.request.urlopen(
             "http://{}/iotgw/api/v1/now".format(host))
         content = resp.read()
         serverTime = json.loads(content.decode('utf-8'), encoding='utf-8')
         tm = localtime(serverTime['data']['unixNano'] / 1000000000)
         os.system(
             "date -s \"{:04}-{:02}-{:02} {:02}:{:02}:{:02}\"".format(*tm))
     except Exception as e:
         next_time = 300  # 获取失败后5分钟之后再尝试
         LOG.error(e.__str__())
     finally:
         timer = threading.Timer(next_time, self.interval_timing)
         timer.start()
Ejemplo n.º 10
0
    def send(self, payload, topic='pc_test', wait_event=None, need_wait=False, cache=False):
        if cache:
            url = r'http://127.0.0.1:7788/mqtt/publish/offlinecache'
        else:
            url = r'http://127.0.0.1:7788/mqtt/publish'
        data = {}
        data['topic'] = topic
        data['payload'] = payload

        try:
            params = json.dumps(data).encode('utf-8')
            LOG.info(params)
            request = urllib.request.Request(url, data=params, headers={'token':token})
            resp = urllib.request.urlopen(request)
            content = resp.read().decode('utf-8')
            LOG.info("result:"+content)
        except Exception as e:
            LOG.error(e.__str__())
Ejemplo n.º 11
0
    def post(self, cmd):
        try:
            request = self.request.body.decode('utf-8')
            request = json.loads(request)
            body = request["d"]
            if cmd == 'group':
                raise Exception("%s cmd not found" % cmd)
            elif cmd == 'white_list':
                ret = gw.create_whitelist(body['url'], body['md5'])
                if ret:
                    LOG.info("white list create success")
                    resp_status = "ok"
                    resp_data = {"result": "ok"}
                else:
                    raise Exception("white list create failed")
            elif cmd == 'check_code':
                gw.set_auth_key(body['check_code'])
                resp_status = "ok"
                resp_data = {"result": "ok"}
            elif cmd == 'interval':
                gw.set_interval_time(body['interval'])
                resp_status = "ok"
                resp_data = {"result": "ok"}
            else:
                raise Exception("%s cmd not found" % cmd)

        except Exception as e:
            LOG.error(e.__repr__())
            resp_status = "err",
            resp_data = {"msg": e.__str__()}
        finally:
            upload = uplink.Upload()
            url = r'http://127.0.0.1:7788/mqtt/publish/offlinecache'
            resp = {
                "id": request.get('id'),
                "from": request.get('from'),
                "status": resp_status,
                "command": request.get('command'),
                "d": resp_data
            }
            data = {'topic': "dma/cmd/resp", 'payload': resp}
            upload.send(url, data)
Ejemplo n.º 12
0
 def func(self, data):
     task_id = data['task_id']
     status = data['status']
     send_data = {}
     try:
         ret = gw.set_task_status(task_id, status)
         if not ret:
             raise Exception('task %d not exist' % task_id)
         upload_data = {}
         if status == 4:
             with open("/tmp/success") as successfile:
                 content = successfile.read()
                 success_list = content.split('\n')
             # with open("/tmp/fail") as failfile:
             #     content = failfile.read()
             #     fail_list = content.split('\n')
             os.unlink('/tmp/success')  # 删除文件
             # os.unlink('/tmp/fail')
             upload_data['success_list'] = list(set(success_list))
             upload_data['failed_list'] = gw.get_failed_list(success_list)
         elif status == 3:
             # 保存待执行列表到文件
             gw.save_pending_list()
         else:
             pass
         # 上传执行状态
         upload_data['task_id'] = task_id
         upload_data['status'] = status
         self.upload('gateway/report/task/status', upload_data)
         send_data['status'] = 'ok'
     except Exception as e:
         LOG.error(e.__str__())
         send_data['status'] = 'error'
         send_data['msg'] = e.__str__()
     finally:
         return send_data
Ejemplo n.º 13
0
    def func(self, request):
        try:
            send_data = dict()
            upload_data = None
            device_id = request['device_id']
            firmware = request.get('firmware', None)
            data_id = request.get('data_id', "0")
            interval = request.get('interval', None)
            if firmware:
                # 注册上报
                LOG.info("%s register", device_id)
                upload_data = {
                    "d": [{
                        "nid": device_id,
                        "d": {
                            "firmware": firmware
                        }
                    }]
                }
                topic = 'dma/report/periph/reg'
            elif data_id:
                # 心跳上报
                # 准备上报数据
                upload_data = {
                    "d": [{
                        "nid": device_id,
                        "d": {
                            "image_data_id": int(data_id),
                            "interval": request['interval'],
                            "battery": request['battery']
                        }
                    }]
                }
                topic = 'dma/report/periph'
                ts = gw.get_task_status()
                LOG.info("task status: %s", ts)
                if ts in ('0', '4', '5'):  # 没有任务或任务已结束
                    data = {
                        'nid': device_id,
                        'image_data_id': int(data_id),
                        # 'image_data_id': int(gw.get_data_id()),
                        'sn': gw.get_gw_id()
                    }
                    LOG.info("start query")
                    host, port = gw.get_server_url()
                    resp = self.query_task(
                        'http://{}/iotgw/api/v1/tasks/gwtasks/assign'.format(
                            host), data)
                    LOG.info("get response")
                    if resp:
                        # 应答成功,保存任务状态,下发时间,下载任务
                        if resp['status'] != 'ok':
                            raise Exception("get task error")
                        data = resp['data']
                        ret = gw.create_task(data['task_id'], data['image_data_id'], data['image_data_url'], \
                                data['image_data_md5'], data['iot_dev_list_md5'], data['iot_dev_list_url'], \
                                data['scheduled_start_time'], data['scheduled_end_time'])
                        if ret:
                            start_time, end_time = gw.get_task_time()
                            send_data['task_id'] = gw.get_task_id()
                            send_data['data_id'] = gw.get_data_id()
                            send_data['start_time'] = start_time
                            send_data['end_time'] = end_time

                            # 向serial发送任务开始命令
                            task_start = {
                                "cmd": "task",
                                "method": "create",
                                "task_id": send_data['task_id'],
                                "data_id": int(send_data['data_id']),
                                "start_time": send_data['start_time'],
                                "end_time": send_data['end_time']
                            }
                            ret = dl.send_service('serial',
                                                  task_start,
                                                  need_resp=True)
                            if ret['status'] != 'ok':
                                gw.set_try_data('serial', task_start)

                            # 添加待执行表
                            gw.create_pending_list()
                            gw.add_pending_list(device_id)
                        else:
                            # 创建失败上报
                            pass
                    else:
                        raise Exception("server no response")
                elif ts in ('1', '2'):
                    ret = gw.is_in_executelist(device_id, data_id)
                    if ret:
                        start_time, end_time = gw.get_task_time()
                        send_data['task_id'] = gw.get_task_id()
                        send_data['data_id'] = int(gw.get_data_id())
                        send_data['start_time'] = start_time
                        send_data['end_time'] = end_time
                        gw.add_pending_list(device_id)
                else:
                    # 其他情况处理
                    pass
                # 更新唤醒周期
                send_data['status'] = 'ok'
                interval_time = gw.get_interval_time()
                if interval_time != request['interval']:
                    send_data['interval'] = interval_time
            else:
                raise Exception("request param invalid")
        except Exception as e:
            send_data['status'] = 'error'
            LOG.error(e.__repr__())
        finally:
            if upload_data:
                self.upload(topic, upload_data)
            return send_data
Ejemplo n.º 14
0
    def post(self, cmd):
        try:
            request = self.request.body.decode('utf-8')
            request = json.loads(request)
            body = request['d']
            if cmd == 'create':
                pass
                # ret = gw.create_task(body['task_id'], body['image_data_id'], body['image_data_url'], \
                #     body['image_data_md5'], body['iot_dev_list_md5'], body['iot_dev_list_url'], \
                #     body['start_time'], body['end_time'])
                # if ret:
                #     data = {
                #         "cmd":"task",
                #         "method":"create",
                #         "task_id":body['task_id'],
                #         "data_id":body['image_data_id'],
                #         "start_time":body['start_time'],
                #         "end_time":body['end_time']
                #     }
                #     ret = dl.send_service('serial', data, need_resp=True)
                #     if ret['status'] != 'ok':
                #         gw.set_try_data('serial', data)
                #     # raise HTTPError(200)
                #     status = 'ok'
                #     msg = "task_id %s create success" % body['task_id']
                # else:
                #     # 不可创建任务
                #     LOG.info("task could not create")
                #     status = 'failed'
                #     msg = "task_id %s create not allowed" % body['task_id']
                #     # 上传命令处理结果
                # upload = uplink.Upload()
                # resp = {
                #     "id": request['id'],
                #     "from": request['from'],
                #     "status": status,
                #     "command": request['command'],
                #     "d":{
                #         "code":"task_status",
                #         "msg":msg
                #     }
                # }
                # # gw.get_task_status()
                # upload.send(resp, topic='dma/cmd/resp')
            elif cmd == 'cancel':
                # cancel task
                data = {
                    "cmd": "task",
                    "method": "cancel",
                    "task_id": body['task_id']
                }
                ret = dl.send_service('serial', data, need_resp=True)
                if ret['status'] != 'ok':  # 向模块发出取消命令
                    gw.set_try_data('serial', data)

                ret = gw.cancel_task(body['task_id'])
                if ret:
                    status = 'ok'
                    result = {'result': 'ok'}
                    try:
                        os.unlink("/tmp/success")
                        os.unlink("/tmp/fail")
                    except:
                        pass
                else:
                    status = 'err'
                    result = {'code': 'cancel_failed', 'msg': 'task not found'}
                # 上传处理结果
                upload = uplink.Upload()

                resp = {
                    "id": request['id'],
                    "from": request['from'],
                    "status": status,
                    "command": request['command'],
                    "msg": result
                }

                upload_data = {'topic': 'dma/cmd/resp', 'payload': resp}

                upload.send('http://127.0.0.1:7788/mqtt/publish/offlinecache',
                            upload_data)
            elif cmd == 'confirm':
                pass
                # confirm task
                # data = {
                #     "table_name":"sql",
                #     "sql_cmd":"update `task` set (`start_time`='%s', `end_time`='%s', `status`=2) where `task_id`='%s';" % \
                #         (body['start_time'], body['end_time'], body['task_id'])
                # }
                # dl.send_service('database', data)
            else:
                raise HTTPError(404)
        except Exception as e:
            self.write(e.__str__())
            LOG.error("%s" % e.__str__())
Ejemplo n.º 15
0
    def post(self, cmd):
        try:
            request = self.request.body.decode('utf-8')
            request = json.loads(request)
            body = request['d']
            if cmd == 'create':
                ret = gw.create_task(body['task_id'], body['image_data_id'], body['image_data_url'], \
                    body['image_data_md5'], body['iot_dev_list_md5'], body['iot_dev_list_url'], \
                    body['start_time'], body['end_time'])
                if ret:
                    data = {
                        "cmd": "task",
                        "method": "create",
                        "task_id": body['task_id'],
                        "data_id": body['image_data_id'],
                        "start_time": body['start_time'],
                        "end_time": body['end_time']
                    }
                    ret = dl.send_service('serial', data, need_resp=True)
                    if ret['status'] != 'ok':
                        gw.set_try_data('serial', data)
                    # raise HTTPError(200)
                    status = 'ok'
                    msg = "task_id %s create success" % body['task_id']
                else:
                    # 不可创建任务
                    LOG.info("task could not create")
                    status = 'failed'
                    msg = "task_id %s create not allowed" % body['task_id']
                    # 上传命令处理结果
                upload = uplink.Upload()
                resp = {
                    "id": request['id'],
                    "from": request['from'],
                    "status": status,
                    "command": request['command'],
                    "d": {
                        "code": "task_status",
                        "msg": msg
                    }
                }
                # gw.get_task_status()
                upload.send(resp, topic='dma/cmd/resp')
            elif cmd == 'cancel':
                # cancel task
                data = {
                    "cmd": "task",
                    "method": "cancel",
                    "task_id": body['task_id']
                }
                ret = dl.send_service('serial', data, need_resp=True)
                if ret['status'] != 'ok':  # 向模块发出取消命令
                    gw.set_try_data('serial', data)

                ret = gw.cancel_task(body['task_id'])
                if ret:
                    status = 'ok'
                    result = {'result': 'ok'}
                else:
                    status = 'err'
                    result = {'code': 'cancel_failed', 'msg': 'task not found'}
                # 上传处理结果
                upload = uplink.Upload()
                resp = {
                    "id": request['id'],
                    "from": request['from'],
                    "status": status,
                    "command": request['command'],
                    "d": result
                }
                upload.send(resp, topic='dma/cmd/resp')
            elif cmd == 'confirm':
                # confirm task
                data = {
                    "table_name":"sql",
                    "sql_cmd":"update `task` set (`start_time`='%s', `end_time`='%s', `status`=2) where `task_id`='%s';" % \
                        (body['start_time'], body['end_time'], body['task_id'])
                }
                dl.send_service('database', data)
            else:
                raise HTTPError(404)
        except Exception as e:
            self.write(e.__str__())
            LOG.error("%s" % e.__str__())