浏览代码

Merge branch 'dev' into lang

lang 4 年之前
父节点
当前提交
a3d5d33d32
共有 2 个文件被更改,包括 89 次插入64 次删除
  1. 5 3
      Controller/IotCoreController.py
  2. 84 61
      Object/IOTCore/IotObject.py

+ 5 - 3
Controller/IotCoreController.py

@@ -46,15 +46,17 @@ class IotCoreView(View):
         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)
+        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:
+        if serial_number and token and time_stamp and serial_number_code and device_version and language:
             uid_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 and distance > 600: 暂时去掉延时
             if token != time_stamp or serial_number != serial_number_code :
@@ -70,7 +72,7 @@ class IotCoreView(View):
                 region_id = Device_Region().get_device_region(ip)
 
                 iotClient = IOTClient(region_id)
-                res = iotClient.create_keys_and_certificate(serial, device_version)
+                res = iotClient.create_keys_and_certificate(serial, thingGroup)
                 nowTime = int(time.time())
                 token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest()
 

+ 84 - 61
Object/IOTCore/IotObject.py

@@ -64,71 +64,94 @@ class IOTClient(IOTObject):
         }
         return res
 
-    def create_keys_and_certificate(self, serial_number, device_version):
-        result = self.client.create_keys_and_certificate(setAsActive=True)
-        res = {
-            'certificateId': result['certificateId'],
-            'certificatePem': result['certificatePem'],
-            'publicKey': result['keyPair']['PublicKey'],
-            'privateKey': result['keyPair']['PrivateKey'],
-            'endpoint': 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
-        }
-        # 根据证书ID注册物品和策略
-        templateBody = {
-            "Parameters": {
-                "ThingName": {
-                    "Type": "String"
-                },
-                "SerialNumber": {
-                    "Type": "String"
-                },
-                "DeviceLocation": {
-                    "Type": "String"
-                },
-                "AWS::IoT::Certificate::Id": {
-                    "Type": "String"
+    def create_keys_and_certificate(self, serial_number, thingGroup):
+        try:
+            result = self.client.create_keys_and_certificate(setAsActive=True)
+            res = {
+                'certificateId': result['certificateId'],
+                'certificatePem': result['certificatePem'],
+                'publicKey': result['keyPair']['PublicKey'],
+                'privateKey': result['keyPair']['PrivateKey'],
+                'endpoint': 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
+            }
+            # 搜索是否存在该物品组
+            thing_groups_res = self.client.list_thing_groups(nextToken='', maxResults=1,
+                                                             namePrefixFilter=thingGroup, recursive=False)
+            if thing_groups_res['thingGroups']:
+                thingGroupName = thing_groups_res['thingGroups'][0]['groupName']  # 获取物品组名称
+            else:
+                attributes = {
+                    "update_time": "0"
                 }
-            },
-            "Resources": {
-                "thing": {
-                    "Type": "AWS::IoT::Thing",
-                    "Properties": {
-                        "AttributePayload": {},
-                        # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
-                        "ThingName": {
-                            "Ref": "ThingName"
-                        },
-                        "ThingGroups": []
-                    },
-                    "OverrideSettings": {
-                        "AttributePayload": "MERGE",
-                        "ThingTypeName": "REPLACE",
-                        "ThingGroups": "DO_NOTHING"
+                thingGroupProperties = {
+                    "thingGroupDescription": "OTA",
+                    "attributePayload": {
+                        "attributes": attributes,
+                        "merge": False  # 更新时覆盖掉而不是合并
                     }
-                },
-                "certificate": {
-                    "Type": "AWS::IoT::Certificate",
-                    "Properties": {
-                        "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
-                        "Status": "Active"
+                }
+                create_thing_group_res = self.client.create_thing_group(thingGroupName=thingGroup,
+                                                                        thingGroupProperties=thingGroupProperties)
+                thingGroupName = create_thing_group_res['thingGroupName']  # 获取物品组名称
+            print('物品组:', thingGroupName)
+            # 根据证书ID注册物品和策略
+            templateBody = {
+                "Parameters": {
+                    "ThingName": {
+                        "Type": "String"
+                    },
+                    "SerialNumber": {
+                        "Type": "String"
+                    },
+                    "thingGroupName": {
+                        "Type": "String"
+                    },
+                    "AWS::IoT::Certificate::Id": {
+                        "Type": "String"
                     }
                 },
-                "policy": {
-                    "Properties": {
-                        "PolicyName": "My_Iot_Policy"
+                "Resources": {
+                    "thing": {
+                        "Type": "AWS::IoT::Thing",
+                        "Properties": {
+                            "AttributePayload": {},
+                            # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
+                            "ThingName": {
+                                "Ref": "ThingName"
+                            },
+                            "ThingGroups": [{"Ref": "thingGroupName"}]
+                        },
+                        "OverrideSettings": {
+                            "AttributePayload": "MERGE",
+                            "ThingTypeName": "REPLACE",
+                            "ThingGroups": "DO_NOTHING"
+                        }
                     },
-                    "Type": "AWS::IoT::Policy"
-                },
+                    "certificate": {
+                        "Type": "AWS::IoT::Certificate",
+                        "Properties": {
+                            "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
+                            "Status": "Active"
+                        }
+                    },
+                    "policy": {
+                        "Properties": {
+                            "PolicyName": "My_Iot_Policy"
+                        },
+                        "Type": "AWS::IoT::Policy"
+                    },
+                }
             }
-        }
-
-        templateBody = json.dumps(templateBody)
-        parameters = {"ThingName": "Ansjer_Device_" + serial_number,
-                      #"DeviceLocation": device_version,
-                      "AWS::IoT::Certificate::Id": res['certificateId']}
-        self.client.register_thing(
-            templateBody=templateBody,
-            parameters=parameters
-        )
-        return res, parameters
 
+            templateBody = json.dumps(templateBody)
+            parameters = {"ThingName": "Ansjer_Device_" + serial_number,
+                          "thingGroupName": thingGroupName,
+                          "AWS::IoT::Certificate::Id": res['certificateId']}
+            self.client.register_thing(
+                templateBody=templateBody,
+                parameters=parameters
+            )
+            return res, parameters
+        except Exception as e:
+            print(e)
+            # return response.json(500, repr(e))