Browse Source

设备获取证书3

chenshibin 4 years ago
parent
commit
78feee4aa6
2 changed files with 36 additions and 290 deletions
  1. 8 29
      Controller/IotCoreController.py
  2. 28 261
      Object/IOTCore/IotObject.py

+ 8 - 29
Controller/IotCoreController.py

@@ -9,7 +9,7 @@ import boto3
 from django.views import View
 
 from Model.models import Device_User, Device_Info, RegionCountryModel, iotdeviceInfoModel
-from Object.IOTCore.IotObject import ChinaIOTClient, AsiaIOTClient, EuropeIOTClient, AmericaIOTClient
+from Object.IOTCore.IotObject import IOTClient
 from Object.ResponseObject import ResponseObject
 from Service.CommonService import CommonService
 
@@ -63,20 +63,8 @@ class IotCoreView(View):
             region_country_qs = RegionCountryModel.objects.filter(number=region_country_qs[0]['userID__region_country'])
             if region_country_qs.exists():
                 user_region = region_country_qs[0]
-
-                if user_region.region_id == 1:
-                    iotClient = ChinaIOTClient()
-
-                    return response.json(0, {'res': iotClient.create_provisioning_claim('Ansjer_Iot_Queue')})
-                elif user_region.region_id == 2:
-                    iotClient = AsiaIOTClient()
-                    return response.json(0, {'res': iotClient.create_provisioning_claim('Ansjer_Iot_Queue')})
-                elif user_region.region_id == 3:
-                    iotClient = EuropeIOTClient()
-                    return response.json(0, {'res': iotClient.create_provisioning_claim('Ansjer_Iot_Queue')})
-                else:
-                    iotClient = AmericaIOTClient()
-                    return response.json(0, {'res': iotClient.create_provisioning_claim('Ansjer_Iot_Queue')})
+                iotClient = IOTClient(user_region.region_id)
+                return response.json(0, {'res': iotClient.create_provisioning_claim('Ansjer_Iot_Queue')})
         else:
             return response.json(444)
 
@@ -86,6 +74,7 @@ class IotCoreView(View):
         uid_code = request_dict.get('uid_code', None)
         token = request_dict.get('token', None)
         time_stamp = request_dict.get('time_stamp', None)
+        device_version = request_dict.get('device_version', None)
 
         if uid and token and time_stamp and uid_code:
             uid_code = CommonService.decode_data(uid_code)
@@ -96,8 +85,8 @@ class IotCoreView(View):
             distance = now_time - time_stamp
 
             # if token != time_stamp and distance > 600: 暂时去掉延时
-            if token != time_stamp or uid != uid_code :
-                return response.json(404)
+            # if token != time_stamp or uid != uid_code :
+            #     return response.json(404)
 
             region_country_qs = Device_Info.objects.filter(UID=uid).values('userID__region_country')
             if not region_country_qs.exists() or region_country_qs[0]['userID__region_country'] == 0 :
@@ -112,18 +101,8 @@ class IotCoreView(View):
                 if region_country_qs.exists():
                     user_region = region_country_qs[0]
 
-                    if user_region.region_id == 1:
-                        iotClient = ChinaIOTClient()
-
-                    elif user_region.region_id == 2:
-                        iotClient = AsiaIOTClient()
-
-                    elif user_region.region_id == 3:
-                        iotClient = EuropeIOTClient()
-
-                    else:
-                        iotClient = AmericaIOTClient()
-                    res = iotClient.create_keys_and_certificate(uid)
+                    iotClient = IOTClient(user_region.region_id)
+                    res = iotClient.create_keys_and_certificate(uid, device_version)
                     nowTime = int(time.time())
                     token_iot_number = hashlib.md5((str(uuid.uuid1()) + str(nowTime)).encode('utf-8')).hexdigest()
                     Device_Info.objects.filter(UID=uid).update(endpoint=res[0]['endpoint'], token_iot_number=token_iot_number )

+ 28 - 261
Object/IOTCore/IotObject.py

@@ -21,99 +21,35 @@ class IOTObject(metaclass=ABCMeta):
         pass
 
 
-class ChinaIOTClient(IOTObject):
+class IOTClient(IOTObject):
 
-    def __init__(self):
-        self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_CHINA_REGION,
-                                   aws_access_key_id=AWS_IOT_SES_ACCESS_CHINA_ID,
-                                   aws_secret_access_key=AWS_IOT_SES_ACCESS_CHINA_SECRET)
+    def __init__(self, region_id = 1):
 
-    def create_provisioning_claim(self, templateName):
-
-        result = self.client.create_provisioning_claim(templateName=templateName)
+        if region_id == 1:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_CHINA_REGION,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_CHINA_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_CHINA_SECRET)
+            self.endpoint = 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
 
-        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'
-        }
-        return res
-
-    def create_keys_and_certificate(self, uid):
-        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"
-                }
-            },
-            "Resources": {
-                "thing": {
-                    "Type": "AWS::IoT::Thing",
-                    "Properties": {
-                        "AttributePayload": {},
-                        "ThingGroups": [],
-                        "ThingName": {
-                            "Ref": "ThingName"
-                        },
-                    },
-                    "OverrideSettings": {
-                        "AttributePayload": "MERGE",
-                        "ThingTypeName": "REPLACE",
-                        "ThingGroups": "DO_NOTHING"
-                    }
-                },
-                "certificate": {
-                    "Type": "AWS::IoT::Certificate",
-                    "Properties": {
-                        "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
-                        "Status": "Active"
-                    }
-                },
-                "policy": {
-                    "Properties": {
-                        "PolicyName": "My_Iot_Policy"
-                    },
-                    "Type": "AWS::IoT::Policy"
-                },
-            }
-        }
+        if region_id == 2:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com'
 
