فهرست منبع

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

locky 3 سال پیش
والد
کامیت
f1d644811c

+ 144 - 16
AdminController/DeviceManagementController.py

@@ -5,18 +5,18 @@ import time
 
 import oss2
 from django.db import transaction
-from django.db.models import Q
+from django.db.models import Q, F
+from django.views.generic.base import View
 
 from Ansjer.config import OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET
+from Model.models import Device_Info, UidSetModel, LogModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
+    VodHlsModel, ExperienceContextModel, DeviceTypeModel, Equipment_Info, UidUserModel, ExperienceAiModel, AiService, \
+    AppBundle, App_Info, AppDeviceType, DeviceNameLanguage
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
-from django.views.generic.base import View
-
+from Service.CommonService import CommonService
 from Service.EquipmentInfoService import EquipmentInfoService
 from Service.ModelService import ModelService
-from Service.CommonService import CommonService
-from Model.models import Device_Info, UidSetModel, LogModel, UID_Bucket, Unused_Uid_Meal, Order_Model, StsCrdModel, \
-    VodHlsModel, ExperienceContextModel, DeviceTypeModel, Equipment_Info, UidUserModel, ExperienceAiModel, AiService
 
 
 class DeviceManagement(View):
@@ -37,6 +37,9 @@ class DeviceManagement(View):
             return self.addDeviceType(request, request_dict, response)
         elif operation == 'delDeviceData':  # 删除设备数据
             return self.del_device_data(request_dict, response)
+        elif operation == 'getDeviceIcon':  # app获取设备图标
+            response = ResponseObject(language)
+            return self.get_device_icon(request_dict, response)
         else:
             tko = TokenObject(
                 request.META.get('HTTP_AUTHORIZATION'),
@@ -47,13 +50,13 @@ class DeviceManagement(View):
             userID = tko.userID
             if not userID:
                 return response.json(444, 'userID')
-            if operation == 'getDeviceInfoList':    # 获取设备信息数据
+            if operation == 'getDeviceInfoList':  # 获取设备信息数据
                 return self.get_device_info_list(request_dict, response)
             elif operation == 'deleteDevice':
                 return self.deleteDevice(request_dict, response)
-            elif operation == 'resetVod':   # 重置云存
+            elif operation == 'resetVod':  # 重置云存
                 return self.resetVod(request, request_dict, response)
-            elif operation == 'resetAi':    # 重置AI
+            elif operation == 'resetAi':  # 重置AI
                 return self.reset_ai(request, request_dict, response)
             elif operation == 'resetPrimaryUser':
                 return self.resetPrimaryUser(request, request_dict, response)
@@ -61,6 +64,14 @@ class DeviceManagement(View):
                 return self.getDeviceTypeList(request_dict, response)
             elif operation == 'deleteDeviceType':
                 return self.deleteDeviceType(request_dict, response)
+            elif operation == 'getAppDeviceTypeList':  # 获取app设备类型数据
+                return self.get_app_device_type_list(request_dict, response)
+            elif operation == 'getAppBundleIdList':  # 获取app包id数据
+                return self.get_app_bundle_id_list(response)
+            elif operation == 'editAppDeviceType':  # 编辑app设备类型数据
+                return self.edit_app_device_type(request_dict, response)
+            elif operation == 'deleteAppDeviceType':  # 删除app设备类型数据
+                return self.delete_app_device_type(request_dict, response)
             else:
                 return response.json(444, 'operation')
 
@@ -80,7 +91,7 @@ class DeviceManagement(View):
         line = int(pageSize)
 
         try:
-            if UID or serialNumber or NickName or username:    # 条件查询
+            if UID or serialNumber or NickName or username:  # 条件查询
                 if UID:
                     device_info_qs = Device_Info.objects.filter(UID__contains=UID)
                 if serialNumber:
@@ -95,7 +106,7 @@ class DeviceManagement(View):
                 if not total:
                     return response.json(0, {'list': {}, 'total': 0})
                 device_info_qs = device_info_qs[(page - 1) * line:page * line]
-            else:   # 查询全部
+            else:  # 查询全部
                 total = Device_Info.objects.filter().count()
                 device_info_qs = Device_Info.objects.filter()[(page - 1) * line:page * line]
                 if not device_info_qs.exists():
@@ -108,13 +119,15 @@ class DeviceManagement(View):
                         # 设备的用户名和主用户
                         username = ModelService.get_user_name(device_info_list["datas"][k]['fields']['userID'])
                         device_info_list["datas"][k]['fields']['username'] = username
-                        device_info_list["datas"][k]['fields']['vodPrimaryMaster'] = device_info_list["datas"][k]['fields']['vodPrimaryMaster']
+                        device_info_list["datas"][k]['fields']['vodPrimaryMaster'] = \
+                            device_info_list["datas"][k]['fields']['vodPrimaryMaster']
                         # 设备类型,是否支持Alexa和ip
                         type = device_info_list["datas"][k]['fields']['Type']
                         device_type_qs = DeviceTypeModel.objects.filter(type=type).values('name')
                         if device_type_qs.exists():
                             device_info_list["datas"][k]['fields']['Type'] = device_type_qs[0]['name']
-                        uid_set_qs = UidSetModel.objects.filter(uid=device_info_list["datas"][k]['fields']['UID']).values('is_alexa', 'ip', 'version')
+                        uid_set_qs = UidSetModel.objects.filter(
+                            uid=device_info_list["datas"][k]['fields']['UID']).values('is_alexa', 'ip', 'version')
                         if uid_set_qs.exists():
                             isAlexa = '是' if uid_set_qs[0]['is_alexa'] else '否'
                             device_info_list["datas"][k]['fields']['isAlexa'] = isAlexa
@@ -138,7 +151,7 @@ class DeviceManagement(View):
                 Device_Info.objects.filter(id=deviceID).delete()
                 # 删除推送消息
                 for val in range(1, 8):
-                    EquipmentInfoService.get_equipment_info_model('', val).\
+                    EquipmentInfoService.get_equipment_info_model('', val). \
                         filter(device_user_id=userID, device_uid=uid).delete()
             return response.json(0)
         except Exception as e:
@@ -294,7 +307,7 @@ class DeviceManagement(View):
             # 上传文件到阿里云OSS
             auth = oss2.Auth(OSS_STS_ACCESS_KEY, OSS_STS_ACCESS_SECRET)
             bucket = oss2.Bucket(auth, 'oss-cn-shenzhen.aliyuncs.com', 'ansjer-static-resources')
-            key = 'device_type/' + icon     # 图片文件存放于 device_type 目录下
+            key = 'device_type/' + icon  # 图片文件存放于 device_type 目录下
             # https://oss.console.aliyun.com/bucket/oss-cn-shenzhen/ansjer-static-resources/object?path=device_type%2F
             bucket.put_object(key=key, data=iconFile)
             DeviceTypeModel.objects.create(name=name, model=model, type=type, ptz_type=ptz_type, icon=icon,
@@ -313,7 +326,7 @@ class DeviceManagement(View):
             return response.json(444)
         try:
             with transaction.atomic():
-                uidList = uidList.splitlines()      # 按行('\r', '\r\n', \n')切割字符串返回列表
+                uidList = uidList.splitlines()  # 按行('\r', '\r\n', \n')切割字符串返回列表
                 # 根据删除项删除相关数据
                 if '设备信息数据' in delDataOptions:
                     Device_Info.objects.filter(UID__in=uidList).delete()
@@ -338,3 +351,118 @@ class DeviceManagement(View):
         except Exception as e:
             print(e)
             return response.json(500, repr(e))
+
+    @staticmethod
+    def get_device_icon(request_dict, response):
+        lang = request_dict.get('lang', None)
+        app_bundle_id = request_dict.get('appBundleId', None)
+
+        if not all([lang, app_bundle_id]):
+            return response.json(444)
+        try:
+            app_bundle_qs = AppBundle.objects.filter(app_bundle_id=app_bundle_id,
+                                                     app_device_type__devicenamelanguage__lang=lang).annotate(
+                model=F('app_device_type__model'), type=F('app_device_type__type'), icon=F('app_device_type__icon'),
+                name=F('app_device_type__devicenamelanguage__name'),
+                sort=F('app_device_type__devicenamelanguage__sort')).order_by(
+                'app_device_type__devicenamelanguage__sort').values('model', 'type', 'icon', 'name', 'sort')
+            dvr_list = [app_bundle for app_bundle in app_bundle_qs if app_bundle['model'] == 1]
+            ipc_list = [app_bundle for app_bundle in app_bundle_qs if app_bundle['model'] == 2]
+            print(dvr_list, ipc_list)
+            res = {
+                'deviceDvr': dvr_list,
+                'deviceIpc': ipc_list,
+            }
+            return response.json(0, res)
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))
+
+    @staticmethod
+    def get_app_device_type_list(request_dict, response):
+        app_bundle_id = request_dict.get('appBundleId', None)
+        lang = request_dict.get('lang', 'cn')
+
+        pageNo = request_dict.get('pageNo', None)
+        pageSize = request_dict.get('pageSize', None)
+
+        if not all([pageNo, pageSize]):
+            return response.json(444)
+
+        page = int(pageNo)
+        line = int(pageSize)
+        try:
+            if not app_bundle_id:
+                app_bundle_id = 'com.ansjer.zccloud'
+            app_bundle_qs = AppBundle.objects.filter(app_bundle_id=app_bundle_id)
+            if lang:
+                app_bundle_qs = app_bundle_qs.filter(app_device_type__devicenamelanguage__lang=lang)
+
+            app_bundle_qs = app_bundle_qs.annotate(
+                model=F('app_device_type__model'), type=F('app_device_type__type'), icon=F('app_device_type__icon'),
+                lang=F('app_device_type__devicenamelanguage__lang'),
+                name=F('app_device_type__devicenamelanguage__name'),
+                sort=F('app_device_type__devicenamelanguage__sort')).values('id', 'app_device_type__id', 'model',
+                                                                            'type', 'icon',
+                                                                            'app_device_type__devicenamelanguage__id',
+                                                                            'lang', 'name', 'sort').order_by(
+                'app_device_type__devicenamelanguage__sort')
+            if not app_bundle_qs.exists():
+                return response.json(0)
+            total = app_bundle_qs.count()
+            app_bundle_qs = app_bundle_qs[(page - 1) * line:page * line]
+            app_device_type_list = [app_bundle for app_bundle in app_bundle_qs]
+            return response.json(0, {'list': app_device_type_list, 'total': total})
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))
+
+    @staticmethod
+    def get_app_bundle_id_list(response):
+        try:
+            app_info_qs = App_Info.objects.filter().values('id', 'appBundleId', 'appName')
+            appBundleIdList = list(app_info_qs)
+            return response.json(0, {'list': appBundleIdList})
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))
+
+    @staticmethod
+    def edit_app_device_type(request_dict, response):
+        # app_device_type表数据
+        app_device_type_id = request_dict.get('app_device_type__id', None)
+        model = request_dict.get('model', None)
+        type = request_dict.get('type', None)
+        icon = request_dict.get('icon', None)
+        # device_name_language表数据
+        device_name_language_id = request_dict.get('app_device_type__devicenamelanguage__id', None)
+        lang = request_dict.get('lang', None)
+        name = request_dict.get('name', None)
+        sort = request_dict.get('sort', None)
+
+        if not all([app_device_type_id, model, type, icon, device_name_language_id, lang, name, sort]):
+            return response.json(444)
+
+        try:
+            with transaction.atomic():
+                AppDeviceType.objects.filter(id=app_device_type_id).update(model=model, type=type, icon=icon)
+                DeviceNameLanguage.objects.filter(id=device_name_language_id).update(lang=lang, name=name, sort=sort)
+            return response.json(0)
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))
+
+    @staticmethod
+    def delete_app_device_type(request_dict, response):
+        app_bundle_id = request_dict.get('appBundleId', None)
+        app_device_type_id = request_dict.get('appDeviceTypeId', None)
+        if not all([app_bundle_id, app_device_type_id]):
+            return response.json(444)
+        try:
+            app_bundle_qs = AppBundle.objects.get(id=app_bundle_id)
+            app_device_type_qs = AppDeviceType.objects.filter(id=app_device_type_id)
+            app_bundle_qs.app_device_type.remove(*app_device_type_qs)
+            return response.json(0)
+        except Exception as e:
+            print(e)
+            return response.json(500, repr(e))

