Giter Club home page Giter Club logo

python-paho-mqtt-for-aws-iot's Introduction

Python, paho, mqtt and AWS IoT

Platforms supported

I've tested the certificate creation commands only on Windows using the AWS CLI. I think they should work on the AWS CLI of other platforms.

My python programs run perfectly 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

Create a thing, certifcate, keys and attaching them to enable usage of AWS IoT hub

Based on AWS docs found here: http://docs.aws.amazon.com/iot/latest/developerguide/secure-communication.html

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 file provided:

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"

Two options about the configuration of your endpoint:

  • change the value of awshost using the returned value of "endpointAddress":
aws iot describe-endpoint
  • use 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 (I will try to understand which are the benefits, if any, of one over the other).

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"

How to test the sample Python programs

  • 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!

python-paho-mqtt-for-aws-iot's People

Contributors

amri91 avatar mariocannistra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-paho-mqtt-for-aws-iot's Issues

Problem with subscription

Hi Mario,
Thank you very much to share this code, I'm trying to use it with a little modification but I have a problem, this is my code:

publish:

#!/usr/bin/python3

#required libraries
import sys                                 
import ssl
import paho.mqtt.client as mutt
from time import sleep
from random import uniform

connflag = False

def on_connect(client, userdata, flags, rc):
    global connflag
    connflag = True
    print("Connection returned result: " + str(rc) )

def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))
    print("Received message from topic: "+msg.topic+" | QoS: "+str(msg.qos)+" | Data Received: "+str(msg.payload))

mqttc = mqtt.Client(client_id="RaspberryPi_2", clean_session=True)

mqttc.on_connect = on_connect
mqttc.on_message = on_message


mqttc.tls_set("/home/pi/aws_iot/things/raspberryPi_2/certs/aws-iot-rootCA.crt",
                certfile="/home/pi/aws_iot/things/raspberryPi_2/certs/0ea2cd7eb6-certificate.pem.crt",
                keyfile="/home/pi/aws_iot/things/raspberryPi_2/certs/0ea2cd7eb6-private.pem.key",
              tls_version=ssl.PROTOCOL_TLSv1_2,
              ciphers=None)

mqttc.connect("A2GF7W5U5A46J1.iot.us-west-2.amazonaws.com", port=8883)

mqttc.loop_start()

while 1==1:
    sleep(0.5)
    if connflag == True:
        tempreading = uniform(20.0,25.0)
        #jsonMessage = "{ \"state\": { \"reported\": { \"temperature\": " + str(tempreading) + "} } }"
        #mqttc.publish("$aws/things/RaspberryPi_2/shadow/update", jsonMessage, qos=1)
        mqttc.publish("topic/test",tempreading,qos=1)
        print("msg sent: temperature " + "%.2f" % temp reading )
    else:
        print("waiting for connection...")

subscription:

#!/usr/bin/python3

#required libraries
import sys                                 
import ssl
import paho.mqtt.client as mqtt
import RPi.GPIO as gpio
from time import sleep

try:
    ledPin = 25
    gpio.setmode(gpio.BCM)
    gpio.setup(ledPin, gpio.OUT)

    def on_connect(client, userdata, flags, rc):
        print("Connected with result code "+str(rc))
        client.subscribe("topic/test",1)

    def on_message(client, userdata, msg):
        print("Message received: "+str(msg.payload))

        if str(msg.payload) >= '23':
            print("High Temperature")
            print(str(msg.payload))
            GPIO.output(ledPin, GPIO.HIGH)
            time.sleep(.1)
            GPIO.output(ledPin, GPIO.LOW)


    def on_subscribe(mqttc, obj, mid, granted_qos):
        print("Subscribed: "+str(mid)+" "+str(granted_qos)+"data"+str(obj))


    mqttc = mqtt.Client(client_id="RaspberryPi_2", clean_session=True)

    mqttc.on_connect = on_connect
    mqttc.on_message = on_message
    mqttc.on_subscribe = on_subscribe


    mqttc.tls_set("/home/pi/aws_iot/things/raspberryPi_2/certs/aws-iot-rootCA.crt",
                    certfile="/home/pi/aws_iot/things/raspberryPi_2/certs/0ea2cd7eb6-certificate.pem.crt",
                    keyfile="/home/pi/aws_iot/things/raspberryPi_2/certs/0ea2cd7eb6-private.pem.key",
                  tls_version=ssl.PROTOCOL_TLSv1_2,
                  ciphers=None)

    mqttc.connect("A2GF7W5U5A46J1.iot.us-west-2.amazonaws.com", port=8883) #AWS IoT service hostname and portno

    mqttc.loop_forever()

except KeyboardInterrupt:
    pass
finally:
    gpio.cleanup()

This is the log of the publisher:

waiting for connection...
Connection returned result: 0
msg sent: temperature 20.68
msg sent: temperature 21.28
msg sent: temperature 23.76
...
msg sent: temperature 24.66
msg sent: temperature 22.92
msg sent: temperature 21.52
msg sent: temperature 20.25
Connection returned result: 0
msg sent: temperature 20.25
msg sent: temperature 20.50
msg sent: temperature 23.31
msg sent: temperature 20.85
...
msg sent: temperature 21.89
msg sent: temperature 21.97

This is the log of the subscriber:

Connected with result code 0
Subscribed: 1 (1,)dataNone
Connected with result code 0
Subscribed: 2 (1,)dataNone
Connected with result code 0
Subscribed: 3 (1,)dataNone
Connected with result code 0
Subscribed: 4 (1,)dataNone
Connected with result code 0
Subscribed: 5 (1,)dataNone

So as you can see there is no print of the on_message function, following your solution on the only issue in this project and i have tried this:

jsonMessage = "{ \"state\": { \"reported\": { \"temperature\": " + str(tempreading) + "} } }"
mqttc.publish("$aws/things/RaspberryPi_2/shadow/update", jsonMessage, qos=1)

and the Thing Shadow on AWS IoT is update, so I think that the connection with AWS is established, can you help me?

I noticed another thing if it can be useful to help me, if I run only the subscriber without the publisher this is the log:

Connected with result code 0
Subscribed: 1 (1,)dataNone

only one subscription, so it seems that something happens when I start to publish, but it does not work, I hope you can help me thanks

Clarification on thingName and ClientID

Dear Author,

You are using thingName which is the name of a Thing and ClientID
How are these two variables:

clientId = "myThingName"
thingName = "myThingName"

used in awsiotsub.py and awsiotpub.py

Please clarify,

With Thanks and Regards
Srini

Risk: over-authorization of AWS IoT policy

We are a security research team and we recently discovered that there is an over-authorization security issue with this project's IoT policy.
The affected file is as following:

1. python-paho-mqtt-for-aws-iot/iotpolicy.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.