Parcourir la source

同步序列号数据接口

locky il y a 1 an
Parent
commit
1cab636516
1 fichiers modifiés avec 159 ajouts et 7 suppressions
  1. 159 7
      AdminController/SerialManageController.py

+ 159 - 7
AdminController/SerialManageController.py

@@ -10,16 +10,18 @@
 import json
 import json
 import time
 import time
 
 
+import requests
 from django.db import transaction
 from django.db import transaction
 from django.utils.decorators import method_decorator
 from django.utils.decorators import method_decorator
 from django.views.decorators.csrf import csrf_exempt
 from django.views.decorators.csrf import csrf_exempt
 from django.views.generic.base import View
 from django.views.generic.base import View
 
 
 from Model.models import CompanyModel, VPGModel, UIDModel, UIDCompanySerialModel, CompanySerialModel, \
 from Model.models import CompanyModel, VPGModel, UIDModel, UIDCompanySerialModel, CompanySerialModel, \
-    LogModel
+    LogModel, iotdeviceInfoModel
 from Object.ResponseObject import ResponseObject
 from Object.ResponseObject import ResponseObject
 from Object.TokenObject import TokenObject
 from Object.TokenObject import TokenObject
 from Service.CommonService import CommonService
 from Service.CommonService import CommonService
+from Ansjer.config import SERVER_DOMAIN_TEST, SERVER_DOMAIN_CN, SERVER_DOMAIN_US, SERVER_DOMAIN_EUR
 
 
 
 
 class SerialView(View):
 class SerialView(View):
@@ -41,6 +43,8 @@ class SerialView(View):
         response = ResponseObject()
         response = ResponseObject()
         if operation == 'uploadUid':
         if operation == 'uploadUid':
             return self.uploadUid(request, request_dict, response)
             return self.uploadUid(request, request_dict, response)
+        elif operation == 'getSerialData':  # 获取需要同步的序列号数据
+            return self.getSerialData(request_dict, response)
         else:
         else:
             token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
             token = TokenObject(request.META.get('HTTP_AUTHORIZATION'))
             if token.code != 0:
             if token.code != 0:
@@ -50,11 +54,13 @@ class SerialView(View):
                 return self.company_page(request_dict, response)
                 return self.company_page(request_dict, response)
             if operation == 'number/page':
             if operation == 'number/page':
                 return self.serial_page(request_dict, response)
                 return self.serial_page(request_dict, response)
+            if operation == 'syncSerial':   # 同步序列号数据
+                return self.sync_serial(request_dict, response)
             if operation == 'vpg-info/page':
             if operation == 'vpg-info/page':
                 return self.vpg_page(request_dict, response)
                 return self.vpg_page(request_dict, response)
             if operation == 'uid-info/page':
             if operation == 'uid-info/page':
                 return self.uid_page(request_dict, response)
                 return self.uid_page(request_dict, response)
-            return response.json(0)
+            return response.json(414)
 
 
     @classmethod
     @classmethod
     def uploadUid(cls, request, request_dict, response):
     def uploadUid(cls, request, request_dict, response):
@@ -128,7 +134,7 @@ class SerialView(View):
             return response.json(0)
             return response.json(0)
         except Exception as e:
         except Exception as e:
             print(e)
             print(e)
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
     @classmethod
     @classmethod
     def company_page(cls, request_dict, response):
     def company_page(cls, request_dict, response):
@@ -155,7 +161,7 @@ class SerialView(View):
             return response.json(0, {'list': list(company_page), 'total': total})
             return response.json(0, {'list': list(company_page), 'total': total})
         except Exception as e:
         except Exception as e:
             print(e)
             print(e)
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
     @classmethod
     @classmethod
     def serial_page(cls, request_dict, response):
     def serial_page(cls, request_dict, response):