-        templateBody = json.dumps(templateBody)
-        parameters = {"ThingName": "Ansjer_Device_" + uid,
-                      "AWS::IoT::Certificate::Id": res['certificateId']}
-        self.client.register_thing(
-            templateBody=templateBody,
-            parameters=parameters
-        )
-        return res, parameters
+        if region_id == 3:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
 
+        if region_id == 4:
+            self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA,
+                                       aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
+                                       aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
+            self.endpoint = 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
 
-class AmericaIOTClient(IOTObject):
 
-    def __init__(self):
-        self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA,
-                                   aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
-                                   aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
 
     def create_provisioning_claim(self, templateName):
 
@@ -124,104 +60,18 @@ class AmericaIOTClient(IOTObject):
             'certificatePem': result['certificatePem'],
             'publicKey': result['keyPair']['PublicKey'],
             'privateKey': result['keyPair']['PrivateKey'],
-            'endpoint': 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
-        }
-        return res
-
-    def create_keys_and_certificate(self, uid):
-        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': 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
-        }
-        # 根据证书ID注册物品和策略
-        templateBody = {
-            "Parameters": {
-                "ThingName": {
-                    "Type": "String"
-                },
-                "SerialNumber": {
-                    "Type": "String"
-                },
-                "DeviceLocation": {
-                    "Type": "String"
-                },
-                "AWS::IoT::Certificate::Id": {
-                    "Type": "String"
-                }
-            },
-            "Resources": {
-                "thing": {
-                    "Type": "AWS::IoT::Thing",
-                    "Properties": {
-                        "AttributePayload": {},
-                        "ThingGroups": [],
-                        "ThingName": {
-                            "Ref": "ThingName"
-                        },
-                    },
-                    "OverrideSettings": {
-                        "AttributePayload": "MERGE",
-                        "ThingTypeName": "REPLACE",
-                        "ThingGroups": "DO_NOTHING"
-                    }
-                },
-                "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_" + uid,
-                      "AWS::IoT::Certificate::Id": res['certificateId']}
-        self.client.register_thing(
-            templateBody=templateBody,
-            parameters=parameters
-        )
-        return res, parameters
-
-
-class AsiaIOTClient(IOTObject):
-
-    def __init__(self):
-        self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA,
-                                   aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
-                                   aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
-
-    def create_provisioning_claim(self, templateName):
-        result = self.client.create_provisioning_claim(templateName=templateName)
-
-        res = {
-            'certificateId': result['certificateId'],
-            'certificatePem': result['certificatePem'],
-            'publicKey': result['keyPair']['PublicKey'],
-            'privateKey': result['keyPair']['PrivateKey'],
-            'endpoint': 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com'
+            'endpoint': self.endpoint
         }
         return res
 
-    def create_keys_and_certificate(self, uid):
+    def create_keys_and_certificate(self, uid, 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': 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com'
+            'endpoint': 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
         }
         # 根据证书ID注册物品和策略
         templateBody = {
@@ -244,10 +94,11 @@ class AsiaIOTClient(IOTObject):
                     "Type": "AWS::IoT::Thing",
                     "Properties": {
                         "AttributePayload": {},
-                        "ThingGroups": [],
+                        # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
                         "ThingName": {
                             "Ref": "ThingName"
                         },
+                        "ThingGroups": [{"Ref" : "DeviceLocation"}]
                     },
                     "OverrideSettings": {
                         "AttributePayload": "MERGE",
@@ -273,6 +124,7 @@ class AsiaIOTClient(IOTObject):
 
         templateBody = json.dumps(templateBody)
         parameters = {"ThingName": "Ansjer_Device_" + uid,
+                      "DeviceLocation": device_version,
                       "AWS::IoT::Certificate::Id": res['certificateId']}
         self.client.register_thing(
             templateBody=templateBody,
@@ -280,88 +132,3 @@ class AsiaIOTClient(IOTObject):
         )
         return res, parameters
 
-
-class EuropeIOTClient(IOTObject):
-
-    def __init__(self):
-        self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE,
-                                   aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
-                                   aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
-
-    def create_provisioning_claim(self, templateName):
-        result = self.client.create_provisioning_claim(templateName=templateName)
-
-        res = {
-            'certificateId': result['certificateId'],
-            'certificatePem': result['certificatePem'],
-            'publicKey': result['keyPair']['PublicKey'],
-            'privateKey': result['keyPair']['PrivateKey'],
-            'endpoint': 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
-        }
-        return res
-
-    def create_keys_and_certificate(self, uid):
-        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': 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
-        }
-        # 根据证书ID注册物品和策略
-        templateBody = {
-            "Parameters": {
-                "ThingName": {
-                    "Type": "String"
-                },
-                "SerialNumber": {
-                    "Type": "String"
-                },
-                "DeviceLocation": {
-                    "Type": "String"
-                },
-                "AWS::IoT::Certificate::Id": {
-                    "Type": "String"
-                }
-            },
-            "Resources": {
-                "thing": {
-                    "Type": "AWS::IoT::Thing",
-                    "Properties": {
-                        "AttributePayload": {},
-                        "ThingGroups": [],
-                        "ThingName": {
-                            "Ref": "ThingName"
-                        },
-                    },
-                    "OverrideSettings": {
-                        "AttributePayload": "MERGE",
-                        "ThingTypeName": "REPLACE",
-                        "ThingGroups": "DO_NOTHING"
-                    }
-                },
-                "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_" + uid,
-                      "AWS::IoT::Certificate::Id": res['certificateId']}
-        self.client.register_thing(
-            templateBody=templateBody,
-            parameters=parameters
-        )
-        return res, parameters