Эх сурвалжийг харах

更新alexa事件网关添加addOrUpdateV2接口,delete兼容删除多通道设备

locky 4 жил өмнө
parent
commit
6c5a05dcfa
1 өөрчлөгдсөн 172 нэмэгдсэн , 33 устгасан
  1. 172 33
      controller/deviceStatus.py

+ 172 - 33
controller/deviceStatus.py

@@ -58,8 +58,10 @@ class deviceStatus(TemplateView):
             return self.getAccessToken(request_dict, response)
         if operation == 'addOrUpdate':
             return self.addOrUpdate(request_dict, response)
+        if operation == 'addOrUpdateV2':
+            return self.addOrUpdateV2(request_dict)
         if operation == 'delete':
-            return self.delete(request_dict, response)
+            return self.delete(request_dict)
         if operation == 'stopPush':
             return self.notifiesDeviceStopPush(request_dict, response)
     def saveAccessToken(self,request_dict, response):
@@ -212,44 +214,187 @@ class deviceStatus(TemplateView):
         logger.info(response)
         return JsonResponse({'res':'success'})
 
+    # 向alexa事件网关发送更新设备操作V2接口
+    def addOrUpdateV2(self,request_dict):
+        logger = logging.getLogger('django')
+        logger.info('--------添加/更新设备信息V2--------')
+
+        region = request_dict.get("region", 'EN')
+        data_list = request_dict.get("data_list", '')
+        logger.info('data_list: {}'.format(data_list))
+        data_list = json.loads(data_list)   # 多通道设备才传 channel 键值对
+
+        if not data_list:
+            return JsonResponse({'code': 101, 'msg': 'Parameter error'})
+
+        UID = data_list[0]['UID']
+        userID = data_list[0]['userID']
+        password = data_list[0]['password']
+        password = CommonService().decode_pwd(password)
 
-        # return json.dumps('test',indent=4,sort_keys=True,ensure_ascii=False)   #格式化返回内容
+        # 获取alexa授权信息
+        alexAuth = AlexaAuthModel.objects.filter(userID=userID).\
+            values('expiresTime', 'access_token', 'refresh_token', 'alexa_region')
+        if not alexAuth.exists():
+            logger.info('UID为 {} 的用户不存在'.format(UID))
+            return JsonResponse({'code': 102, 'msg': 'not found user'})
+        expiresTime = alexAuth[0]['expiresTime']
+        access_token = alexAuth[0]['access_token']
+        refresh_token = alexAuth[0]['refresh_token']
+        alexa_region = alexAuth[0]['alexa_region']
+
+        # 更新alexa token
+        now_time = int(time.time())
+        if now_time > expiresTime:
+            logger.info(refresh_token)
+            res = self.getRefreshToken(refresh_token)
+            logger.info(res)
+            if 'error' not in res:
+                alexAuth.update(
+                    updTime=now_time,
+                    expiresTime=now_time + 3000,
+                    access_token=res['access_token'],
+                    refresh_token=res['refresh_token'],
+                )
+                access_token = res['access_token']
+            else:
+                logger.info('get refresh_token fail')
+                return JsonResponse({'code': 102, 'msg': 'get refresh_token fail'})
+
+        # 添加rtsp记录
+        channel = len(data_list)    # 列表的元素个数即通道数量
+        rtsp_url = tkObject(rank=1).encrypt(data=UID)
+        uid_rtsp_qs = UidRtspModel.objects.filter(uid__contains=UID)
+        if not uid_rtsp_qs.exists():
+            # 创建UidRtsp数据
+            if channel == 1:
+                # 单通道设备
+                UidRtspModel.objects.create(uid=UID, nick=data_list[0]['uid_nick'], region=region, rtsp_url=rtsp_url,
+                                           password=password, addTime=now_time, updTime=now_time)
+            else:
+                # 多通道设备
+                bulk = []
+                for data in data_list:
+                    uid = UID + '_' + str(data['channel'])  # 多通道设备: uid_通道号
+                    uidRtsp = UidRtspModel(uid=uid, nick=data['uid_nick'], region=region, rtsp_url=rtsp_url,
+                                           password=password, addTime=now_time, updTime=now_time)
+                    bulk.append(uidRtsp)
+                UidRtspModel.objects.bulk_create(bulk)
+        else:
+            # 更新UidRtsp数据
+            count = len(uid_rtsp_qs)
+            if count != channel:
+                return JsonResponse({'code': 103, 'msg': '通道数不匹配'})
+            if count == 1:
+                uid_rtsp_qs.update(nick=data_list[0]['uid_nick'], region=region, password=password)
+            else:
+                # 多通道设备
+                for data in data_list:
+                    uid = UID + '_' + str(data['channel'])   # 多通道设备: uid_通道号
+                    UidRtspModel.objects.filter(uid=uid).update(nick=data['uid_nick'], region=region, password=password)
 
