IotCoreController.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import hashlib
  4. import json
  5. import time
  6. import uuid
  7. import boto3
  8. from django.views import View
  9. from Controller.DeviceConfirmRegion import Device_Region
  10. from Model.models import Device_User, Device_Info, iotdeviceInfoModel, UIDCompanySerialModel, \
  11. SerialNumberModel
  12. from Object.IOTCore.IotObject import IOTClient
  13. from Object.ResponseObject import ResponseObject
  14. from Service.CommonService import CommonService
  15. class IotCoreView(View):
  16. def get(self, request, *args, **kwargs):
  17. request.encoding = 'utf-8'
  18. request_dict = request.GET
  19. operation = kwargs.get('operation', None)
  20. return self.validate(operation, request_dict, request)
  21. def post(self, request, *args, **kwargs):
  22. request.encoding = 'utf-8'
  23. request_dict = request.POST
  24. operation = kwargs.get('operation', None)
  25. return self.validate(operation, request_dict, request)
  26. def validate(self, operation, request_dict, request):
  27. response = ResponseObject()
  28. if operation == 'createKeysAndCertificate':
  29. return self.create_keys_and_certificate(request_dict, response, request)
  30. elif operation == 'thingRegroup':
  31. return self.thing_regroup(request_dict, response, request)
  32. else:
  33. return response.json(404)
  34. # CVM注册 :正使用
  35. def create_keys_and_certificate(self, request_dict, response, request):
  36. serial_number = request_dict.get('serial_number', None)
  37. serial_number_code = request_dict.get('serial_number_code', None)
  38. token = request_dict.get('token', None)
  39. time_stamp = request_dict.get('time_stamp', None)
  40. device_version = request_dict.get('device_version', None).replace('.', '_') # 物品组命名不能包含'.'
  41. language = request_dict.get('language', None)
  42. if serial_number and token and time_stamp and serial_number_code and device_version and language:
  43. serial_number_code = CommonService.decode_data(serial_number_code)
  44. token = int(CommonService.decode_data(token))
  45. time_stamp = int(time_stamp)
  46. now_time = int(time.time())
  47. distance = now_time - time_stamp
  48. thingGroup = device_version + '_' + language
  49. if token != time_stamp or distance > 60000 or distance < -60000 or serial_number != serial_number_code: # 为了全球化时间控制在一天内
  50. return response.json(404)
  51. serial = serial_number[0:6]
  52. iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=serial)
  53. # 判断设备是否已注册证书
  54. if not iotqs.exists():
  55. ip = CommonService.get_ip_address(request)
  56. region_id = Device_Region().get_device_region(ip)
  57. iotClient = IOTClient(region_id)
  58. res = iotClient.create_keys_and_certificate(serial_number, thingGroup)
  59. nowTime = int(time.time())
  60. token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest()
  61. sn = SerialNumberModel.objects.get(serial_number=serial)
  62. iotdeviceInfoModel.objects.create(serial_number=sn,
  63. endpoint=res[0]['endpoint'],
  64. certificate_id=res[0]['certificateId'],
  65. certificate_pem=res[0]['certificatePem'],
  66. public_key=res[0]['publicKey'],
  67. private_key=res[0]['privateKey'],
  68. thing_name=res[1]['ThingName'],
  69. token_iot_number=token_iot_number
  70. )
  71. res = {
  72. 'certificateId': res[0]['certificateId'],
  73. 'certificatePem': res[0]['certificatePem'],
  74. 'publicKey': res[0]['publicKey'],
  75. 'privateKey': res[0]['privateKey'],
  76. 'endpoint': res[0]['endpoint']
  77. }
  78. return response.json(0, {'res': res})
  79. else:
  80. iot = iotqs[0]
  81. res = {
  82. 'certificateId': iot.certificate_id,
  83. 'certificatePem': iot.certificate_pem,
  84. 'publicKey': iot.public_key,
  85. 'privateKey': iot.private_key,
  86. 'endpoint': iot.endpoint
  87. }
  88. # print('此设备已注册证书')
  89. return response.json(0, {'res': res})
  90. else:
  91. return response.json(444)
  92. def thing_regroup(self, request_dict, response, request):
  93. # 物品重新分组
  94. token = request_dict.get('token', None)
  95. time_stamp = request_dict.get('time_stamp', None)
  96. serial_number = request_dict.get('serial_number', None)
  97. device_version = request_dict.get('device_version', None)
  98. language = request_dict.get('language', None)
  99. if not all([serial_number, device_version, language, token, time_stamp]):
  100. return response.json(444)
  101. # 封装token认证
  102. token = int(CommonService.decode_data(token))
  103. time_stamp = int(time_stamp)
  104. now_time = int(time.time())
  105. distance = now_time - time_stamp
  106. if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内
  107. return response.json(404)
  108. ip = CommonService.get_ip_address(request)
  109. region_id = Device_Region().get_device_region(ip)
  110. thingName = 'Ansjer_Device_' + serial_number
  111. new_thingGroupName = (device_version + '_' + language).replace('.', '_') # 物品组命名不能包含'.'
  112. # 调试参数
  113. # thingName = 'Ansjer_Device_00EBEX'
  114. # new_thingGroupName = 'C1Pro_V1_0_1_cn'
  115. iotClient = IOTClient(region_id)
  116. try:
  117. # 获取旧物品组
  118. list_groups_res = iotClient.client.list_thing_groups_for_thing(thingName=thingName, maxResults=1)
  119. old_thingGroupName = list_groups_res['thingGroups'][0]['groupName']
  120. # 没有新物品组则创建
  121. list_thing_groups_res = iotClient.client.list_thing_groups(namePrefixFilter=new_thingGroupName
  122. , maxResults=1, recursive=False)
  123. if not list_thing_groups_res['thingGroups']:
  124. attributes = {
  125. "update_time": "0"
  126. }
  127. thingGroupProperties = {
  128. "thingGroupDescription": "OTA",
  129. "attributePayload": {
  130. "attributes": attributes,
  131. "merge": False # 更新时覆盖掉而不是合并
  132. }
  133. }
  134. iotClient.client.create_thing_group(thingGroupName=new_thingGroupName
  135. , thingGroupProperties=thingGroupProperties)
  136. iotClient.client.update_thing_groups_for_thing(thingName=thingName
  137. , thingGroupsToAdd=[new_thingGroupName]
  138. , thingGroupsToRemove=[old_thingGroupName])
  139. # 更新设备版本信息
  140. Device_Info.objects.filter(serial_number=serial_number).update(version=device_version)
  141. return response.json(0)
  142. except Exception as e:
  143. print(e)
  144. return response.json(500, repr(e))