IotObject.py 7.7 KB

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