Ver código fonte

Merge branch 'test' of http://192.168.136.99:3000/servers/ASJServer

locky 3 anos atrás
pai
commit
42a7b8f31d

+ 15 - 0
Ansjer/server_urls/unicom_url.py

@@ -0,0 +1,15 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : unicom_url.py
+@Time    : 2022/6/23 9:50
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+from django.urls import re_path
+
+from Controller.UnicomCombo import UnicomComboController
+
+urlpatterns = [
+    re_path(r'^api/(?P<operation>.*)$', UnicomComboController.UnicomComboView.as_view()),
+]

+ 2 - 0
Ansjer/urls.py

@@ -366,6 +366,8 @@ urlpatterns = [
     # 网关家庭模块
     url(r'^app/sensor/gateway/(?P<operation>.*)$', EquipmentFamilyController.EquipmentFamilyView.as_view()),
     url(r'^loocam/', include("Ansjer.server_urls.loocam_url")),
+    # 联通4G套餐模块
+    url(r'^unicom/', include("Ansjer.server_urls.unicom_url")),
 
     # 传感器网关
     re_path('sensorGateway/(?P<operation>.*)', SensorGatewayController.SensorGateway.as_view()),

+ 7 - 0
Controller/AiController.py

@@ -363,7 +363,14 @@ class AiView(View):
             ai_service_qs = ai_service_qs.order_by('addTime').annotate(
                 bucket__content=F('orders__ai_rank__lang__title')). \
                 values('uid', 'use_status', 'bucket__content')
+
             ai_service_data = ai_service_qs[0]
+            # 如果存在序列号返回完整序列号
+            device_info_qs = Device_Info.objects.filter(UID=uid).values('serial_number', 'Type')
+            serial_number = device_info_qs[0]['serial_number']
+            if serial_number:
+                ai_service_data['uid'] = CommonService.get_full_serial_number(uid, serial_number, device_info_qs[0]['Type'])
+
             ai_service_data['endTime'] = sum_end_time
             return response.json(0, [ai_service_data])
         except Exception as e:

+ 11 - 1
Controller/SensorGateway/EquipmentFamilyController.py

@@ -155,8 +155,18 @@ class EquipmentFamilyView(View):
             if device_user_id == user_id:
                 return response.json(174)
             else:
+                if qs[0]['userID__userEmail']:
+                    bind_user = qs[0]['userID__userEmail']
+                elif qs[0]['userID__phone']:
+                    bind_user = qs[0]['userID__phone']
+                elif qs[0]['userID__username']:
+                    bind_user = qs[0]['userID__username']
+                elif qs[0]['userID__NickName']:
+                    bind_user = qs[0]['userID__NickName']
+                else:
+                    bind_user = qs[0]['userID_id']
                 res = {
-                    'bindUser': qs[0]['userID__NickName'],
+                    'bindUser': bind_user,
                     'bindDeviceName': nickname,
                     'isMainUserExists': 1
                 }

+ 3 - 0
Controller/SensorGateway/GatewayFamilyMemberController.py

@@ -145,6 +145,9 @@ class GatewayFamilyMemberView(View):
         n_time = int(time.time())
         location = request_dict.get('location', '')
         room_names = request_dict.get('roomNames', None)
+        user_family_qs = UserFamily.objects.filter(name=family_name, user_id=app_user_id)
+        if user_family_qs.exists():
+            return response.json(174)
         try:
             with transaction.atomic():
                 member_permission_qs = FamilyMemberPermission.objects.filter(no='001').values('id')

+ 150 - 88
Controller/SensorGateway/SubDeviceController.py

@@ -1,19 +1,20 @@
 # -*- coding: utf-8 -*-
 """
+@Author : Joker
 @Time : 2022/5/25 15:17
-@Auth : Locky
 @File :SubDeviceController.py
-@IDE :PyCharm
 """
 import time
 from collections import OrderedDict
 
 from django.db import transaction
+from django.db.models import Count
 from django.views import View
 
 from Model.models import Device_Info, GatewaySubDevice, FamilyRoomDevice, SensorRecord
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
+from Service.CommonService import CommonService
 
 
 class GatewaySubDeviceView(View):
@@ -43,8 +44,12 @@ class GatewaySubDeviceView(View):
             return self.sensor_update(request_dict, response)
         elif operation == 'delete':  # 删除子设备
             return self.delete(request_dict, user_id, response)
-        elif operation == 'records':  # 查询子设备记录数据
+        elif operation == 'records/tem-hum':  # 查询温湿度传感器记录
+            return self.records_tem_hum(request_dict, response)
+        elif operation == 'records':  # 查询其他传感器记录
             return self.records(request_dict, response)
+        elif operation == 'records-date':  # 查询传感器记录日期
+            return self.records_date(request_dict, response)
         else:
             return response.json(414)
 
@@ -177,109 +182,166 @@ class GatewaySubDeviceView(View):
             return response.json(500, repr(e))
 
     @staticmethod
-    def records(request_dict, response):
+    def records_tem_hum(request_dict, response):
         """
-        查询子设备记录数据
+        查询温湿度传感器记录
         @param request_dict: 请求参数
         @request_dict gatewaySubId: 子设备id
         @request_dict cycle: 时间周期
-        @request_dict page: 页数
-        @request_dict size: 条数
+        @request_dict eventType: 事件类型, 18:温度,19:湿度
         @param response: 响应对象
         @return: response
         """
         sub_device_id = request_dict.get('gatewaySubId', None)
         cycle = request_dict.get('cycle', None)
-        if not all([sub_device_id]):
-            return response.json(444)
+        event_type = request_dict.get('eventType', None)
+        if not all([sub_device_id, cycle, event_type]):
+            return response.json(444, {'error param': 'gatewaySubId or cycle or eventType'})
         now_time = int(time.time())
         try:
-            if not cycle:
-                page = request_dict.get('page', None)
-                size = request_dict.get('size', None)
-                start_time = request_dict.get('startTime', None)
-                end_time = request_dict.get('endTime', None)
-                if not all([page, size]):
-                    return response.json(444)
-                page, size = int(page), int(size)
+            record_dict = OrderedDict()
+            record_list = []
+            if cycle == 'Hours':
+                start_time = now_time - 24 * 60 * 60
+                sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
+                                                               event_type=event_type,
+                                                               created_time__range=(start_time, now_time)). \
+                    values('alarm', 'created_time').order_by('created_time')
+                if not sensor_record_qs.exists():
+                    return response.json(0, {'records': [], 'time': now_time})
 
