IotObject.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. import json
  4. from abc import ABCMeta,abstractmethod
  5. import boto3
  6. from Ansjer.config import AWS_IOT_SES_ACCESS_CHINA_REGION, AWS_IOT_SES_ACCESS_CHINA_ID, AWS_IOT_SES_ACCESS_CHINA_SECRET, \
  7. AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA, AWS_IOT_SES_ACCESS_FOREIGN_ID, AWS_IOT_SES_ACCESS_FOREIGN_SECRET, \
  8. AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE, AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA
  9. class IOTObject(metaclass=ABCMeta):
  10. @abstractmethod
  11. def create_provisioning_claim(self, templateName):
  12. pass
  13. @abstractmethod
  14. def create_keys_and_certificate(self, uid):
  15. pass
  16. class IOTClient(IOTObject):
  17. def __init__(self, region_id = 1):
  18. if region_id == 1:
  19. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_CHINA_REGION,
  20. aws_access_key_id=AWS_IOT_SES_ACCESS_CHINA_ID,
  21. aws_secret_access_key=AWS_IOT_SES_ACCESS_CHINA_SECRET)
  22. self.endpoint = 'a250bbr0p9u7as-ats.iot.cn-northwest-1.amazonaws.com.cn'
  23. if region_id == 2:
  24. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_ASIA,
  25. aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
  26. aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
  27. self.endpoint = 'a2rqy12o004ad8-ats.iot.ap-southeast-1.amazonaws.com'
  28. if region_id == 3:
  29. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA,
  30. aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
  31. aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
  32. self.endpoint = 'a2rqy12o004ad8-ats.iot.us-east-1.amazonaws.com'
  33. if region_id == 4:
  34. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE,
  35. aws_access_key_id=AWS_IOT_SES_ACCESS_FOREIGN_ID,
  36. aws_secret_access_key=AWS_IOT_SES_ACCESS_FOREIGN_SECRET)
  37. self.endpoint = 'a2rqy12o004ad8-ats.iot.eu-west-1.amazonaws.com'
  38. def create_provisioning_claim(self, templateName):
  39. result = self.client.create_provisioning_claim(templateName=templateName)
  40. res = {
  41. 'certificateId': result['certificateId'],
  42. 'certificatePem': result['certificatePem'],
  43. 'publicKey': result['keyPair']['PublicKey'],
  44. 'privateKey': result['keyPair']['PrivateKey'],
  45. 'endpoint': self.endpoint
  46. }
  47. return res
  48. def create_keys_and_certificate(self, serial_number, thingGroup):
  49. try:
  50. result = self.client.create_keys_and_certificate(setAsActive=True)
  51. res = {
  52. 'certificateId': result['certificateId'],
  53. 'certificatePem': result['certificatePem'],
  54. 'publicKey': result['keyPair']['PublicKey'],
  55. 'privateKey': result['keyPair']['PrivateKey'],
  56. 'endpoint': self.endpoint
  57. }
  58. # 搜索是否存在该物品组
  59. thing_groups_res = self.client.list_thing_groups(nextToken='', maxResults=1,
  60. namePrefixFilter=thingGroup, recursive=False)
  61. if thing_groups_res['thingGroups']:
  62. thingGroupName = thing_groups_res['thingGroups'][0]['groupName'] # 获取物品组名称
  63. else:
  64. attributes = {
  65. "update_time": "0"
  66. }
  67. thingGroupProperties = {
  68. "thingGroupDescription": "OTA",
  69. "attributePayload": {
  70. "attributes": attributes,
  71. "merge": False # 更新时覆盖掉而不是合并
  72. }
  73. }
  74. create_thing_group_res = self.client.create_thing_group(thingGroupName=thingGroup,
  75. thingGroupProperties=thingGroupProperties)
  76. thingGroupName = create_thing_group_res['thingGroupName'] # 获取物品组名称
  77. print('物品组:', thingGroupName)
  78. # 根据证书ID注册物品和策略
  79. templateBody = {
  80. "Parameters": {
  81. "ThingName": {
  82. "Type": "String"
  83. },
  84. "SerialNumber": {
  85. "Type": "String"
  86. },
  87. "thingGroupName": {
  88. "Type": "String"
  89. },
  90. "AWS::IoT::Certificate::Id": {
  91. "Type": "String"
  92. }
  93. },
  94. "Resources": {
  95. "thing": {
  96. "Type": "AWS::IoT::Thing",
  97. "Properties": {
  98. "AttributePayload": {},
  99. # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
  100. "ThingName": {
  101. "Ref": "ThingName"
  102. },
  103. "ThingGroups": [{"Ref": "thingGroupName"}]
  104. },
  105. "OverrideSettings": {
  106. "AttributePayload": "MERGE",
  107. "ThingTypeName": "REPLACE",
  108. "ThingGroups": "DO_NOTHING"
  109. }
  110. },
  111. "certificate": {
  112. "Type": "AWS::IoT::Certificate",
  113. "Properties": {
  114. "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
  115. "Status": "Active"
  116. }
  117. },
  118. "policy": {
  119. "Properties": {
  120. "PolicyName": "My_Iot_Policy"
  121. },
  122. "Type": "AWS::IoT::Policy"
  123. },
  124. }
  125. }
  126. templateBody = json.dumps(templateBody)
  127. parameters = {"ThingName": "Ansjer_Device_" + serial_number,
  128. "thingGroupName": thingGroupName,
  129. "AWS::IoT::Certificate::Id": res['certificateId']}
  130. self.client.register_thing(
  131. templateBody=templateBody,
  132. parameters=parameters
  133. )
  134. return res, parameters
  135. except Exception as e:
  136. print(e)
  137. # return response.json(500, repr(e))