6

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
s.write("\r\n\r\n")
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
f.close()
s.close()  
Aurora0001
  • 18,520
  • 13
  • 55
  • 169
Balsam Qassem
  • 693
  • 4
  • 11

1 Answers1

4

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.

Aurora0001
  • 18,520
  • 13
  • 55
  • 169