+ 5 - 3
AdminController/SerialManageController.py

@@ -15,7 +15,7 @@ from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 
-from Model.models import CompanyModel, SerialNumberModel, VPGModel, UIDModel, UIDCompanySerialModel, CompanySerialModel, \
+from Model.models import CompanyModel, VPGModel, UIDModel, UIDCompanySerialModel, CompanySerialModel, \
     LogModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -182,7 +182,7 @@ class SerialView(View):
             if not company_serial_qs.exists():
                 return response.json(0, {'list': '', 'total': 0})
             total = company_serial_qs.count()
-            serial_number_page = company_serial_qs.order_by('-serial_number')[(page - 1) * line:page * line].\
+            serial_number_page = company_serial_qs.order_by('-serial_number')[(page - 1) * line:page * line]. \
                 values('serial_number', 'company__name', 'status', 'add_time', 'update_time')
             return response.json(0, {'list': list(serial_number_page), 'total': total})
         except Exception as e:
@@ -241,7 +241,7 @@ class SerialView(View):
         try:
             query = UIDModel.objects.filter()
             if serial_number:
-                company_serial_qs = CompanySerialModel.objects.filter(serial_number=serial_number).values()
+                company_serial_qs = CompanySerialModel.objects.filter(serial_number__contains=serial_number).values()
                 if company_serial_qs.exists():
                     cs_id = str(company_serial_qs[0]['id'])
                     uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial_id=cs_id).values(
@@ -249,6 +249,8 @@ class SerialView(View):
                     if uid_company_serial_qs.exists():
                         uid_id = uid_company_serial_qs[0]['uid_id']
                         query = query.filter(id=uid_id)
+                else:
+                    return response.json(0, {'list': '', 'total': 0})
             if vpg_id:
                 query = query.filter(vpg_id=int(vpg_id))
             if status:

+ 13 - 5
AdminController/ServeManagementController.py

@@ -14,7 +14,7 @@ from boto3.session import Session
 from django.http import JsonResponse, HttpResponseRedirect, HttpResponse, StreamingHttpResponse
 from django.views.generic.base import View
 from Model.models import Device_Info, Role, MenuModel, VodBucketModel, CDKcontextModel, Store_Meal, Order_Model, \
-    UID_Bucket, ExperienceContextModel, Lang, Device_User, CloudLogModel, UidSetModel
+    UID_Bucket, ExperienceContextModel, Lang, Device_User, CloudLogModel, UidSetModel, Unused_Uid_Meal
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Object.UidTokenObject import UidTokenObject
@@ -845,16 +845,24 @@ class serveManagement(View):
             uid_bucket_qs = uid_bucket_qs.order_by('-addTime')[(page - 1) * line:page * line]
 
             for uid_bucket in uid_bucket_qs:
+                # 套餐到期时间累加未使用套餐
+                unused_qs = Unused_Uid_Meal.objects.filter(uid=uid_bucket.uid).values('num', 'expire')
+                if unused_qs.exists():
+                    addMonth = 0
+                    for unused in unused_qs:
+                        addMonth += unused['num'] * unused['expire']
+                    endTime = CommonService.calcMonthLater(addMonth, uid_bucket.endTime)
+                    endTime = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(endTime))
+                else:
+                    endTime = time.strftime("%Y--%m--%d %H:%M:%S", time.localtime(uid_bucket.endTime))
+
                 uid = uid_bucket.uid.upper()
                 data = {
                     'id': uid_bucket.id,
                     'uid': uid,
                     'channel': uid_bucket.channel,
                     'status': uid_bucket.status,
-                    'endTime': time.strftime(
-                        "%Y--%m--%d %H:%M:%S",
-                        time.localtime(
-                            uid_bucket.endTime)),
+                    'endTime': endTime,
                     'addTime': time.strftime(
                         "%Y--%m--%d %H:%M:%S",
                         time.localtime(

+ 2 - 1
Ansjer/server_urls/loocam_url.py

@@ -9,7 +9,7 @@
 from django.urls import re_path
 
 from Controller.SensorGateway import GatewayFamilyRoomController, SubDeviceController, GatewayFamilyMemberController, \
-    EquipmentFamilyController
+    EquipmentFamilyController, GatewayDeviceController
 
 urlpatterns = [
     re_path(r'^sensor/gateway/(?P<operation>.*)$', EquipmentFamilyController.EquipmentFamilyView.as_view()),
@@ -17,4 +17,5 @@ urlpatterns = [
     re_path(r'^gateway/family/member/(?P<operation>.*)$',
             GatewayFamilyMemberController.GatewayFamilyMemberView.as_view()),
     re_path(r'^gateway/subdevice/(?P<operation>.*)$', SubDeviceController.GatewaySubDeviceView.as_view()),
+    re_path(r'^gateway/device/info/(?P<operation>.*)$', GatewayDeviceController.GatewayDeviceView.as_view()),
 ]

+ 7 - 12
Controller/DeviceConfirmRegion.py

@@ -5,7 +5,7 @@ from django.utils.decorators import method_decorator
 
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic import TemplateView
-from Model.models import CountryModel, RegionModel, P2PIpModel, DeviceDomainModel
+from Model.models import CountryModel, RegionModel, P2PIpModel, DeviceDomainModel, DeviceDomainRegionModel
 from Object.ResponseObject import ResponseObject
 from Service.CommonService import CommonService
 
@@ -52,17 +52,12 @@ class ConfirmRegionV2(TemplateView):
 
     def get(self, request, *args, **kwargs):
         response = ResponseObject()
-        uid = request.GET.get('uid', None)
         serial_number = request.GET.get('serial_number', None)
-        if not uid and not serial_number:
+        if not serial_number:
             return response.json(444)
         try:
-            if uid:
-                data_dict = {'uid': uid}
-                device_domain_qs = DeviceDomainModel.objects.filter(uid=uid)
-            else:
-                data_dict = {'serial_number': serial_number}
-                device_domain_qs = DeviceDomainModel.objects.filter(serial_number=serial_number)
+            data_dict = {'serial_number': serial_number}
+            device_domain_region_qs = DeviceDomainRegionModel.objects.filter(serial_number=serial_number)
 
             # 根据请求ip确认地区
             request.encoding = 'utf-8'
@@ -87,10 +82,10 @@ class ConfirmRegionV2(TemplateView):
             # 更新或创建设备域名数据
             data_dict['api'] = api
             data_dict['region_id'] = region_id
-            if device_domain_qs.exists():
-                device_domain_qs.update(**data_dict)
+            if device_domain_region_qs.exists():
+                device_domain_region_qs.update(**data_dict)
             else:
-                device_domain_qs.create(**data_dict)
+                device_domain_region_qs.create(**data_dict)
             res = {'request_api_url': api, 'region_id': region_id}
             return response.json(0, res)
         except Exception as e:

+ 8 - 1
Controller/EquipmentManagerV2.py

@@ -9,7 +9,7 @@ from django.views.generic.base import View
 
 from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
 from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidPushModel, UidChannelSetModel, \
-    iotdeviceInfoModel
+    iotdeviceInfoModel, UIDModel
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -325,6 +325,13 @@ class EquipmentManagerV2(View):
             uv_dict[us['uid']]['channels'] = channels
 
         for p in dvls:
+            # 如果存在序列号组织序列号数据返回
+            if p['serial_number']:
+                p2p_type = str(UIDModel.objects.filter(uid=p['UID']).values('p2p_type')[0]['p2p_type'])
+                # 设备类型转为16进制并补齐4位
+                device_type = hex(p['Type'])[2:]
+                device_type = (4-len(device_type)) * '0' + device_type
+                p['UID'] = p['serial_number'] + p2p_type + device_type
             # 新增IOT
             p['iot'] = []
             for iot in iotqs:

+ 5 - 3
Controller/IotCoreController.py

@@ -129,10 +129,12 @@ class IotCoreView(View):
                 }
                 return response.json(0, {'res': res})
             else:
-                # 根据配置信息确定region_id
-                region_id = CommonService.confirm_region_id(request)
-                iotClient = IOTClient(region_id)
+                region_id = request_dict.get('region_id', None)
+                if not region_id:
+                    # 根据配置信息确定region_id
+                    region_id = CommonService.confirm_region_id(request)
 
+                iotClient = IOTClient(int(region_id))
                 # 拼接物品名
                 thingName = CommonService.get_thing_name(company_mark, thing_name_suffix)
                 thingGroup = device_version + '_' + language

+ 90 - 27
Controller/SensorGateway/EquipmentFamilyController.py

@@ -19,7 +19,7 @@ from Ansjer.config import OSS_STS_ACCESS_SECRET, OSS_STS_ACCESS_KEY
 from Controller.DeviceConfirmRegion import Device_Region
 from Model.models import Device_Info, UID_Bucket, UID_Preview, UidSetModel, UidChannelSetModel, \
     iotdeviceInfoModel, UIDModel, Device_User, UserFamily, FamilyMember, FamilyMemberPermission, \
-    FamilyRoomDevice, FamilyRoom
+    FamilyRoomDevice, FamilyRoom, FamilyMemberJoin
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
@@ -69,7 +69,7 @@ class EquipmentFamilyView(View):
             return self.family_save(user_id, request_dict, response)
         # 家庭设置
         elif operation == 'family-setting':
-            return self.get_family_setting(user_id, request_dict, response)
+            return self.get_family_setting(request_dict, response)
         # 家庭成员删除
         elif operation == 'member-del':
             return self.family_member_del(user_id, request_dict, response)
@@ -85,9 +85,50 @@ class EquipmentFamilyView(View):
         # 成员权限修改
         elif operation == 'permission-update':
             return self.changes_member_permission(user_id, request_dict, response)
+        elif operation == 'family/del':
+            return self.family_family_del(user_id, request_dict, response)
         else:
             return response.json(414)
 
+    @classmethod
+    def family_family_del(cls, user_id, request_dict, response):
+        """
+        删除家庭
+        @param user_id:
+        @param request_dict:
+        @param response:
+        @return:
+        """
+        family_id = request_dict.get('familyId', None)
+        if not family_id:
+            return response.json(444)
+        family_id = int(family_id)
+        permission = cls.get_member_permission_details(user_id, family_id)
+        if not permission or permission == '003':
+            return response.json(404)
+        user_family_qs = UserFamily.objects.filter(id=family_id, user_id=user_id)
+        if not user_family_qs.exists():
+            return response.json(173)
+        count = UserFamily.objects.filter(user_id=user_id).count()
+        if count <= 1:
+            return response.json(10057)
+        family_room_device_qs = FamilyRoomDevice.objects.filter(family_id=family_id)
+        if family_room_device_qs.exists():
+            family_room_device_qs.delete()
+        family_join_qs = FamilyMemberJoin.objects.filter(family_id=family_id)
+        if family_join_qs.exists():
+            family_join_qs.delete()
+        family_room_qs = FamilyRoom.objects.filter(family_id=family_id)
+        if family_room_qs.exists():
+            family_room_qs.delete()
+        family_member_qs = FamilyMember.objects.filter(family_id=family_id)
+        if family_member_qs.exists():
+            family_member_qs.delete()
+        family_qs = UserFamily.objects.filter(id=family_id)
+        if family_qs.exists():
+            family_qs.delete()
+        return response.json(0)
+
     @classmethod
     def do_save(cls, user_id, request_dict, response, request):
         """
@@ -106,15 +147,23 @@ class EquipmentFamilyView(View):
         # type 可能为0
         if not all([nick_name, serial_number, device_type]):
             return response.json(444, {'param': 'nick_name, serial_number, device_type'})
-        device_info_qs = Device_Info.objects.filter(serial_number=serial_number, userID_id=user_id)
+        device_info_qs = Device_Info.objects.filter(serial_number=serial_number, isShare=False)
         if device_info_qs:
-            # 判断设备是否已存在
-            if device_info_qs[0].isExist == 1:
+            qs = device_info_qs.values('userID__NickName', 'NickName', 'userID_id')
+            nickname = qs[0]['NickName']
+            device_user_id = qs[0]['userID_id']
+            if device_user_id == user_id:
                 return response.json(174)
             else:
-                device_info_qs.delete()
+                res = {
+                    'bindUser': qs[0]['userID__NickName'],
+                    'bindDeviceName': nickname,
+                    'isMainUserExists': 1
+                }
+                return response.json(0, res=res)
         try:
             with transaction.atomic():
+                family_id = int(family_id)
                 # 格式化后的日期时间
                 now_time = CommonService.timestamp_to_str(int(time.time()))
                 device_id = CommonService.getUserID(getUser=False)
@@ -188,6 +237,13 @@ class EquipmentFamilyView(View):
             permission = cls.get_member_permission_details(user_id, int(family_id))
             if not permission or permission == '003':
                 return response.json(404)
+        if room_id:
+            family_room = FamilyRoom.objects.filter(id=room_id)
+            if not family_room.exists():
+                return response.json(173)
+            permission = cls.get_member_permission_details(user_id, family_room.first().family_id)
+            if not permission or permission == '003':
+                return response.json(404)
         # 获取设备信息列表
         device_info_list = cls.get_device_info_list(user_id, nick_name, uid,
                                                     page, line, family_id, room_id)
@@ -268,6 +324,7 @@ class EquipmentFamilyView(View):
         sql += 'FROM device_info d INNER JOIN family_room_device l ON d.id = l.device_id '
         sql += 'WHERE d.userID_id = %s AND d.isExist != %s '
         if family_id:
+            family_id = int(family_id)
             user_id = UserFamily.objects.filter(id=family_id).first().user_id
             sql += ' AND l.family_id = %s '
         if room_id and is_room_other:
@@ -519,30 +576,34 @@ class EquipmentFamilyView(View):
                 family_member_qs = FamilyMember.objects.filter(user_id=user_id) \
                     .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
                                              'family__location', 'user__username', 'user__userIconUrl')
-                items = []
-                data = {}
-                for item in family_member_qs:
-                    data['familyId'] = item['family_id']
-                    data['identity'] = item['identity']
-                    data['familyName'] = item['family__name']
-                    data['permissionId'] = item['permission_id']
-                    data['permissionNo'] = item['permission__no']
-                    data['familyLocation'] = item['family__location']
-                    data['userName'] = item['user__username']
-                    data['userIconUrl'] = item['user__userIconUrl']
-                    room_qs = FamilyRoom.objects.filter(family_id=data['familyId']).order_by('sort') \
-                        .values('id', 'name')
-                    data['rooms'] = list(room_qs)
-                    items.append(data)
-                    data = {}
+                items = EquipmentFamilyView.family_info_list(family_member_qs)
                 return response.json(0, items)
         return response.json(309)
 
+    @staticmethod
+    def family_info_list(family_member_qs):
+        items = []
+        data = {}
+        for item in family_member_qs:
+            data['familyId'] = item['family_id']
+            data['identity'] = item['identity']
+            data['familyName'] = item['family__name']
+            data['permissionId'] = item['permission_id']
+            data['permissionNo'] = item['permission__no']
+            data['familyLocation'] = item['family__location']
+            data['userName'] = item['user__username']
+            data['userIconUrl'] = item['user__userIconUrl']
+            room_qs = FamilyRoom.objects.filter(family_id=data['familyId']).order_by('sort') \
+                .values('id', 'name')
+            data['rooms'] = list(room_qs)
+            items.append(data)
+            data = {}
+        return items
+
     @classmethod
-    def get_family_setting(cls, user_id, request_dict, response):
+    def get_family_setting(cls, request_dict, response):
         """
         家庭设置
-        @param user_id: 用户id
         @param request_dict: 请求
         @param response: 响应
         @return: 家庭列表items
@@ -550,10 +611,13 @@ class EquipmentFamilyView(View):
         family_id = request_dict.get('familyId', None)
         if not family_id:
             return response.json(444)
-        user_family_qs = UserFamily.objects.filter(id=family_id, user_id=user_id).values('id', 'name', 'location')
+        family_id = int(family_id)
+        user_family_qs = UserFamily.objects.filter(id=family_id).values('id', 'name', 'location')
         if not user_family_qs.exists():
             return response.json(404)
         family_dict = user_family_qs.first()
+        device_count = FamilyRoomDevice.objects.filter(family_id=family_id, sub_device=0).count()
+        family_dict['deviceCount'] = device_count
         family_dict['roomCount'] = FamilyRoom.objects.filter(family_id=family_id).count()
 
         family_member_qs = FamilyMember.objects.filter(family_id=family_id)
@@ -729,8 +793,7 @@ class EquipmentFamilyView(View):
             room_qs = FamilyRoom.objects.filter(family_id=family_id, name=room_name)
 
             if room_qs.exists():
-                room_dict = {'updated_time': now_time, 'name': room_name}
-                room_qs.update(**room_dict)
+                return response.json(174)
             FamilyRoom.objects.create(family_id=family_id, name=room_name, updated_time=now_time,
                                       created_time=now_time)
         return response.json(0)

+ 262 - 0
Controller/SensorGateway/GatewayDeviceController.py

@@ -0,0 +1,262 @@
+# -*- encoding: utf-8 -*-
+"""
+@File    : GatewayDeviceController.py
+@Time    : 2022/6/6 13:50
+@Author  : stephen
+@Email   : zhangdongming@asj6.wecom.work
+@Software: PyCharm
+"""
+from django.db import transaction
+from django.db.models import Q
+from django.views.generic.base import View
+
+from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
+from Model.models import FamilyRoomDevice, FamilyRoom, GatewaySubDevice, Device_Info, UserFamily, FamilyMember, \
+    UidSetModel, iotdeviceInfoModel
+from Object.ResponseObject import ResponseObject
+from Object.TokenObject import TokenObject
+
+
+# 网关主页
+class GatewayDeviceView(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):
+
+        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
+        lang = request_dict.get('lang', None)
+        response = ResponseObject(lang) if lang else ResponseObject(token.lang)
+        if token.code != 0:
+            return response.json(token.code)
+        user_id = token.userID
+
+        # 网关设备
+        if operation == 'list':
+            return self.gateway_device_list(request_dict, response)
+        elif operation == 'del':
+            return self.gateway_device_del(user_id, request_dict, response)
+        elif operation == 'update':
+            return self.gateway_device_update(user_id, request_dict, response)
+        elif operation == 'my/family/list':
+            return self.my_family_list(user_id, response)
+        elif operation == 'location-setting':
+            return self.device_location_setting(user_id, request_dict, response)
+
+    @classmethod
+    def device_location_setting(cls, user_id, request_dict, response):
+        """
+        网关位置迁移
+        @param user_id: 用户id
+        @param request_dict: 请求参数字典
+        @param response: 响应对象
+        @return: []
+        """
+        device_id = request_dict.get('deviceId', None)
+        family_id = request_dict.get('familyId', None)
+        room_id = request_dict.get('roomId', None)
+        if not all([device_id, family_id]):
+            return response.json(444)
+        family_id = int(family_id)
+        permission = EquipmentFamilyView.get_member_permission_details(user_id, family_id)
+        if not permission or permission == '003':
+            return response.json(404)
+        try:
+            with transaction.atomic():
+                family_room_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id, family_id=family_id)
+                if family_room_device_qs.exists():
+                    family_room_device_qs = family_room_device_qs.filter(sub_device=0)
+                    if family_room_device_qs.exists() and room_id:
+                        family_room_device_qs.update(room_id=int(room_id))
+                else:
+                    user_family_qs = UserFamily.objects.filter(id=family_id)
+                    if not user_family_qs:
+                        return response.json(173)
+                    family_room_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
+                    if family_room_device_qs.exists():
+                        param_data = {'family_id': family_id, 'room_id': 0}
+                        if room_id:
+                            param_data['room_id'] = room_id
+                        family_room_device_qs.update(**param_data)
+                return response.json(0)
+        except Exception as e:
+            print(e)
+            return response.json(177, repr(e))
+
+    @classmethod
+    def gateway_device_update(cls, user_id, request_dict, response):
+        """
+        网关设备修改名称
+        @param user_id:
+        @param request_dict:
+        @param response:
+        @return:
+        """
+        device_name = request_dict.get('deviceName')
+        device_id = request_dict.get('deviceId')
+        if not all([device_name, device_id]):
+            return response.json(444)
+        device_info_qs = Device_Info.objects.filter(userID_id=user_id, id=device_id)
+        if device_info_qs.exists():
+            device_info_qs.update(NickName=device_name)
+        return response.json(0)
+
+    @classmethod
+    def my_family_list(cls, user_id, response):
+        """
+        我的家庭列表
+        @param user_id:
+        @param response:
+        @return:
+        """
+        user_family_qs = UserFamily.objects.filter(user_id=user_id).values()
+        family_list = []
+        if user_family_qs.exists():
+            family_member_qs = FamilyMember.objects.filter(user_id=user_id, identity=1) \
+                .order_by('sort').values('identity', 'family_id', 'family__name', 'permission_id', 'permission__no',
+                                         'family__location', 'user__username', 'user__userIconUrl')
+            items = EquipmentFamilyView.family_info_list(family_member_qs)
+            return response.json(0, items)
+        return response.json(0, family_list)
+
+    @classmethod
+    def gateway_device_del(cls, user_id, request_dict, response):
+        """
+        网关设备删除或删除子设备
+        @param user_id:
+        @param request_dict:
+        @param response:
+        @return:
+        """
+        device_id = request_dict.get('deviceId')
+        family_id = request_dict.get('familyId')
+        # 1 删除网关 否则删除子设备
+        sub_ids = request_dict.get('subIds')
+        if not family_id:
+            return response.json(444)
+        permission = EquipmentFamilyView.get_member_permission_details(user_id, family_id)
+        if not permission or permission == '003':
+            return response.json(404)
+        try:
+            with transaction.atomic():
+                if device_id:
+                    device_qs = Device_Info.objects.filter(id=device_id)
+                    if device_qs.exists():
+                        family_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
+                        if family_device_qs.exists():
+                            family_device_qs.delete()
+                        gateway_qs = GatewaySubDevice.objects.filter(device_id=device_id)
+                        if gateway_qs.exists():
+                            gateway_qs.delete()
+                        uid_set_qs = UidSetModel.objects.filter(uid=device_qs.first().UID)
+                        if uid_set_qs.exists():
+                            uid_set_qs.delete()
+                        device_qs.delete()
+                elif sub_ids:
+                    sub_ids = sub_ids.split(',')
+                    ids = []
+                    for item in sub_ids:
+                        sub_id = int(item)
+                        ids.append(sub_id)
+                    family_device_qs = FamilyRoomDevice.objects.filter(sub_device__in=ids)
+                    if family_device_qs.exists():
+                        family_device_qs.delete()
+                    gateway_sub_qs = GatewaySubDevice.objects.filter(id__in=ids)
+                    if gateway_sub_qs.exists():
+                        gateway_sub_qs.delete()
+                return response.json(0)
+        except Exception as e:
+            print(e)
+            return response.json(177, repr(e))
+
+    @classmethod
+    def gateway_device_list(cls, request_dict, response):
+        """
+        网关设备列表
+        @param request_dict:
+        @param response:
+        @return:
+        """
+        device_id = request_dict.get('deviceId', None)
+        if not device_id:
+            return response.json(444)
+        device_qs = FamilyRoomDevice.objects.filter(device_id=device_id, sub_device=0)
+        if not device_qs.exists():
+            return response.json(173)
+        try:
+            device_qs = device_qs.values('family_id', 'device_id', 'room_id', 'device__Type', 'device__NickName',
+                                         'device__UID',
+                                         'device__serial_number')
+            device_qs = device_qs.first()
+            room_id = device_qs['room_id']
+            family_id = device_qs['family_id']
+            gateway_room_name = ''
+            if room_id:
+                room_qs = FamilyRoom.objects.filter(id=room_id)
+                gateway_room_name = room_qs.first().name if room_qs.exists() else ''
+
+            iot_device_info_qs = iotdeviceInfoModel.objects.filter(
+                serial_number=device_qs['device__serial_number'][0:6])
+            iot_data = {}
+            if iot_device_info_qs.exists():
+                iot_device_Info = iot_device_info_qs.values('endpoint', 'token_iot_number')
+                iot_data = {
+                    'endpoint': iot_device_Info[0]['endpoint'],
+                    'token_iot_number': iot_device_Info[0]['token_iot_number']
+                }
+            gateway = {
+                'deviceId': device_qs['device_id'],
+                'deviceType': device_qs['device__Type'],
+                'deviceNickName': device_qs['device__NickName'],
+                'UID': device_qs['device__UID'],
+                'serialNumber': device_qs['device__serial_number'],
+                'roomName': gateway_room_name,
+                'iot': iot_data,
+                'roomId': room_id,
+                'familyId': family_id
+            }
+            family_device_qs = FamilyRoomDevice.objects.filter(device_id=device_id)
+            family_device_qs = family_device_qs.filter(~Q(sub_device=0)).order_by('-created_time')
+
+            sub_device = []
+            if family_device_qs.exists():
+                family_device_qs = family_device_qs.values()
+                for item in family_device_qs:
+                    sub_id = item['sub_device']
+                    gateway_sub_qs = GatewaySubDevice.objects.filter(device_id=device_id, id=sub_id).values(
+                        'id', 'device_type',
+                        'nickname',
+                        'src_addr', 'status',
+                        'created_time', 'ieee_addr')
+                    if not gateway_sub_qs.exists():
+                        continue
+                    room_id = item['room_id']
+                    room_qs = FamilyRoom.objects.filter(id=room_id)
+                    gateway_room_name = room_qs.first().name if room_qs.exists() else ''
+                    gateway_sub_qs = gateway_sub_qs.first()
+                    sub_device.append({
+                        'gatewaySubId': gateway_sub_qs['id'],
+                        'nickName': gateway_sub_qs['nickname'],
+                        'deviceType': gateway_sub_qs['device_type'],
+                        'srcAddr': gateway_sub_qs['src_addr'],
+                        'status': gateway_sub_qs['status'],
+                        'createdTime': gateway_sub_qs['created_time'],
+                        'roomName': gateway_room_name,
+                        'roomId': room_qs.first().id if room_qs.exists() else 0,
+                        'ieeeAddr': gateway_sub_qs['ieee_addr'],
+                        'familyId': family_id,
+                    })
+            return response.json(0, {'gateway': gateway, 'sub_device': sub_device})
+
+        except Exception as e:
+            print(e.args)
+            return response.json(500)

+ 54 - 17
Controller/SensorGateway/GatewayFamilyMemberController.py

@@ -15,7 +15,7 @@ from django.views.generic.base import View
 
 from Controller.SensorGateway.EquipmentFamilyController import EquipmentFamilyView
 from Model.models import UserFamily, FamilyMemberJoin, FamilyMember, SysMsgModel, FamilyMemberPermission, \
-    Device_User, FamilyRoomDevice
+    Device_User, FamilyRoomDevice, FamilyRoom
 from Object.RedisObject import RedisObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
@@ -74,18 +74,20 @@ class GatewayFamilyMemberView(View):
         @param response:
         @return:
         """
-        join_id = request_dict.get('joinId', None)
-        if not join_id:
+        join_ids = request_dict.get('joinIds', None)
+        family_id = request_dict.get('familyId', None)
+        if not join_ids:
             return response.json()
-        family_member_join_qs = FamilyMemberJoin.objects.filter(id=join_id)
-        if not family_member_join_qs.exists():
-            return response.json(173)
-        is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_member_join_qs.first().family_id)
+        is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_id)
         if not is_owner:
             return response.json(404)
         try:
             with transaction.atomic():
-                family_member_join_qs.delete()
+                items = join_ids.split(',')
+                for item in items:
+                    family_member_join_qs = FamilyMemberJoin.objects.filter(id=int(item))
+                    if family_member_join_qs.exists():
+                        family_member_join_qs.delete()
             return response.json(0)
         except Exception as e:
             print(e)
@@ -109,9 +111,16 @@ class GatewayFamilyMemberView(View):
         family_id = int(family_id)
         try:
             with transaction.atomic():
-                family_room_device_qs = FamilyRoomDevice.objects.filter(family_id=family_id)
-                if family_room_device_qs.exists():
-                    family_room_device_qs.delete()
+                family_member_qs = FamilyMember.objects.filter(family_id=family_id, identity=0)
+                if family_member_qs.exists():
+                    return response.json(10057)
+                family_room_dev_qs = FamilyRoomDevice.objects.filter(family_id=family_id)
+                if family_room_dev_qs.exists():
+                    return response.json(10057)
+                family_room_qs = FamilyRoom.objects.filter(family_id=family_id)
+                if family_room_qs.exists():
+                    family_room_qs.delete()
+                FamilyMember.objects.filter(family_id=family_id).delete()
                 user_family_qs = UserFamily.objects.filter(id=family_id)
                 if user_family_qs.exists():
                     user_family_qs.delete()
@@ -135,6 +144,7 @@ class GatewayFamilyMemberView(View):
             return response.json(444)
         n_time = int(time.time())
         location = request_dict.get('location', '')
+        room_names = request_dict.get('roomNames', None)
         try:
             with transaction.atomic():
                 member_permission_qs = FamilyMemberPermission.objects.filter(no='001').values('id')
@@ -149,6 +159,18 @@ class GatewayFamilyMemberView(View):
                                                 user_name=device_user.username, identity=1,
                                                 permission_id=int(permission_id), sort=1, updated_time=n_time,
                                                 created_time=n_time)
+                if room_names:
+                    names = room_names.split(',')
+                    rooms = []
+                    for index, item in enumerate(names):
+                        rooms.append(FamilyRoom(
+                            name=item,
+                            family_id=user_family.id,
+                            sort=index,
+                            updated_time=n_time,
+                            created_time=n_time
+                        ))
+                    FamilyRoom.objects.bulk_create(rooms)
                 return response.json(0)
         except Exception as e:
             print(e)
@@ -183,7 +205,7 @@ class GatewayFamilyMemberView(View):
                     return response.json(0)
                 else:
                     # 成员退出当前家庭
-                    family_member = FamilyMember.objects.filter(user_id=app_user_id, identity=1)
+                    family_member = FamilyMember.objects.filter(family_id=family_id, user_id=app_user_id, identity=1)
                     if family_member.exists():
                         return response.json(173)
                     family_member_qs = FamilyMember.objects.filter(family_id=family_id, user_id=app_user_id)
@@ -211,6 +233,10 @@ class GatewayFamilyMemberView(View):
         family_join = FamilyMemberJoin.objects.filter(id=join_id, status=0)
         if not family_join.exists():
             return response.json(173)
+        family_member = FamilyMember.objects.filter(family_id=family_join.first().family_id,
+                                                    user_id=family_join.first().user_id)
+        if family_member.exists():
+            return response.json(174)
         try:
             now_time = int(time.time())
             with transaction.atomic():
@@ -225,8 +251,8 @@ class GatewayFamilyMemberView(View):
                 data = {
                     'addTime': now_time,
                     'updTime': now_time,
-                    'userID_id': family_join['family__user_id'] if join_type == 1 else family_join['user_id'],
-                    'eventType': 705
+                    'userID_id': family_join['user_id'] if join_type == 1 else family_join['family__user_id'],
+                    'eventType': 0
                 }
                 if confirm == 'confirm':
                     msg_text = cls.get_confirm_text(nick_name, family_name, join_type, True, lang)
@@ -293,12 +319,16 @@ class GatewayFamilyMemberView(View):
         family_join_qs = FamilyMemberJoin.objects.filter(id=join_id)
         if not family_join_qs.exists():
             return response.json(173)
-        family_join_qs = family_join_qs.values('type', 'user__NickName', 'family__name', 'status', 'id')
+        family_join_qs = family_join_qs.values('type', 'user__NickName', 'family__name', 'status', 'id',
+                                               'family__user__NickName')
         family_join_qs = family_join_qs.first()
+        nick_name = family_join_qs['user__NickName']
+        if family_join_qs['type'] == 0:
+            nick_name = family_join_qs['family__user__NickName']
         return response.json(0, {
             'id': family_join_qs['id'],
             'type': family_join_qs['type'],
-            'nickName': family_join_qs['user__NickName'],
+            'nickName': nick_name,
             'familyName': family_join_qs['family__name'],
             'status': family_join_qs['status'],
         })
@@ -359,6 +389,13 @@ class GatewayFamilyMemberView(View):
                 return response.json(173)
             data['msg'] = msg_text
             with transaction.atomic():
+                member_user_id = user_id if user_id else app_user_id
+                member_join_qs = FamilyMemberJoin.objects.filter(family_id=family_id, user_id=member_user_id)
+                if member_join_qs.exists():
+                    member_join_qs.update(status=0, updated_time=now_time)
+                    data['uid'] = member_join_qs.first().id
+                    SysMsgModel.objects.create(**data)
+                    return response.json(0)
                 family_user_join = FamilyMemberJoin.objects.create(family_id=family_id, user_id=join_user_id,
                                                                    status=0,
                                                                    updated_time=now_time,
@@ -415,7 +452,7 @@ class GatewayFamilyMemberView(View):
 
         page_no = int(page_no)
         page_size = int(page_size)
-        member_join = member_join.order_by('-created_time')[(page_no - 1) * page_size: page_no * page_size]
+        member_join = member_join.order_by('-updated_time')[(page_no - 1) * page_size: page_no * page_size]
         if not member_join.exists():
             return response.json(0, [])
         result = []

+ 6 - 2
Controller/SensorGateway/GatewayFamilyRoomController.py

@@ -49,7 +49,7 @@ class GatewayFamilyRoomView(View):
             return self.room_del(app_user_id, request_dict, response)
         # 房间详情
         elif operation == 'details':
-            return self.get_room_details(request_dict, response)
+            return self.get_room_details(app_user_id, request_dict, response)
 
     @classmethod
     def room_device_save(cls, app_user_id, request_dict, response):
@@ -145,9 +145,10 @@ class GatewayFamilyRoomView(View):
         return response.json(0)
 
     @classmethod
-    def get_room_details(cls, request_dict, response):
+    def get_room_details(cls, app_user_id, request_dict, response):
         """
         房间设备详情(所在当前房间下,和所在家庭不在当前房间下的主设备)
+        @param app_user_id:
         @param request_dict:
         @param response:
         @return:
@@ -156,6 +157,9 @@ class GatewayFamilyRoomView(View):
         room_id = request_dict.get('roomId', None)
         if not all([family_id, room_id]):
             return response.json(444)
+        is_owner = EquipmentFamilyView.get_family_owner(app_user_id, family_id)
+        if not is_owner:
+            return response.json(404)
         family_id = int(family_id)
         room_id = int(room_id)
         room_device_qs = FamilyRoomDevice.objects.filter(family_id=family_id, room_id=room_id).order_by('sort').values(

+ 150 - 50
Controller/SensorGateway/SubDeviceController.py

@@ -10,7 +10,7 @@ import time
 from django.db import transaction
 from django.views import View
 
-from Model.models import Device_Info, GatewaySubDevice, FamilyRoomDevice
+from Model.models import Device_Info, GatewaySubDevice, FamilyRoomDevice, SensorRecord
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 
@@ -27,22 +27,23 @@ class GatewaySubDeviceView(View):
         return self.validation(request.POST, request, operation)
 
     def validation(self, request_dict, request, operation):
-        token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
+        token_obj = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
         lang = request_dict.get('lang', None)
-        response = ResponseObject(lang) if lang else ResponseObject(token.lang)
+        response = ResponseObject(lang if lang else token_obj.lang)
 
-        # if token.code != 0:
-        #     return response.json(token.code)
-        # user_id = token.userID
-        user_id = '154700384179113800138000'
+        if token_obj.code != 0:
+            return response.json(token_obj.code)
+        user_id = token_obj.userID
         if operation == 'add':  # 添加子设备
             return self.add(request_dict, user_id, response)
         elif operation == 'query':  # 查询子设备
             return self.query(request_dict, user_id, response)
         elif operation == 'update':  # 更新子设备信息
-            return self.update(request_dict, user_id, response)
+            return self.sensor_update(request_dict, response)
         elif operation == 'delete':  # 删除子设备
             return self.delete(request_dict, user_id, response)
+        elif operation == 'records':  # 查询子设备记录数据
+            return self.records(request_dict, response)
         else:
             return response.json(414)
 
@@ -61,27 +62,34 @@ class GatewaySubDeviceView(View):
         @param response: 响应对象
         @return: response 响应对象
         """
-        serial_number = request_dict.get('serial_number', None)
-        device_type = int(request_dict.get('device_type', None))
-        nickname = request_dict.get('nickname', None)
-        src_addr = request_dict.get('src_addr', None)
-        family_id = request_dict.get('family_id', None)
-        room_id = request_dict.get('room_id', None)
-
-        if not all([serial_number, device_type, nickname, src_addr, family_id, room_id]):
+        serial_number = request_dict.get('serialNumber', None)
+        device_type = int(request_dict.get('deviceType', None))
+        nickname = request_dict.get('nickName', None)
+        ieee_addr = request_dict.get('ieeeAddr', None)
+        src_addr = request_dict.get('srcAddr', None)
+        family_id = request_dict.get('familyId', None)
+        room_id = request_dict.get('roomId', 0)
+
+        if not all([serial_number, device_type, nickname, src_addr, family_id]):
             return response.json(444)
         now_time = int(time.time())
         try:
+            # 查询网关设备数据
             device_info_qs = Device_Info.objects.filter(userID_id=user_id, serial_number=serial_number).values('id')
             if not device_info_qs.exists():
                 return response.json(14)
             device_id = device_info_qs[0]['id']
+            # 查询是否已添加过该子设备
+            sub_device_qs = GatewaySubDevice.objects.filter(device_id=device_id, ieee_addr=ieee_addr)
+            if sub_device_qs.exists():
+                return response.json(174)
+
             with transaction.atomic():
                 sub_device = GatewaySubDevice.objects.create(device_id=device_id, device_type=device_type,
-                                                             nickname=nickname, src_addr=src_addr, status=1,
-                                                             created_time=now_time, updated_time=now_time)
+                                                             nickname=nickname, ieee_addr=ieee_addr, src_addr=src_addr,
+                                                             status=1, created_time=now_time, updated_time=now_time)
                 FamilyRoomDevice.objects.create(family_id=family_id, room_id=room_id, device_id=device_id,
-                                                sub_device=sub_device, created_time=now_time, updated_time=now_time)
+                                                sub_device=sub_device.id, created_time=now_time, updated_time=now_time)
             return response.json(0)
         except Exception as e:
             return response.json(500, repr(e))
@@ -96,7 +104,7 @@ class GatewaySubDeviceView(View):
         @param response: 响应对象
         @return: response
         """
-        serial_number = request_dict.get('serial_number', None)
+        serial_number = request_dict.get('serialNumber', None)
 
         if not all([serial_number]):
             return response.json(444)
@@ -107,8 +115,8 @@ class GatewaySubDeviceView(View):
             device_id = device_info_qs[0]['id']
             count = GatewaySubDevice.objects.filter(device_id=device_id).count()
             gateway_sub_device_qs = GatewaySubDevice.objects.filter(device_id=device_id).values('device_type',
-                                                                                                'nickname', 'src_addr',
-                                                                                                'status')
+                                                                                                'nickname', 'ieee_addr',
+                                                                                                'src_addr', 'status')
             gateway_sub_device_list = [gateway_sub_device for gateway_sub_device in gateway_sub_device_qs]
             res = {
                 'count': count,
@@ -118,39 +126,33 @@ class GatewaySubDeviceView(View):
         except Exception as e:
             return response.json(500, repr(e))
 
-    @staticmethod
-    def update(request_dict, user_id, response):
+    @classmethod
+    def sensor_update(cls, request_dict, response):
         """
-        更新子设备信息
+        传感器修改
         @param request_dict: 请求参数
-        @request_dict serial_number: 序列号
-        @request_dict sub_device_id: 子设备id
-        @param user_id: 用户id
-        @param response: 响应对象
-        @return: response
+        @request_dict gateway_sub_id: 子设备id
+        @request_dict nickName: 设备名
+        @request_dict room_id: 房间id
+        @param response: 响应结果
+        @return: list
         """
-        serial_number = request_dict.get('serial_number', None)
-        sub_device_id = request_dict.get('sub_device_id', None)
-        nickname = request_dict.get('nickname', None)
-        src_addr = request_dict.get('src_addr', None)
-        status = int(request_dict.get('status', None))
-        family_id = request_dict.get('family_id', None)
-        room_id = request_dict.get('room_id', None)
-
-        if not all([serial_number]):
+        gateway_sub_id = int(request_dict.get('gatewaySubId', None))
+        nickName = request_dict.get('nickName', None)
+        room_id = request_dict.get('roomId', None)
+        if not all([gateway_sub_id]):
             return response.json(444)
         try:
-            device_info_qs = Device_Info.objects.filter(userID_id=user_id, serial_number=serial_number).values('id')
-            if not device_info_qs.exists():
-                return response.json(14)
-            update_data = {
-                'nickname': nickname,
-                'src_addr': src_addr,
-                'status': status,
-            }
-            GatewaySubDevice.objects.filter(id=sub_device_id).update(**update_data)
+            gateway_sub_qs = GatewaySubDevice.objects.filter(id=gateway_sub_id)
+            if not gateway_sub_qs.exists():
+                return response.json(173)
+            if nickName:
+                gateway_sub_qs.update(nickname=nickName)
+            elif room_id:
+                FamilyRoomDevice.objects.filter(sub_device=gateway_sub_id).update(room_id=room_id)
             return response.json(0)
         except Exception as e:
+            print(e.args)
             return response.json(500, repr(e))
 
     @staticmethod
@@ -158,12 +160,12 @@ class GatewaySubDeviceView(View):
         """
         更新子设备信息
         @param request_dict: 请求参数
-       @request_dict sub_device_id: 子设备id
+        @request_dict sub_device_id: 子设备id
         @param user_id: 用户id
         @param response: 响应对象
         @return: response
         """
-        sub_device_id = request_dict.get('sub_device_id', None)
+        sub_device_id = request_dict.get('subDeviceId', None)
 
         if not all([sub_device_id]):
             return response.json(444)
@@ -173,3 +175,101 @@ class GatewaySubDeviceView(View):
         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 cycle: 时间周期
+        @request_dict page: 页数
+        @request_dict size: 条数
+        @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)
+        now_time = int(time.time())
+        try:
+            if not cycle:
+                page = request_dict.get('page', None)
+                size = request_dict.get('size', None)
+                if not all([page, size]):
+                    return response.json(444)
+                page, size = int(page), int(size)
+                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))
+            else:
+                record_dict = {}
+                record_list = []
+                if cycle == '24 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)
+
+                    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,
+                                                                   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)
+
+                    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,
+                                                                   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)
+
+                    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]
+
+                # 组织响应数据列表,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)
+        except Exception as e:
+            return response.json(500, repr(e))