-    #向alex事件网关发送删除设备操作
-    def delete(self,request_dict, response):
+        api_uri = ALEXA_EVENT_API[alexa_region]
+        messageId = str(uuid.uuid4()).strip()
+        bearer_access_token = "Bearer {access_token}".format(access_token=access_token)
+        headers = {"content-type": "application/json", "Authorization": bearer_access_token}
+        endpoints = self.append_endpoint(data_list, channel)
+        payload_json = {
+            "event": {
+                "header": {
+                    "namespace": "Alexa.Discovery",
+                    "name": "AddOrUpdateReport",
+                    "payloadVersion": "3",
+                    "messageId": messageId,
+                },
+                "payload": {
+                    "endpoints": endpoints,
+                    "scope": {
+                        "type": "BearerToken",
+                        "token": 'sdf',
+                    },
+                },
+            }
+        }
+
+        response = requests.post(api_uri, json=payload_json, headers=headers)
+        logger.info('--------Alexa AddOrUpdateReport响应: {}--------'.format(response))
+        return JsonResponse({'res': 'success'})
+
+    def append_endpoint(self, data_list, channel):
+        # 组织 endpoints 数据
+        endpoints = []
+        for data in data_list:
+            endpointId = data['UID'] if channel == 1 else data['UID']+'_'+str(data['channel'])
+            endpoint = {
+                "endpointId": endpointId,
+                "manufacturerName": "zosi smart",
+                "modelName": "P1425-LE",
+                "friendlyName": data['uid_nick'],
+                "description": "Camera connected via zosi smart",
+                "displayCategories": ["CAMERA"],
+                "capabilities": [
+                    {
+                        "type": "AlexaInterface",
+                        "interface": "Alexa.CameraStreamController",
+                        "version": "3",
+                        "cameraStreamConfigurations": [
+                            {
+                                "protocols": ["RTSP"],
+                                "resolutions": [{"width": 1280, "height": 720}],
+                                "authorizationTypes": ["NONE"],
+                                "videoCodecs": ["H264"],
+                                "audioCodecs": ["ACC"],
+                            }
+                        ],
+                    }
+                ],
+            }
+            endpoints.append(endpoint)
+        return endpoints
+
+    # 向alexa事件网关发送删除设备操作
+    def delete(self, request_dict):
         UID = request_dict.get("UID", '')
         userID = request_dict.get("userID", '')
         logger = logging.getLogger('django')
         logger.info('class:deviceStatus-------function:delete------------------')
-        logger.info(UID)
-        logger.info(userID)
-        if UID == '':
-            return JsonResponse({'code':111,'msg':'fail'})
+        logger.info('userID: {}, UID: {}'.format(userID, UID))
+        if not all([UID, userID]):
+            return JsonResponse({'code': 111, 'msg': 'fail'})
 
-        alexAuth = AlexaAuthModel.objects.filter(userID=userID)
+        alexAuth = AlexaAuthModel.objects.filter(userID=userID).\
+            values('expiresTime', 'refresh_token', 'access_token', 'alexa_region')
         if not alexAuth.exists():
-            return JsonResponse({'code':102,'msg':'not found user'})
+            return JsonResponse({'code': 102, 'msg': 'not found user'})
 
-        info = alexAuth.values()
-        expiresTime = info[0]['expiresTime']
-        refresh_token = info[0]['refresh_token']
-        now_time = int(time.time())
-        access_token = info[0]['access_token']
-        alexa_region = info[0]['alexa_region']
+        expiresTime = alexAuth[0]['expiresTime']
+        refresh_token = alexAuth[0]['refresh_token']
+        access_token = alexAuth[0]['access_token']
+        alexa_region = alexAuth[0]['alexa_region']
 
+        now_time = int(time.time())
         if now_time > expiresTime:
             res = self.getRefreshToken(refresh_token)
-            if('error' not in res):
+            if 'error' not in res:
                 alexAuth.update(
-                    access_token = res['access_token'],
-                    refresh_token = res['refresh_token'],
-                    expiresTime = now_time + 300,
-                    updTime = now_time,
+                    access_token=res['access_token'],
+                    refresh_token=res['refresh_token'],
+                    expiresTime=now_time + 300,
+                    updTime=now_time,
                 )
                 access_token = res['access_token']
             else:
-                return JsonResponse({'code':102,'msg':'get refresh_token fail'})
-        messageId = str(uuid.uuid4())
+                return JsonResponse({'code': 102, 'msg': 'get refresh_token fail'})
+
+        uidRtsp_qs = UidRtspModel.objects.filter(uid__contains=UID).values('uid')
+        if not uidRtsp_qs.exists():
+            return JsonResponse({'code': 103, 'msg': '不存在uidRtsp数据'})
+
+        endpoints = []
+        for uidRtsp in uidRtsp_qs:
+            endpointId = {"endpointId": uidRtsp['uid']}
+            endpoints.append(endpointId)
+
         headers = {
             "Authorization": "Bearer " + access_token,
             "Content-Type": "application/json;charset=UTF-8",
@@ -261,15 +406,11 @@ class deviceStatus(TemplateView):
                 "header": {
                     "namespace": "Alexa.Discovery",
                     "name": "DeleteReport",
-                    "messageId": messageId,
+                    "messageId": str(uuid.uuid4()),
                     "payloadVersion": "3"
                 },
                 "payload": {
-                    "endpoints": [
-                        {
-                            "endpointId": UID
-                        }
-                    ],
+                    "endpoints": endpoints,
                     "scope": {
                         "type": "BearerToken",
                         "token": access_token
@@ -277,13 +418,11 @@ class deviceStatus(TemplateView):
                 }
             }
         }
-        # return JsonResponse({"res": headers})
 
         api_uri = ALEXA_EVENT_API[alexa_region]
         response = requests.post(api_uri, json=payload, headers=headers)
-        logger.info('--------delete_response')
-        logger.info(response)
-        return JsonResponse({'res':'success'})
+        logger.info('--------Alexa DeleteReport响应: {}--------'.format(response))
+        return JsonResponse({'res': 'success'})
 
 
     def getRefreshToken(self,refresh_token):