-                if start_time and end_time:
-                    sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
-                                                                   created_time__range=(start_time, end_time)). \
-                                           values('alarm', 'created_time').order_by('-created_time')[
-                                       (page - 1) * size:page * size]
-                else:
-                    sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id). \
-                                           values('alarm', 'created_time').order_by('-created_time')[
-                                       (page - 1) * size:page * size]
+                for sensor_record in sensor_record_qs:
+                    created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
+                    hour = int(created_time[-7:-5])
+                    minute = int(created_time[-4:-2])
+                    if hour != 23 and minute > 30:  # 不为23时且分钟大于30,hour+1
+                        hour += 1
+                    alarm = float(sensor_record['alarm'])
+                    # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
+                    if str(hour) in record_dict:
+                        record_dict[str(hour)].append(alarm)
+                    else:
+                        record_dict[str(hour)] = [alarm]
+
+            elif cycle == 'Week':
+                start_time = now_time - 24 * 60 * 60 * 7
+                sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
+                                                               event_type=event_type,
+                                                               created_time__range=(start_time, now_time)). \
+                    values('alarm', 'created_time').order_by('created_time')
                 if not sensor_record_qs.exists():
-                    return response.json(0)
-                return response.json(0, list(sensor_record_qs))
-            else:
-                record_dict = OrderedDict()
-                record_list = []
-                if cycle == 'Hours':
-                    start_time = now_time - 24 * 60 * 60
-                    sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
-                                                                   created_time__range=(start_time, now_time)). \
-                        values('alarm', 'created_time').order_by('created_time')
-                    if not sensor_record_qs.exists():
-                        return response.json(0)
+                    return response.json(0, {'records': [], 'time': now_time})
+
+                for sensor_record in sensor_record_qs:
+                    created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
+                    week = int(created_time[-1:])
+                    alarm = float(sensor_record['alarm'])
+                    # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
+                    if str(week) in record_dict:
+                        record_dict[str(week)].append(alarm)
+                    else:
+                        record_dict[str(week)] = [alarm]
+
+            elif cycle == 'Month':
+                start_time = now_time - 24 * 60 * 60 * 30
+                sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
+                                                               event_type=event_type,
+                                                               created_time__range=(start_time, now_time)). \
+                    values('alarm', 'created_time').order_by('created_time')
+                if not sensor_record_qs.exists():
+                    return response.json(0, {'records': [], 'time': now_time})
 