+ 14 - 16
Controller/SerialNumberController.py

@@ -129,11 +129,9 @@ class SerialNumberView(View):
 
     def do_attach_uid(self, request_dict, response, request):
         serial_number = request_dict.get('serial_number', None)
-        region_id = request_dict.get('country_id', None)
         company_id = request_dict.get('company_id', None)
         token = request_dict.get('token', None)
         time_stamp = request_dict.get('time_stamp', None)
-        p2p_type = request_dict.get('p2ptype', 1)
 
         if not all([serial_number, company_id, token, time_stamp]):
             return response.json(444)
@@ -146,25 +144,11 @@ class SerialNumberView(View):
         serial = serial_number[0:6]
         full_serial = serial_number[0:9]
 
-        if serial_number[9:10]:
-            p2p_type = serial_number[9:10]
-
         try:
-            p2p_type = int(p2p_type)
-            if not region_id:
-                # 根据配置信息确定region_id
-                region_id = CommonService.confirm_region_id(request)
-
-            # 尚云: 地区为亚洲分配美洲的uid
-            if p2p_type == 1 and region_id == 2:
-                region_id = 3
-
             # 判断序列号是否已和企业关联
             company_serial_qs = CompanySerialModel.objects.filter(company__secret=company_id, serial_number=serial)
             if not company_serial_qs.exists():
                 return response.json(173)
