IotObject.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  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 or region_id == 5:
  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.iot_role = AWS_IOT_SES_ACCESS_CHINA_ROLE
  19. elif region_id == 2 or region_id == 3:
  20. # 美东弗吉尼亚
  21. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_AMERICA,
  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.us-east-1.amazonaws.com'
  25. self.iot_role = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
  26. elif region_id == 4:
  27. # 西欧爱尔兰
  28. self.client = boto3.client('iot', region_name=AWS_IOT_SES_ACCESS_FOREIGN_REGION_EUROPE,
  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.eu-west-1.amazonaws.com'
  32. self.iot_role = AWS_IOT_SES_ACCESS_FOREIGN_ROLE
  33. def create_provisioning_claim(self, templateName):
  34. result = self.client.create_provisioning_claim(templateName=templateName)
  35. res = {
  36. 'certificateId': result['certificateId'],
  37. 'certificatePem': result['certificatePem'],
  38. 'publicKey': result['keyPair']['PublicKey'],
  39. 'privateKey': result['keyPair']['PrivateKey'],
  40. 'endpoint': self.endpoint
  41. }
  42. return res
  43. def register_to_iot_core(self, ThingName, thingGroup, response):
  44. try:
  45. result = self.client.create_keys_and_certificate(setAsActive=True)
  46. res = {
  47. 'certificateId': result['certificateId'],
  48. 'certificatePem': result['certificatePem'],
  49. 'publicKey': result['keyPair']['PublicKey'],
  50. 'privateKey': result['keyPair']['PrivateKey'],
  51. 'endpoint': self.endpoint
  52. }
  53. # 搜索是否存在该物品组
  54. thing_groups_res = self.client.list_thing_groups(nextToken='', maxResults=1,
  55. namePrefixFilter=thingGroup, recursive=False)
  56. if thing_groups_res['thingGroups']:
  57. thingGroupName = thing_groups_res['thingGroups'][0]['groupName'] # 获取物品组名称
  58. else:
  59. attributes = {
  60. "update_time": "0"
  61. }
  62. thingGroupProperties = {
  63. "thingGroupDescription": "OTA",
  64. "attributePayload": {
  65. "attributes": attributes,
  66. "merge": False # 更新时覆盖掉而不是合并
  67. }
  68. }
  69. create_thing_group_res = self.client.create_thing_group(thingGroupName=thingGroup,
  70. thingGroupProperties=thingGroupProperties)
  71. thingGroupName = create_thing_group_res['thingGroupName'] # 获取物品组名称
  72. print('物品组:', thingGroupName)
  73. # 根据证书ID注册物品和策略
  74. templateBody = {
  75. "Parameters": {
  76. "ThingName": {
  77. "Type": "String"
  78. },
  79. "SerialNumber": {
  80. "Type": "String"
  81. },
  82. "thingGroupName": {
  83. "Type": "String"
  84. },
  85. "AWS::IoT::Certificate::Id": {
  86. "Type": "String"
  87. }
  88. },
  89. "Resources": {
  90. "thing": {
  91. "Type": "AWS::IoT::Thing",
  92. "Properties": {
  93. "AttributePayload": {},
  94. # "ThingGroups" : ["v1-lightbulbs", {"Ref" : "DeviceLocation"}],
  95. "ThingName": {
  96. "Ref": "ThingName"
  97. },
  98. "ThingGroups": [{"Ref": "thingGroupName"}]
  99. },
  100. "OverrideSettings": {
  101. "AttributePayload": "MERGE",
  102. "ThingTypeName": "REPLACE",
  103. "ThingGroups": "DO_NOTHING"
  104. }
  105. },
  106. "certificate": {
  107. "Type": "AWS::IoT::Certificate",
  108. "Properties": {
  109. "CertificateId": {"Ref": "AWS::IoT::Certificate::Id"},
  110. "Status": "Active"
  111. }
  112. },
  113. "policy": {
  114. "Properties": {
  115. "PolicyName": "My_Iot_Policy"
  116. },
  117. "Type": "AWS::IoT::Policy"
  118. },
  119. }
  120. }
  121. templateBody = json.dumps(templateBody)
  122. parameters = {"ThingName": ThingName,
  123. "thingGroupName": thingGroupName,
  124. "AWS::IoT::Certificate::Id": res['certificateId']}
  125. self.client.register_thing(
  126. templateBody=templateBody,
  127. parameters=parameters
  128. )
  129. return res, parameters
  130. except Exception as e:
  131. print(e)
  132. return response.json(500, repr(e))