[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK

Purpose

Register things in AWS IoT using the AWS IoT Python SDK. When there are a lot of things, it is difficult to register each time on the console.

Supplement

At the same time as registering the item, do the following.

--Various information registration -Register information in "Attribute" --Register information in device shadow --Add things to "group of things" --Certificate issuance and attachment --Issue and save device certificate / key --Attach policy to certificate --Attach things to certificates

Run

Advance preparation

--Create a group to which things belong. (Procedure omitted) group.png

--Create a policy to attach to the certificate. (Procedure omitted) policy.png

code

import boto3
import json
import os

class AWSIoT():
    
    #Certificate, key file name
    FILENAME_PUBLIC_KEY = 'public_key.pem'
    FILENAME_PRIVATE_KEY = 'private_key.pem'
    FILENAME_CERT = 'cert.pem'
    
    def __init__(self, dirpath_cert):
        
        #Instantiate the class to use
        self.client_iot = boto3.client('iot')
        self.client_iotdata = boto3.client('iot-data')
        
        #Directory for storing certificates
        self.DIRPATH_CERT = dirpath_cert
        
        return

    
    def enroll_thing(self, thing_name, dict_attr, group_name, property_desired, property_reported, policy):
        '''
Register things with AWS IoT
        '''
        #Register things in AWS IoT ("attribute"Register information about things in
        self.__create_thing(thing_name, dict_attr)
        
        #Add registered items to group
        self.client_iot.add_thing_to_thing_group(thingGroupName=group_name, thingName=thing_name)
        
        #Register information in device shadow
        self.__update_shadow(thing_name, property_desired, property_reported)
        
        #Issue and save device certificate / key
        response = self.__create_keys_and_cert(thing_name)
        
        #Attach policy to certificate
        self.client_iot.attach_policy(policyName=policy, target=response['certificateArn'])

        #Link the certificate to the device
        self.client_iot.attach_thing_principal(thingName=thing_name, principal=response['certificateArn'])
        
        return
    
    
    def __create_thing(self, thingname, dict_attr):
        '''
Register things in AWS IoT ("attribute"Register information about things in
        '''
        #Generate registration information (attribute)
        attributePayload = self.__create_attribute_payload(dict_attr)
        
        #Register things
        self.client_iot.create_thing(
            thingName=thingname,
            attributePayload=attributePayload
        )

        return   


    def __create_attribute_payload(self, dict_attr):
        '''
Generate registration information (attribute)
        '''
        attributePayload = {
                'attributes': dict_attr
        }
        return attributePayload
    
    
    def __update_shadow(self, thing_name, property_desired, property_reported):
        '''
Register information in device shadow
        '''
        #Formatting version information to write to device shadow
        payload = self.__create_payload(property_desired, property_reported)

        #Register information in device shadow
        self.client_iotdata.update_thing_shadow(
            thingName=thing_name,
            payload=payload
        )

        return


    def __create_payload(self, property_desired, property_reported):
        '''
Formatting version information to write to device shadow
        '''
        payload = json.dumps({'state': 
            {"desired": {"property": property_desired},
            "reported": {"property": property_reported}}})

        return payload
    
    
    def __create_keys_and_cert(self, thing_name):
        '''
Issue and save device certificate / key
        '''
        #Issue certificate and key
        response = self.client_iot.create_keys_and_certificate(setAsActive=True)
        
        #Generate destination directory path
        dirpath_save = self.DIRPATH_CERT + thing_name + '/'
        
        #Write to file and save
        self.__write_to_file(dirpath_save, self.FILENAME_PUBLIC_KEY, response['keyPair']['PublicKey'])
        self.__write_to_file(dirpath_save, self.FILENAME_PRIVATE_KEY, response['keyPair']['PrivateKey'])
        self.__write_to_file(dirpath_save, self.FILENAME_CERT, response['certificatePem'])

        return response
    
    
    def __write_to_file(self, dirpath, filename, contents):
        '''
Write to file
        '''
        os.makedirs(dirpath, exist_ok=True)

        filepath = dirpath + filename
        with open(filepath, mode='w') as f:
            f.write(contents)
            
        return

Run

--Define registration information --This time, register the thing named "ThingName". --Register'hogehoge_building' as'BuildingName' and '6' as'Floor' in the attribute. --Register the ideal temperature and the current temperature in the device shadow.

#The name of the thing
thing_name = 'ThingName' 

#Attribute of thing (attribute key:value)
dict_attr = {'BuildingName':'hogehoge_building', 'Floor':'6'}

#The name of the group to which the thing belongs
group_name = 'hogehoge_group'

#Information to be registered in device shadow
temp_desired = 26
temp_reported = 22

#Policy to attach to certificate
policy = 'policy_thermometer'

#Directory path to store certificates and keys
dirpath_cert = './cert/'

--Instantiate and execute the class

awsiot = AWSIoT(dirpath_cert)
awsiot.enroll_thing(thing_name, dict_attr, group_name, temp_desired, temp_reported, policy)

result

The device has been registered. The attributes are also registered correctly. モノの名前.png

The shadow is also registered correctly. ("Delta" is created automatically. Details are omitted.) シャドウ.png

The certificate is also linked correctly, 証明書.png

A policy is attached to the certificate. ポリシー2.png

Afterword

I'm a very beginner, so I would appreciate it if you could point out and comment on even the smallest things. I'm on Twitter → @shin_job

Recommended Posts

[AWS IoT] Register things in AWS IoT using the AWS IoT Python SDK
Load the remote Python SDK in IntelliJ
Try using the Wunderlist API in Python
Tweet using the Twitter API in Python
Working with OpenStack using the Python SDK
Try using the BitFlyer Ligntning API in Python
Pre-process the index in Python using Solr's ScriptUpdateProcessor
Getting started with AWS IoT easily in Python
Call Polly from the AWS SDK for Python
Try using the DropBox Core API in Python
Receive the form in Python and do various things
Fleet provisioning with AWS IoT SDK for Python v2
Collectively register data in Firestore using csv file in Python
Initial settings when using the foursquare API in python
Determine the threshold using the P tile method in python
Using the National Diet Library Search API in Python
AWS SDK for Python (Boto3) development in Visual Studio 2017
Using the LibreOffice app in Python (1) Where are the macros?
[Python] Scraping in AWS Lambda
Download the file in Python
Find the difference in Python
Translate using googletrans in Python
Using Python mode in Processing
Run AWS IoT Device SDK for Python on Raspberry Pi
Try a similar search for Image Search using the Python SDK [Search]
Solve the Japanese problem when using the CSV module in Python.
Things to keep in mind when using Python with AtCoder
Things to keep in mind when using cgi with python.
Things to watch out for when using default arguments in Python
GUI programming in Python using Appjar
Getting the arXiv API in Python
Precautions when using pit in Python
Python in the browser: Brython's recommendation
Save the binary file in Python
Hit the Sesami API in Python
Try the Python LINE Pay SDK
Python beginners tried Hello World in 30 seconds using the micro-framework Flask
Get the desktop path in Python
Write AWS Lambda function in Python
Try using LevelDB in Python (plyvel)
Get the script path in Python
In the python command python points to python3.8
Implement the Singleton pattern in Python
The Python library `awsiot` to pub/sub to AWS IoT used the default port = 443.
Try PLC register access in Python
Using global variables in python functions
boto3 (AWS SDK for Python) Note
Hit the web API in Python
Let's see using input in python
I compared Node.js and Python in creating thumbnails using AWS Lambda
Infinite product in Python (using functools)
Extract the targz file using python
Edit videos in Python using MoviePy
I wrote the queue in Python
Calculate the previous month in Python
Examine the object's class in python
Get the desktop path in Python
Try using the Python Cmd module
Get the host name in Python
Regularly upload files to Google Drive using the Google Drive API in Python
Handwriting recognition using KNN in Python