IotObject.py 7.7 KB

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