By far the easiest method would be to use a library such as paho-mqtt or the AWS IoT SDK for Python (see the bottom of this post), which are MQTT client libraries for Python.
Usage guidance is provided in the linked documentation. Here is an example, for reference, which you may find useful to adapt to your purposes (it's loosely based on the documentation provided):
import paho.mqtt.client as mqtt
import time
# Runs when the client receives a CONNACK connection acknowledgement.
def on_connect(client, userdata, flags, result_code):
print "Successful connection."
# Subscribe to your topics here.
client.subscribe("sensor/topic_you_want_to_subscribe_to")
# Runs when a message is PUBLISHed from the broker. Any messages you receive
# will run this callback.
def on_message(client, userdata, message):
if message.topic == "sensor/topic_you_want_to_subscribe_to":
if message.payload == "START":
# We've received a message "START" from the sensor.
# You could do something here if you wanted to.
elif message.payload == "STOP":
# Received "STOP". Do the corresponding thing here.
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("yourbrokerurl.com", 1883, 60)
client.loop_start()
while True:
# Your script must loop here, and CAN block the thread.
# For example, you could take a measurement, then sleep 5 seconds
# and publish it.
data_to_broadcast = get_data()
client.publish("cnc/data", data_to_broadcast)
time.sleep(5)
This example looks a little overwhelming... But it's quite easy when you take it in bits. Start by looking at the line client = mqtt.Client()
. Here we create an MQTT client. We then register callbacks for connecting and receiving a message (these are just functions that run when an event occurs).
In our connect callback, we subscribe to the sensor topic. Then, in the message received function, we check if the message is telling our CNC to do something, then do it (the implementation of that is left to the reader).
Then, in the while True:
loop, we publish data every 5 seconds. That's just an example—you can do whatever you want there. Just remember client.publish
is the function you need to publish something.
Alternatively, if you're looking for a library specifically for AWS IoT, you can use aws-iot-device-sdk-python. This builds on Paho, but makes the extra requirements and features (such as the Device Shadow) more easily accessible from the library.
Remember also that AWS IoT requires a device certificate for each device—their SDK will help you handle this, but Paho alone won't.
Here is a basic pub/sub sample for Amazon's SDK. You'll notice it's broadly similar to the example above, and might be quicker to start from.