-
-            # 当序列号已关联UID
             company_serial = company_serial_qs[0]
 
             if company_serial.status == 0:  # 该序列号未绑定企业
@@ -177,6 +161,20 @@ class SerialNumberView(View):
                 redisObj.CONN.expire(key, 60)
                 if not isLock:
                     return response.json(5)
+
+                region_id = request_dict.get('region_id', None)
+                if not region_id:
+                    # 根据配置信息确定region_id
+                    region_id = CommonService.confirm_region_id(request)
+
+                p2p_type = request_dict.get('p2ptype', 1)
+                if serial_number[9:10]:
+                    p2p_type = serial_number[9:10]
+                p2p_type = int(p2p_type)
+                # 尚云: 地区为亚洲分配美洲的uid
+                if p2p_type == 1 and region_id == 2:
+                    region_id = 3
+
                 with transaction.atomic():
                     count = 0
                     while count < 3:

+ 34 - 1
Model/models.py

@@ -1695,7 +1695,7 @@ class AppDeviceType(models.Model):
     id = models.AutoField(primary_key=True)
     model = models.SmallIntegerField(default=0, verbose_name='设备类型')  # 1:DVR, 2:IPC
     type = models.IntegerField(default=0, verbose_name='设备型号')
-    icon = models.CharField(default='', max_length=32, verbose_name='文件名')
+    icon = models.CharField(default='', max_length=200, verbose_name='图标文件路径')
 
     class Meta:
         db_table = 'app_device_type'
