#!/usr/bin/env python3 # -*- coding: utf-8 -*- import hashlib import json import time import uuid import boto3 from django.views import View from Controller.DeviceConfirmRegion import Device_Region from Model.models import Device_User, Device_Info, iotdeviceInfoModel, UIDCompanySerialModel, \ SerialNumberModel from Object.IOTCore.IotObject import IOTClient from Object.ResponseObject import ResponseObject from Service.CommonService import CommonService class IotCoreView(View): def get(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.GET operation = kwargs.get('operation', None) return self.validate(operation, request_dict, request) def post(self, request, *args, **kwargs): request.encoding = 'utf-8' request_dict = request.POST operation = kwargs.get('operation', None) return self.validate(operation, request_dict, request) def validate(self, operation, request_dict, request): response = ResponseObject() if operation == 'createKeysAndCertificate': return self.create_keys_and_certificate(request_dict, response, request) elif operation == 'thingRegroup': return self.thing_regroup(request_dict, response, request) else: return response.json(404) # CVM注册 :正使用 def create_keys_and_certificate(self, request_dict, response, request): serial_number = request_dict.get('serial_number', None) serial_number_code = request_dict.get('serial_number_code', None) token = request_dict.get('token', None) time_stamp = request_dict.get('time_stamp', None) device_version = request_dict.get('device_version', None).replace('.', '_') # 物品组命名不能包含'.' language = request_dict.get('language', None) if serial_number and token and time_stamp and serial_number_code and device_version and language: serial_number_code = CommonService.decode_data(serial_number_code) token = int(CommonService.decode_data(token)) time_stamp = int(time_stamp) now_time = int(time.time()) distance = now_time - time_stamp thingGroup = device_version + '_' + language if token != time_stamp or distance > 60000 or distance < -60000 or serial_number != serial_number_code: # 为了全球化时间控制在一天内 return response.json(404) serial = serial_number[0:6] iotqs = iotdeviceInfoModel.objects.filter(serial_number__serial_number=serial) # 判断设备是否已注册证书 if not iotqs.exists(): ip = CommonService.get_ip_address(request) region_id = Device_Region().get_device_region(ip) iotClient = IOTClient(region_id) res = iotClient.create_keys_and_certificate(serial_number, thingGroup) nowTime = int(time.time()) token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest() sn = SerialNumberModel.objects.get(serial_number=serial) iotdeviceInfoModel.objects.create(serial_number=sn, endpoint=res[0]['endpoint'], certificate_id=res[0]['certificateId'], certificate_pem=res[0]['certificatePem'], public_key=res[0]['publicKey'], private_key=res[0]['privateKey'], thing_name=res[1]['ThingName'], token_iot_number=token_iot_number ) res = { 'certificateId': res[0]['certificateId'], 'certificatePem': res[0]['certificatePem'], 'publicKey': res[0]['publicKey'], 'privateKey': res[0]['privateKey'], 'endpoint': res[0]['endpoint'] } return response.json(0, {'res': res}) else: iot = iotqs[0] res = { 'certificateId': iot.certificate_id, 'certificatePem': iot.certificate_pem, 'publicKey': iot.public_key, 'privateKey': iot.private_key, 'endpoint': iot.endpoint } # print('此设备已注册证书') return response.json(0, {'res': res}) else: return response.json(444) def thing_regroup(self, request_dict, response, request): # 物品重新分组 token = request_dict.get('token', None) time_stamp = request_dict.get('time_stamp', None) serial_number = request_dict.get('serial_number', None) device_version = request_dict.get('device_version', None) language = request_dict.get('language', None) if not all([serial_number, device_version, language, token, time_stamp]): return response.json(444) # 封装token认证 token = int(CommonService.decode_data(token)) time_stamp = int(time_stamp) now_time = int(time.time()) distance = now_time - time_stamp if token != time_stamp or distance > 60000 or distance < -60000: # 为了全球化时间控制在一天内 return response.json(404) ip = CommonService.get_ip_address(request) region_id = Device_Region().get_device_region(ip) thingName = 'Ansjer_Device_' + serial_number new_thingGroupName = (device_version + '_' + language).replace('.', '_') # 物品组命名不能包含'.' # 调试参数 # thingName = 'Ansjer_Device_00EBEX' # new_thingGroupName = 'C1Pro_V1_0_1_cn' iotClient = IOTClient(region_id) try: # 获取旧物品组 list_groups_res = iotClient.client.list_thing_groups_for_thing(thingName=thingName, maxResults=1) old_thingGroupName = list_groups_res['thingGroups'][0]['groupName'] # 没有新物品组则创建 list_thing_groups_res = iotClient.client.list_thing_groups(namePrefixFilter=new_thingGroupName , maxResults=1, recursive=False) if not list_thing_groups_res['thingGroups']: attributes = { "update_time": "0" } thingGroupProperties = { "thingGroupDescription": "OTA", "attributePayload": { "attributes": attributes, "merge": False # 更新时覆盖掉而不是合并 } } iotClient.client.create_thing_group(thingGroupName=new_thingGroupName , thingGroupProperties=thingGroupProperties) iotClient.client.update_thing_groups_for_thing(thingName=thingName , thingGroupsToAdd=[new_thingGroupName] , thingGroupsToRemove=[old_thingGroupName]) # 更新设备版本信息 Device_Info.objects.filter(serial_number=serial_number).update(version=device_version) return response.json(0) except Exception as e: print(e) return response.json(500, repr(e))