IotObject.py 6.4 KB

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