Parcourir la source

首页搜索查询设备

zhangdongming il y a 3 semaines
Parent
commit
12fe152094
1 fichiers modifiés avec 148 ajouts et 1 suppressions
  1. 148 1
      Controller/EquipmentManagerV3.py

+ 148 - 1
Controller/EquipmentManagerV3.py

@@ -94,6 +94,10 @@ class EquipmentManagerV3(View):
             return self.view_device_password(request_dict, response)
         elif operation == 'editSortOrder':
             return self.edit_sort_order(userID, request_dict, response)
+        elif operation == 'getDeviceListByUserId':  # 根据用户id获取设备UID、设备名称列表
+            return self.get_device_list_by_user_id(userID, response)
+        elif operation == 'getDeviceDetailByUid': # 根据用户id获取设备详情
+            return self.get_device_detail_by_uid(userID, request_dict, response)
         else:
             return response.json(414)
 
@@ -1491,4 +1495,147 @@ class EquipmentManagerV3(View):
                 device.save(update_fields=['sort_order'])
             return response.json(0)
         except Exception as e:
-            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @classmethod
+    def get_device_list_by_user_id(cls, user_id, response):
+        """
+        根据用户ID获取设备列表(设备名称、UID、序列号、类型)
+
+        Args:
+            user_id: 用户ID
+            response: 响应对象
+
+        Returns:
+            Response: 包含设备列表的响应对象
+        """
+        # 输入参数验证
+        if not user_id:
+            LOGGER.warning("获取设备列表失败: 用户ID为空")
+            return response.json(400, "用户ID不能为空")
+
+        try:
+            # 使用链式查询优化,减少数据库查询次数
+            device_queryset = (
+                Device_Info.objects
+                .filter(
+                    userID=user_id,
+                )
+                .exclude(Type__in=[200, 201])  # 排除网关和插座类型
+                .only('NickName', 'UID', 'serial_number', 'Type')  # 仅查询需要的字段
+                .order_by('-sort_order')  # 添加排序,提高用户体验
+            )
+
+            # 直接使用values()返回字典列表,避免创建模型实例
+            device_data = list(
+                device_queryset.values(
+                    'NickName',
+                    'UID',
+                    'serial_number',
+                    'Type'
+                )
+            )
+
+            # 添加空数据检查
+            if not device_data:
+                return response.json(0, [])
+
+            return response.json(0, device_data)
+
+        except Exception as e:
+            # 其他异常
+            LOGGER.error(
+                f"用户 {user_id} 获取设备列表时发生未知异常: {repr(e)}",
+                exc_info=True  # 记录完整的堆栈信息
+            )
+            return response.json(500, "系统内部错误")
+
+    def get_device_detail_by_uid(self, user_id, request_dict, response):
+        """
+        根据USER_ID、UID查询设备详情
+        @param userID: 用户id
+        @param request_dict: 请求参数
+        @param response: 响应结果
+        """
+        try:
+            uid = request_dict.get('uid', None)
+            if not uid:
+                return response.json(444)
+            all_dv_list, _ = UserDeviceService.query_device_list(
+                user_id,
+                uid=uid,
+                nickname=None,
+                page=1,
+                line=500,
+                group_id=0
+            )
+
+            matched_dv = all_dv_list
+
+            search_uids = [dev['UID'] for dev in matched_dv]
+
+            ub_qs = UserDeviceService.query_device_uid_bucket(search_uids)  # 根据uid集合查询云存套餐
+            up_qs = UserDeviceService.query_device_preview(search_uids)  # 根据uid集合查询设备预览图
+            uv_dict = UserDeviceService.query_device_channel(search_uids)  # 查询设备uid通道配置属性
+            auth = oss2.Auth(ALICLOUD_AK, ALICLOUD_SK)
+            bucket = oss2.Bucket(auth, 'oss-cn-hongkong.aliyuncs.com', 'statres')
+            nowTime = int(time.time())
+            data = []
+
+            # 遍历所有匹配的设备,查询设备关联数据详情
+            for p in matched_dv:
+                p['UID'] = p['UID'].replace('\n', '').replace('\r', '')
+                p_uid = p['UID'].upper()
+                UserDeviceService.get_sim_by_serial_number(p)  # 获取SIM卡属性
+                p['cloudPhoto'] = self.get_cloud_photo_status(p['UID'])
+                # 获取云存使用状态
+                p['vod_use_status'] = self.get_vod_use_status(p_uid, nowTime)
+                # 获取iot_deviceInfo表的endpoint和token_iot_number
+                p['iot'] = []
+                if p['serial_number']:  # 存在序列号根据序列号查询
+                    iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(serial_number=p['serial_number'][0:6])
+                else:  # 根据uid查询
+                    iotdeviceInfo_qs = iotdeviceInfoModel.objects.filter(uid=p_uid)
+                if iotdeviceInfo_qs.exists():
+                    iotdeviceInfo = iotdeviceInfo_qs.values('endpoint', 'token_iot_number')
+                    p['iot'].append({
+                        'endpoint': iotdeviceInfo[0]['endpoint'],
+                        'token_iot_number': iotdeviceInfo[0]['token_iot_number']
+                    })
+
+                p['vod'] = []
+                for dm in ub_qs:
+                    if p_uid == dm['uid']:
+                        if dm['endTime'] > nowTime:
+                            p['vod'].append(dm)
+                p['preview'] = []
+                for up in up_qs:
+                    if p_uid == up['uid']:
+                        obj = 'uid_preview/{uid}/channel_{channel}.png'.format(uid=up['uid'], channel=up['channel'])
+                        img_sign = bucket.sign_url('GET', obj, 300)
+                        p['preview'].append(img_sign)
+                UserDeviceService.get_uid_info(p, p_uid)  # 获取uid初始化信息
+
+                if p_uid in uv_dict:
+                    # 获取设备信息DTO
+                    UserDeviceService.get_device_info_dto(p, p_uid, uv_dict, user_id)
+                else:
+                    # 设备版本号
+                    p['uid_version'] = ''
+                    p['ucode'] = ''
+                p['View_Password'] = self.encrypt_pwd(p['View_Password'])
+
+                # 判断设备是否支持4G和查询移动侦测状态
+                uid_set_qs = UidSetModel.objects.filter(uid=p['UID']).values('detect_status', 'ucode', 'version')
+                if uid_set_qs.exists():
+                    uid_set_qs = uid_set_qs.first()
+                    p['has_4g_cloud'] = self.get_device_is_4G(uid_set_qs['ucode'], uid_set_qs['version'])
+                    if p['has_4g_cloud'] == 1:
+                        p['isCameraOpenCloud'] = 1
+                    p['NotificationMode'] = uid_set_qs['detect_status']
+                data.append(p)
+
+            return response.json(0, data)
+        except Exception as e:
+            LOGGER.error(f"{user_id}查询设备详情时发生错误: {str(e)}")
+            return response.json(500)