@@ -1712,6 +1712,7 @@ class DeviceNameLanguage(models.Model):
     sort = models.SmallIntegerField(default=0, verbose_name=u'升序排序')
 
     class Meta:
+        ordering = ('sort',)
         db_table = 'device_name_language'
         verbose_name = '设备名称语言表'
         verbose_name_plural = verbose_name
@@ -2233,6 +2234,22 @@ class DeviceDomainModel(models.Model):
         verbose_name_plural = verbose_name
 
 
+class DeviceDomainRegionModel(models.Model):
+    id = models.AutoField(primary_key=True, verbose_name=u'自增标记ID')
+    serial_number = models.CharField(max_length=9, default='', verbose_name='序列号')
+    ip = models.CharField(default='', max_length=32, verbose_name='ip')
+    country_name = models.CharField(max_length=20, default='', verbose_name='国家名')
+    api = models.CharField(max_length=50, default='', verbose_name='使用的域名')
+    region_id = models.SmallIntegerField(default=0, verbose_name='地区id')
+    add_time = models.DateTimeField(blank=True, auto_now_add=True, verbose_name=u'添加时间')
+    update_time = models.DateTimeField(blank=True, auto_now=True, verbose_name=u'更新时间')
+
+    class Meta:
+        db_table = 'device_domain_region'
+        verbose_name = u'设备域名地区表'
+        verbose_name_plural = verbose_name
+
+
 class RequestRecordModel(models.Model):
     id = models.AutoField(primary_key=True, verbose_name=u'自增ID')
     method = models.CharField(max_length=10, default='', verbose_name='请求类型')
