IotCoreController.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  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. uid_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 and distance > 600: 暂时去掉延时
  50. # if token != time_stamp or serial_number != serial_number_code :
  51. # return response.json(404)
  52. serial = serial_number[0:6]
  53. iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=serial)
  54. # 判断设备是否已注册证书
  55. if not iotqs.exists():
  56. ip = CommonService.get_ip_address(request)
  57. region_id = Device_Region().get_device_region(ip)
  58. iotClient = IOTClient(region_id)
  59. res = iotClient.create_keys_and_certificate(serial_number, thingGroup)
  60. nowTime = int(time.time())
  61. token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest()
  62. sn = SerialNumberModel.objects.get(serial_number=serial)
  63. iotdeviceInfoModel.objects.create(serial_number=sn,
  64. endpoint=res[0]['endpoint'],
  65. certificate_id=res[0]['certificateId'],
  66. certificate_pem=res[0]['certificatePem'],
  67. public_key=res[0]['publicKey'],
  68. private_key=res[0]['privateKey'],
  69. thing_name=res[1]['ThingName'],
  70. token_iot_number=token_iot_number
  71. )
  72. res = {
  73. 'certificateId': res[0]['certificateId'],
  74. 'certificatePem': res[0]['certificatePem'],
  75. 'publicKey': res[0]['publicKey'],
  76. 'privateKey': res[0]['privateKey'],
  77. 'endpoint': res[0]['endpoint']
  78. }
  79. return response.json(0, {'res': res})
  80. else:
  81. iot = iotqs[0]
  82. res = {
  83. 'certificateId': iot.certificate_id,
  84. 'certificatePem': iot.certificate_pem,
  85. 'publicKey': iot.public_key,
  86. 'privateKey': iot.private_key,
  87. 'endpoint': iot.endpoint
  88. }
  89. # print('此设备已注册证书')
  90. return response.json(0, {'res': res})
  91. else:
  92. return response.json(444)
  93. def thing_regroup(self, request_dict, response, request):
  94. # 物品重新分组
  95. # token = request_dict.get('token', None)
  96. # time_stamp = request_dict.get('time_stamp', None)
  97. serial_number = request_dict.get('serial_number', None)
  98. device_version = request_dict.get('device_version', None)
  99. language = request_dict.get('language', None)
  100. if not all([serial_number, device_version, language]):
  101. return response.json(444)
  102. # 封装token认证
  103. # token = int(CommonService.decode_data(token))
  104. # time_stamp = int(time_stamp)
  105. # now_time = int(time.time())
  106. # distance = now_time - time_stamp
  107. # if token != time_stamp and distance > 600: 暂时去掉延时
  108. # if token != time_stamp or serial_number != serial_number_code :
  109. # return response.json(404)
  110. # ip = CommonService.get_ip_address(request)
  111. # region_id = Device_Region().get_device_region(ip)
  112. thingName = 'Ansjer_Device_' + serial_number
  113. new_thingGroupName = (device_version + '_' + language).replace('.', '_') # 物品组命名不能包含'.'
  114. # 调试参数
  115. # thingName = 'Ansjer_Device_00EBEX'
  116. # new_thingGroupName = 'C1Pro_V1_0_1_cn'
  117. region_id = 1
  118. iotClient = IOTClient(region_id)
  119. try:
  120. # 获取旧物品组
  121. list_groups_res = iotClient.client.list_thing_groups_for_thing(thingName=thingName, maxResults=1)
  122. old_thingGroupName = list_groups_res['thingGroups'][0]['groupName']
  123. # 没有新物品组则创建
  124. list_thing_groups_res = iotClient.client.list_thing_groups(namePrefixFilter=new_thingGroupName
  125. , maxResults=1, recursive=False)
  126. if not list_thing_groups_res['thingGroups']:
  127. attributes = {
  128. "update_time": "0"
  129. }
  130. thingGroupProperties = {
  131. "thingGroupDescription": "OTA",
  132. "attributePayload": {
  133. "attributes": attributes,
  134. "merge": False # 更新时覆盖掉而不是合并
  135. }
  136. }
  137. iotClient.client.create_thing_group(thingGroupName=new_thingGroupName
  138. , thingGroupProperties=thingGroupProperties)
  139. iotClient.client.update_thing_groups_for_thing(thingName=thingName
  140. , thingGroupsToAdd=[new_thingGroupName]
  141. , thingGroupsToRemove=[old_thingGroupName])
  142. # 更新设备版本信息
  143. Device_Info.objects.filter(serial_number=serial_number).update(version=device_version)
  144. return response.json(0)
  145. except Exception as e:
  146. print(e)
  147. return response.json(500, repr(e))