Browse Source

优化快照接口

locky 2 weeks ago
parent
commit
29f8577662
1 changed files with 102 additions and 0 deletions
  1. 102 0
      controller/Snapshot.py

+ 102 - 0
controller/Snapshot.py

@@ -0,0 +1,102 @@
+# @Author    : Rocky
+# @File      : Snapshot.py
+# @Time      : 2025/7/29 8:51
+import threading
+
+import requests
+from django.http import JsonResponse
+from django.views import View
+
+from azoauth.config import LOGGER, SERVER_API
+from model.models import UserModel
+from object.ResObject import ResObject
+from service.CommonService import CommonService
+
+
+class SnapshotView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.GET, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, operation)
+
+    def validation(self, request_dict, operation):
+        response = ResObject()
+        if operation == 'sendMqtt':             # 下发快照指令
+            return self.send_mqtt(request_dict)
+        elif operation == 'asynEventResponse':  # 异步事件响应
+            return self.asyn_event_response(request_dict, response)
+        else:
+            return response.json(10, 'error url')
+
+    @classmethod
+    def send_mqtt(cls, request_dict):
+        uid = request_dict.get("uid", None)
+        access_token = request_dict.get("access_token", None)
+        correlation_token = request_dict.get("correlation_token", None)
+
+        if not all([uid, access_token, correlation_token]):
+            return JsonResponse({'result_code': '444', '错误': '参数错误'})
+
+        try:
+            user_qs = UserModel.objects.filter(access_token=access_token)
+            if not user_qs.exists():
+                return JsonResponse({'result_code': '500', '错误': '用户数据不存在'})
+
+            # 更新correlation_token
+            user_qs.update(correlation_token=correlation_token)
+
+            region = user_qs.values('region_code')[0]['region_code']
+            send_res = cls._send_mqtt_snapshot_command(uid, region)
+            if send_res:
+                return JsonResponse({'result_code': '0'})
+            else:
+                return JsonResponse({
+                    'result_code': '500',
+                    'msg': 'send mqtt failed'}
+                )
+
+        except Exception as e:
+            return JsonResponse({'result_code': '500', 'error_msg': 'error_line:{}, error_msg:{}'.
+                                format(e.__traceback__.tb_lineno, repr(e))})
+
+    @staticmethod
+    def _send_mqtt_snapshot_command(uid, region):
+        thing_name = CommonService.query_serial_with_uid(uid)
+        topic_name = 'ansjer/generic/{}'.format(thing_name)
+
+        msg = {
+            "commandType": "alexaSnapshot",
+        }
+
+        try:
+            result = CommonService.req_publish_mqtt_msg(thing_name, topic_name, msg)
+            LOGGER.info('快照指令下发结果 {}: {}'.format(uid, result))
+
+            if result:
+                return True
+
+            domain_name = SERVER_API[region]
+            url = '{}/iot/requestPublishMessage'.format(domain_name)
+            request_data = {'UID': uid, 'commandType': 'alexaSnapshot'}
+
+            response = requests.post(url, data=request_data, timeout=10)
+            if response.status_code == 200:
+                result = response.json()
+                if result.get('result_code') == 0:
+                    LOGGER.info('快照远程MQTT接口成功')
+                    return True
+                else:
+                    LOGGER.info('快照远程MQTT接口失败, res:{}'.format(result))
+                    return False
+            else:
+                LOGGER.info('快照远程MQTT接口失败, 状态码: {}', response.status_code)
+                return False
+
+        except Exception as e:
+            LOGGER.info('快照MQTT函数异常: error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            return False