@@ -2517,6 +2534,7 @@ class GatewaySubDevice(models.Model):
                                verbose_name='关联设备信息id')
     device_type = models.SmallIntegerField(default=0, verbose_name=u'设备类型')
     nickname = models.CharField(default='', max_length=32, verbose_name=u'设备名称')
+    ieee_addr = models.CharField(default='', max_length=64, verbose_name=u'长地址')
     src_addr = models.CharField(default='', max_length=16, verbose_name=u'短地址')
     status = models.SmallIntegerField(default=0, verbose_name='状态')  # 0:关闭, 1:开启
     created_time = models.IntegerField(default=0, verbose_name='创建时间')
@@ -2561,3 +2579,18 @@ class FamilyMemberJoin(models.Model):
         db_table = 'family_member_join'
         verbose_name = '家庭成员加入'
         verbose_name_plural = verbose_name
+
+
+class SensorRecord(models.Model):
+    id = models.AutoField(primary_key=True, verbose_name=u'自增标记ID')
+    gateway_sub_device_id = models.IntegerField(default=0, blank=True, verbose_name=u'网关子设备id')
+    alarm = models.CharField(default='', max_length=32, verbose_name=u'消息内容')
+    event_type = models.SmallIntegerField(default=0, verbose_name=u'消息类型')
+    created_time = models.IntegerField(default=0, verbose_name='创建时间')
+
+    class Meta:
+        db_table = 'sensor_record'
+        verbose_name = '传感器记录'
+        verbose_name_plural = verbose_name
+        app_label = 'PushModel'
+

