I want to connect my CNC machine with AWS IoT within a system that contains a robotic arm and sensor. The CNC machine is connected to a laptop and runs with Python code. I want to use MQTT to make the CNC machine a publisher and subscriber but I don't know how to do that. Here is the CNC Python code.

import serial
import time

# Open grbl serial port
s = serial.Serial('COM3',9600)

# Open g-code file
f = open('grbl.gcode.txt','r');

# Wake up grbl
time.sleep(2)   # Wait for grbl to initialize 
s.flushInput()  # Flush startup text in serial input

# Stream g-code to grbl
for line in f:
    l = line.strip() # Strip all EOL characters for consistency
    print 'Sending: ' + l,
    s.write(l + '\n') # Send g-code block to grbl
    grbl_out = s.readline() # Wait for grbl response with carriage return
    print ' : ' + grbl_out.strip()

# Wait here until grbl is finished to close serial port and file.
raw_input("  Press <Enter> to exit and disable grbl.") 

# Close file and serial port

1 Answer 1


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.

# 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)

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)

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.

  • 1
    i want to make cnc subscriber and publisher in the same time , subscriber to know when the object comes ,and publisher to publish to robotic arm to remove the object after it finished . Commented Aug 28, 2017 at 20:25
  • @BalsamQassem Indeed, and this example does both show subscribing and publishing. I obviously can't write the whole thing for you, but you should be able to adapt the example to the rest of your code and hardware. If you're struggling with that, you can leave a comment and I'll try to help, but I don't know what hardware you're using so can't provide guidance there.
    – Aurora0001
    Commented Aug 28, 2017 at 20:28
  • actually yes i am new with all these stuff but i will try to learn how do it ,if I fail then I will ask you, thank u for help Commented Aug 28, 2017 at 20:54
  • I need your help, i can't do it by my self , can you please help me and show me how to use your code with my cnc code that posted above@Aurora0001 Commented Sep 10, 2017 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.