Software apps and online services
I've put together a couple of Python programs to use MQTT with AWS IoT.
Tested them on:
- Raspberry PI 2 with Raspbian Jessie and Python 2.7
- Debian Jessie virtual machine with Python 2.7
- Windows with Python 3.4 installed by Conda
Download my programs from github as usual (using git) and go to the expanded folder:
git clone https://github.com/mariocannistra/python-paho-mqtt-for-aws-iot.git cd python-paho-mqtt-for-aws-iot
In order to use/test my sample Python programs you have to first create your account on Amazon AWS .
Once logged on your AWS account you can download and setup the AWS CLI (the command line interface) with which you will be able to create your test "thing" and some certificates that will allow the encrypted connection with AWS IoT gateway.
Please find below the steps to create a thing, some certificates and link the certificates with the thing. I've slightly edited and annotated the basic instructions found on AWS here .
Create one thing in aws IoT:
aws iot create-thing --thing-name "myThingName"
List the things you now have:
aws iot list-things
Create certificate and keys:
aws iot create-keys-and-certificate --set-as-active --certificate-pem-outfile cert.pem --public-key-outfile publicKey.pem --private-key-outfile privkey.pem
Take note of the certificate-arn in the output or, if you forgot to copy the certificate-arn you can get it listing the certificates with:
aws iot list-certificates
Download root certificate from this URL using your browser and save it with filename: aws-iot-rootCA.crt
Create a policy from the json file you got cloning the repository with git in first step:
aws iot create-policy --policy-name "PubSubToAnyTopic" --policy-document file://iotpolicy.json
Paste your certificate-arn inside the following command before entering it:
aws iot attach-principal-policy --principal "certificate-arn" --policy-name "PubSubToAnyTopic"
- Use the data hostname and specify the region with the one you used to create the thing and certificates. Current sample code contains data.iot.eu-west-1.amazonaws.com
At this point my sample python programs ( awsiotpub.py and awsiotsub.py ) should run correctly but the AWS documentation specifies to also enter the following to attach the certificate to the thing:
aws iot attach-thing-principal --thing-name "myThingName" --principal "certificate-arn"
Install the Paho MQTT client for Python:
pip install paho-mqtt
Open two console windows and enter in the first awsiotsub.py and in the second awsiotpub.py
The second one will start sending random temperature values to the AWS IoT hub:
The first one will display them when received from the IoT hub:
You can check the sources and modify the topics used by both programs to better fit your needs. Currently, awsiotsub.py subscribes to any topic and will show all of the received msgs.
Enjoy MQTT and AWS IoT in your Python programs!
All feedbacks are welcome.