-                    for sensor_record in sensor_record_qs:
-                        created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
-                        hour = int(created_time[-7:-5])
-                        minute = int(created_time[-4:-2])
-                        if hour != 23 and minute > 30:  # 不为23时且分钟大于30,hour+1
-                            hour += 1
-                        alarm = float(sensor_record['alarm'])
-                        # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
-                        if str(hour) in record_dict:
-                            record_dict[str(hour)].append(alarm)
-                        else:
-                            record_dict[str(hour)] = [alarm]
+                for sensor_record in sensor_record_qs:
+                    created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
+                    month = int(created_time[:2])
+                    day = int(created_time[3:5])
+                    date = str(month) + '/' + str(day)
+                    alarm = float(sensor_record['alarm'])
+                    # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
+                    if date in record_dict:
+                        record_dict[date].append(alarm)
+                    else:
+                        record_dict[date] = [alarm]
 
-                elif cycle == 'Week':
-                    start_time = now_time - 24 * 60 * 60 * 7
-                    sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
-                                                                   created_time__range=(start_time, now_time)). \
-                        values('alarm', 'created_time').order_by('created_time')
-                    if not sensor_record_qs.exists():
-                        return response.json(0)
+            # 组织响应数据列表,value为每 小时/天 的平均值
+            for k, v in record_dict.items():
+                record_list.append({'key': k, 'value': round(sum(v) / len(v), 1)})
+
+            res = {
+                'records': record_list,
+                'time': now_time
+            }
+            return response.json(0, res)
+        except Exception as e:
+            return response.json(500, repr(e))
+
+    @staticmethod
+    def records(request_dict, response):
+        """
+        查询其他传感器记录
+        @param request_dict: 请求参数
+        @request_dict gatewaySubId: 子设备id
+        @request_dict page: 页数
+        @request_dict size: 条数
+        @request_dict startTime: 开始时间
+        @request_dict endTime: 结束时间
+        @param response: 响应对象
+        @return: response
+        """
+        sub_device_id = request_dict.get('gatewaySubId', None)
+        page = request_dict.get('page', None)
+        size = request_dict.get('size', None)
+        if not all([sub_device_id, page, size]):
+            return response.json(444, {'error param': 'gatewaySubId or page or size'})
 
-                    for sensor_record in sensor_record_qs:
-                        created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
-                        week = int(created_time[-1:])
-                        alarm = float(sensor_record['alarm'])
-                        # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
-                        if str(week) in record_dict:
-                            record_dict[str(week)].append(alarm)
-                        else:
-                            record_dict[str(week)] = [alarm]
+        start_time = request_dict.get('startTime', None)
+        end_time = request_dict.get('endTime', None)
 