@@ -187,7 +193,153 @@ class SerialView(View):
             return response.json(0, {'list': list(serial_number_page), 'total': total})
             return response.json(0, {'list': list(serial_number_page), 'total': total})
         except Exception as e:
         except Exception as e:
             print(e)
             print(e)
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @staticmethod
+    def sync_serial(request_dict, response):
+        serial = request_dict.get('serial', None)
+        sync_region = request_dict.get('syncRegion', None)
+        if not all([serial, sync_region]):
+            return response.json(444)
+
+        # 判断序列号是否已绑定uid
+        uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial)
+        if uid_company_serial_qs.exists():
+            return response.json(174)
+
+        if sync_region == 'test':
+            url = SERVER_DOMAIN_TEST
+        elif sync_region == 'cn':
+            url = SERVER_DOMAIN_CN
+        elif sync_region == 'us':
+            url = SERVER_DOMAIN_US
+        elif sync_region == 'eu':
+            url = SERVER_DOMAIN_EUR
+        else:
+            return response.json(444)
+
+        try:
+            # 请求需要同步的地区获取数据
+            url = url + 'serial/getSerialData'
+            data = {'serial': serial}
+            req = requests.post(url=url, data=data, timeout=5)
+            if req.status_code != 200:
+                return response.json(503)
+            req = req.json()
+            if req['result_code'] != 0:
+                return response.json(173)
+            res_data = req['result']['res_data']
+
+            # 查询是否存在该uid,存在修改状态为已使用,否则写入数据
+            uid = res_data['uid']
+            uid_qs = UIDModel.objects.filter(uid=uid).values('id')
+            with transaction.atomic():
+                if uid_qs.exists():
+                    uid_qs.update(status=2)
+                    uid_id = uid_qs['id']
+                else:
+                    uid_data = {
+                        'uid': uid,
+                        'mac': res_data['mac'],
+                        'uid_extra': res_data['uid_extra'],
+                        'status': res_data['status'],
+                        'add_time': res_data['add_time'],
+                        'update_time': res_data['update_time'],
+                        'area': res_data['area'],
+                        'vpg_id': res_data['vpg_id'],
+                        'p2p_type': res_data['p2p_type'],
+                        'full_uid_code': res_data['full_uid_code'],
+                        'platform': res_data['platform'],
+                        'init_string': res_data['init_string'],
+                        'init_string_app': res_data['init_string_app']
+                    }
+                    uid_obj = UIDModel.objects.create(**uid_data)
+                    uid_id = uid_obj.id
+
+                # 查询tb_company_serial表id
+                company_serial_qs = CompanySerialModel.objects.filter(serial_number=serial).values('id')
+                company_serial_id = company_serial_qs[0]['id']
+                # 序列号绑定uid
+                now_time = int(time.time())
+                UIDCompanySerialModel.objects.create(add_time=now_time, update_time=now_time,
+                                                     uid_id=uid_id, company_serial_id=company_serial_id)
+                # 修改序列号状态为绑定uid
+                company_serial_qs.update(status=2)
+
+                # 同步iot数据
+                if res_data['certificate_id']:
+                    iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial).\
+                        values('certificate_id')
+                    iot_data = {
+                        'certificate_id': res_data['certificate_id'],
+                        'certificate_pem': res_data['certificate_pem'],
+                        'public_key': res_data['public_key'],
+                        'private_key': res_data['private_key'],
+                        'thing_name': res_data['thing_name'],
+                        'thing_groups': res_data['thing_groups'],
+                        'endpoint': res_data['endpoint'],
+                        'token_iot_number': res_data['token_iot_number']
+                    }
+                    if iot_device_info_qs.exists():
+                        if iot_device_info_qs[0]['certificate_id'] != res_data['certificate_id']:
+                            iot_device_info_qs.update(**iot_data)
+                    else:
+                        iot_data['serial_number'] = serial
+                        iotdeviceInfoModel.objects.create(**iot_data)
+            return response.json(0)
+        except Exception as e:
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
+
+    @staticmethod
+    def getSerialData(request_dict, response):
+        serial = request_dict.get('serial', None)
+        if not serial:
+            return response.json(444)
+
+        try:
+            # 查询绑定的uid数据
+            uid_company_serial_qs = UIDCompanySerialModel.objects.filter(company_serial__serial_number=serial).\
+                values('uid__uid', 'uid__mac', 'uid__uid_extra', 'uid__status', 'uid__add_time', 'uid__update_time',
+                       'uid__area', 'uid__vpg_id', 'uid__p2p_type', 'uid__full_uid_code', 'uid__platform',
+                       'uid__init_string', 'uid__init_string_app')
+            if not uid_company_serial_qs.exists():
+                return response.json(173)
+
+            res_data = {
+                'uid': uid_company_serial_qs[0]['uid__uid'],
+                'mac': uid_company_serial_qs[0]['uid__mac'],
+                'uid_extra': uid_company_serial_qs[0]['uid__uid_extra'],
+                'status': uid_company_serial_qs[0]['uid__status'],
+                'add_time': uid_company_serial_qs[0]['uid__add_time'],
+                'update_time': uid_company_serial_qs[0]['uid__update_time'],
+                'area': uid_company_serial_qs[0]['uid__area'],
+                'vpg_id': uid_company_serial_qs[0]['uid__vpg_id'],
+                'p2p_type': uid_company_serial_qs[0]['uid__p2p_type'],
+                'full_uid_code': uid_company_serial_qs[0]['uid__full_uid_code'],
+                'platform': uid_company_serial_qs[0]['uid__platform'],
+                'init_string': uid_company_serial_qs[0]['uid__init_string'],
+                'init_string_app': uid_company_serial_qs[0]['uid__init_string_app']
+            }
+
+            # 查询iot数据
+            iot_device_info_qs = iotdeviceInfoModel.objects.filter(serial_number=serial).values(
+                'certificate_id', 'certificate_pem', 'public_key', 'private_key', 'thing_name',
+                'thing_groups', 'endpoint', 'token_iot_number')
+            if iot_device_info_qs.exists():
+                res_data['certificate_id'] = iot_device_info_qs[0]['certificate_id']
+                res_data['certificate_pem'] = iot_device_info_qs[0]['certificate_pem']
+                res_data['public_key'] = iot_device_info_qs[0]['public_key']
+                res_data['private_key'] = iot_device_info_qs[0]['private_key']
+                res_data['thing_name'] = iot_device_info_qs[0]['thing_name']
+                res_data['thing_groups'] = iot_device_info_qs[0]['thing_groups']
+                res_data['endpoint'] = iot_device_info_qs[0]['endpoint']
+                res_data['token_iot_number'] = iot_device_info_qs[0]['token_iot_number']
+
+            # 修改序列号状态为占用
+            CompanySerialModel.objects.filter(serial_number=serial).update(status=3)
+            return response.json(0, {'res_data': res_data})
+        except Exception as e:
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
     @classmethod
     @classmethod
     def vpg_page(cls, request_dict, response):
     def vpg_page(cls, request_dict, response):
@@ -228,7 +380,7 @@ class SerialView(View):
             return response.json(173)
             return response.json(173)
         except Exception as e:
         except Exception as e:
             print(e)
             print(e)
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))
 
 
     @classmethod
     @classmethod
     def uid_page(cls, request_dict, response):
     def uid_page(cls, request_dict, response):
@@ -299,4 +451,4 @@ class SerialView(View):
 
 
         except Exception as e:
         except Exception as e:
             print(e)
             print(e)
-            return response.json(500, repr(e))
+            return response.json(500, 'error_line:{}, error_msg:{}'.format(e.__traceback__.tb_lineno, repr(e)))