+ 7 - 7
Object/IOTCore/IotObject.py

@@ -19,7 +19,7 @@ class IOTClient:
                                        aws_secret_access_key=AWS_IOT_SES_ACCESS_CHINA_SECRET)
             # 终端节点: https://cn-northwest-1.console.amazonaws.cn/iot/home?region=cn-northwest-1#/settings
             self.endpoint = 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
-            self.iotrole = AWS_IOT_SES_ACCESS_CHINA_ROLE
+            self.iot_role = AWS_IOT_SES_ACCESS_CHINA_ROLE
 
         elif region_id == 2 or region_id == 3:
             # 美东弗吉尼亚
@@ -27,7 +27,7 @@ class IOTClient:
                                        aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
                                        aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
             self.endpoint = 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
-            self.iotrole = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
+            self.iot_role = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
 
         elif region_id == 4:
             # 西欧爱尔兰
@@ -35,7 +35,7 @@ class IOTClient:
                                        aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
                                        aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
             self.endpoint = 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
-            self.iotrole = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
+            self.iot_role = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
 
     def create_provisioning_claim(self, templateName):
 
@@ -137,17 +137,17 @@ class IOTClient:
                 templateBody=templateBody,
                 parameters=parameters
             )
-            topicsql = "SELECT * FROM 'my/things/" + ThingName + "/shadow/update_lwt'"
+            topic_sql = "SELECT * FROM 'my/things/{}/shadow/update_lwt'".format(ThingName)
             self.client.create_topic_rule(
-                ruleName= ThingName + '_LWT',
+                ruleName=ThingName + '_LWT',
                 topicRulePayload={
-                    "sql": topicsql,
+                    "sql": topic_sql,
                     "ruleDisabled": False,
                     "awsIotSqlVersion": "2016-03-23",
                     'actions': [
                         {
                             'republish': {
-                                'roleArn': self.iotrole,
+                                'roleArn': self.iot_role,
                                 'topic': '$$aws/things/' + ThingName + '/shadow/update',
                                 'qos': 1
                             }

+ 3 - 1
Object/ResponseObject.py

@@ -113,6 +113,7 @@ class ResponseObject(object):
             10054: 'The AI service has expired',
             10055: 'The AI does not recognize any labels',
             10056: 'The device has enabled automatic renewal of cloud storage package and cannot be transferred for the time being',
+            10057: "Can't delete",
         }
         data_cn = {
             0: '成功',
@@ -219,6 +220,7 @@ class ResponseObject(object):
             10054: 'AI服务已过期',
             10055: 'AI没有识别到任何标签',
             10056: '该设备已开通云存套餐自动续费,暂时无法转移',
+            10057: '不能删除',
         }
         if self.lang == 'cn':
             msg = data_cn
@@ -234,7 +236,7 @@ class ResponseObject(object):
             message = '系统错误,code不存在'
         print(self.lang == 'cn')
         print(msg)
-        if self.returntype=='pc':
+        if self.returntype == 'pc':
             return {'code': code, 'msg': message, 'data': res, 'error_code': code}
         return {'result_code': code, 'reason': message, 'result': res, 'error_code': code}
 

+ 216 - 0
Object/utils/SymmetricCryptoUtil.py

@@ -0,0 +1,216 @@
+from Crypto.Cipher import AES
+import base64
+import binascii
+
+
+# 数据类
+class MData:
+    def __init__(self, data=b"", characterSet='utf-8'):
+        # data肯定为bytes
+        self.data = data
+        self.characterSet = characterSet
+
+    def saveData(self, FileName):
+        with open(FileName, 'wb') as f:
+            f.write(self.data)
+
+    def fromString(self, data):
+        self.data = data.encode(self.characterSet)
+        return self.data
+
+    def fromBase64(self, data):
+        self.data = base64.b64decode(data.encode(self.characterSet))
+        return self.data
+
+    def fromHexStr(self, data):
+        self.data = binascii.a2b_hex(data)
+        return self.data
+
+    def toString(self):
+        return self.data.decode(self.characterSet)
+
+    def toBase64(self):
+        return base64.b64encode(self.data).decode()
+
+    def toHexStr(self):
+        return binascii.b2a_hex(self.data).decode()
+
+    def toBytes(self):
+        return self.data
+
+    def __str__(self):
+        try:
+            return self.toString()
+        except Exception:
+            return self.toBase64()
+
+
+"""
+封装类
+"""
+
+
+class AESencrypt:
+    def __init__(self, encode_key, mode, iv_key=b'', paddingMode="NoPadding", characterSet="utf-8"):
+        """
+        构建一个AES对象
+        key: 秘钥,字节型数据
+        mode: 使用模式,只提供两种,AES.MODE_CBC, AES.MODE_ECB
+        iv: iv偏移量,字节型数据
+        paddingMode: 填充模式,默认为NoPadding, 可选NoPadding,ZeroPadding,PKCS5Padding,PKCS7Padding
+        characterSet: 字符集编码
+        """
+        self.key = encode_key
+        self.mode = mode
+        self.iv = iv_key
+        self.characterSet = characterSet
+        self.paddingMode = paddingMode
+        self.data = ""
+
+    @classmethod
+    def __zero_padding(cls, data):
+        data += b'\x00'
+        while len(data) % 16 != 0:
+            data += b'\x00'
+        return data
+
+    @classmethod
+    def __strip_zero_padding(cls, data):
+        data = data[:-1]
+        while len(data) % 16 != 0:
+            data = data.rstrip(b'\x00')
+            if data[-1] != b"\x00":
+                break
+        return data
+
+    def __PKCS5_7Padding(self, data):
+        needSize = 16 - len(data) % 16
+        if needSize == 0:
+            needSize = 16
+        return data + needSize.to_bytes(1, 'little') * needSize
+
+    def __StripPKCS5_7Padding(self, data):
+        paddingSize = data[-1]
+        return data.rstrip(paddingSize.to_bytes(1, 'little'))
+
+    def __paddingData(self, data):
+        if self.paddingMode == "NoPadding":
+            if len(data) % 16 == 0:
+                return data
+            else:
+                return self.__zero_padding(data)
+        elif self.paddingMode == "ZeroPadding":
+            return self.__zero_padding(data)
+        elif self.paddingMode == "PKCS5Padding" or self.paddingMode == "PKCS7Padding":
+            return self.__PKCS5_7Padding(data)
+        else:
+            print("不支持Padding")
+
+    def __stripPaddingData(self, data):
+        if self.paddingMode == "NoPadding":
+            return self.__strip_zero_padding(data)
+        elif self.paddingMode == "ZeroPadding":
+            return self.__strip_zero_padding(data)
+
+        elif self.paddingMode == "PKCS5Padding" or self.paddingMode == "PKCS7Padding":
+            return self.__StripPKCS5_7Padding(data)
+        else:
+            print("不支持Padding")
+
+    def setCharacterSet(self, characterSet):
+        """
+        设置字符集编码
+        characterSet: 字符集编码
+        """
+        self.characterSet = characterSet
+
+    def setPaddingMode(self, mode):
+        """
+        设置填充模式
+        mode: 可选NoPadding,ZeroPadding,PKCS5Padding,PKCS7Padding
+        """
+        self.paddingMode = mode
+
+    def decryptFromBase64(self, entext):
+        """
+        从base64编码字符串编码进行AES解密
+        entext: 数据类型str
+        """
+        mData = MData(characterSet=self.characterSet)
+        self.data = mData.fromBase64(entext)
+        return self.__decrypt()
+
+    def decryptFromHexStr(self, entext):
+        """
+        从hexstr编码字符串编码进行AES解密
+        entext: 数据类型str
+        """
+        mData = MData(characterSet=self.characterSet)
+        self.data = mData.fromHexStr(entext)
+        return self.__decrypt()
+
+    def decryptFromString(self, entext):
+        """
+        从字符串进行AES解密
+        entext: 数据类型str
+        """
+        mData = MData(characterSet=self.characterSet)
+        self.data = mData.fromString(entext)
+        return self.__decrypt()
+
+    def decryptFromBytes(self, entext):
+        """
+        从二进制进行AES解密
+        entext: 数据类型bytes
+        """
+        self.data = entext
+        return self.__decrypt()
+
+    def encryptFromString(self, data):
+        """
+        对字符串进行AES加密
+        data: 待加密字符串,数据类型为str
+        """
+        self.data = data.encode(self.characterSet)
+        return self.__encrypt()
+
+    def __encrypt(self):
+        """
+        加密数据
+        @return:
+        """
+        if self.mode == AES.MODE_CBC:
+            aes = AES.new(self.key, self.mode, self.iv)
+        elif self.mode == AES.MODE_ECB:
+            aes = AES.new(self.key, self.mode)
+        else:
+            print("不支持这种模式")
+            return
+
+        data = self.__paddingData(self.data)
+        enData = aes.encrypt(data)
+        return MData(enData)
+
+    def __decrypt(self):
+        if self.mode == AES.MODE_CBC:
+            aes = AES.new(self.key, self.mode, self.iv)
+        elif self.mode == AES.MODE_ECB:
+            aes = AES.new(self.key, self.mode)
+        else:
+            print("不支持这种模式")
+            return
+        data = aes.decrypt(self.data)
+        mData = MData(self.__stripPaddingData(data), characterSet=self.characterSet)
+        return mData
+
+
+if __name__ == '__main__':
+    key = b"1234567812345678"
+    iv = b"0000000000000000"
+    aes = AESencrypt(key, AES.MODE_CBC, iv, paddingMode="ZeroPadding", characterSet='utf-8')
+
+    str_data = "dddd321123."
+    rData = aes.encryptFromString(str_data)
+    print("加密:", rData.toBase64())
+    rData = aes.decryptFromBase64(rData.toBase64())
+    print("解密:", rData)

+ 1 - 1
Service/CommonService.py

@@ -594,7 +594,7 @@ GCqvlyw5dfxNA+EtxNE2wCW/LW7ENJlACgcfgPlBZtpLheWoZB/maw4=
         if company_mark == '11A':
             return 'Ansjer_Device_' + thing_name_suffix
         elif company_mark == '11L':
-            return 'Loocam_Device_' + thing_name_suffix
+            return 'LC_' + thing_name_suffix
         else:
             return thing_name_suffix
 

BIN
requirements.txt