-                elif cycle == 'Month':
-                    start_time = now_time - 24 * 60 * 60 * 30
-                    sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
-                                                                   created_time__range=(start_time, now_time)). \
-                        values('alarm', 'created_time').order_by('created_time')
-                    if not sensor_record_qs.exists():
-                        return response.json(0)
+        try:
+            page, size = int(page), int(size)
+            if start_time and end_time:
+                sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id,
+                                                               created_time__range=(start_time, end_time)). \
+                                       values('alarm', 'created_time').order_by('-created_time')[
+                                   (page - 1) * size:page * size]
+            else:
+                sensor_record_qs = SensorRecord.objects.filter(gateway_sub_device_id=sub_device_id). \
+                                       values('alarm', 'created_time').order_by('-created_time')[
+                                   (page - 1) * size:page * size]
+            if not sensor_record_qs.exists():
+                return response.json(0, [])
+            return response.json(0, list(sensor_record_qs))
+        except Exception as e:
+            return response.json(500, repr(e))
 
-                    for sensor_record in sensor_record_qs:
-                        created_time = time.strftime('%m/%d %H:%M %w', time.localtime(sensor_record['created_time']))
-                        month = int(created_time[:2])
-                        day = int(created_time[3:5])
-                        date = str(month) + '/' + str(day)
-                        alarm = float(sensor_record['alarm'])
-                        # 组织数据,record_dict:{"0": [1.0, 2.0, 3.0], "1": [1.0, 2.0, 3.0]...}
-                        if date in record_dict:
-                            record_dict[date].append(alarm)
-                        else:
-                            record_dict[date] = [alarm]
+    @staticmethod
+    def records_date(request_dict, response):
+        """
+        查询传感器记录日期
+        @param request_dict: 请求参数
+        @request_dict gatewaySubId: 子设备id
+        @request_dict startTime: 开始时间
+        @request_dict endTime: 结束时间
+        @param response: 响应对象
+        @return: response
+        """
+        sub_device_id = request_dict.get('gatewaySubId', None)
+        if not sub_device_id:
+            return response.json(444, {'error param': 'gatewaySubId'})
 
-                # 组织响应数据列表,value为每 小时/天 的平均值
-                for k, v in record_dict.items():
-                    record_list.append({'key': k, 'value': round(sum(v) / len(v), 1)})
-                return response.json(0, record_list)
+        try:
+            sensor_record_qs = SensorRecord.objects.extra(
+                select={'date': "FROM_UNIXTIME(created_time,'%%Y-%%m-%%d')"}).values('date'). \
+                                   filter(gateway_sub_device_id=sub_device_id). \
+                                   annotate(count=Count('created_time')). \
+                                   order_by('-date')[:31]
+            record_date_list = []
+            for sensor_record in sensor_record_qs:
+                record_date_list.append({
+                    'timestamp': CommonService.str_to_timestamp(sensor_record['date'], '%Y-%m-%d'),
+                    'count': sensor_record['count'],
+                    'format': sensor_record['date'],
+                })
+            return response.json(0, record_date_list)
         except Exception as e:
             return response.json(500, repr(e))

+ 41 - 0
Controller/UnicomCombo/UnicomComboController.py

@@ -0,0 +1,41 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : UnicomComboController.py
+@Time    : 2022/6/23 9:18
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+import json
+
+from django.http import HttpResponse
+from django.views.generic.base import View
+
+
+class UnicomComboView(View):
+    def get(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.GET, request, operation)
+
+    def post(self, request, *args, **kwargs):
+        request.encoding = 'utf-8'
+        operation = kwargs.get('operation')
+        return self.validation(request.POST, request, operation)
+
+    def validation(self, request_dict, request, operation):
+        if operation == 'test':
+            return self.test(request_dict, request)
+        else:
+            r_data = {'success': False, 'msg': '失败'}
+            return HttpResponse(json.dumps(r_data, ensure_ascii=False), content_type="application/json,charset=utf-8")
+
+    @staticmethod
+    def test(request_dict, request):
+        body = request.body.decode("utf-8")
+        if body:
+            dict_data = json.loads(body)
+            print(dict_data)
+        print(request_dict)
+        r_data = {'success': True, 'msg': '成功'}
+        return HttpResponse(json.dumps(r_data, ensure_ascii=False), content_type="application/json,charset=utf-8")