As with most micro python ESP32 stuff – adding MQTT control was about as easy as it can get.
I installed the mosquitto MQTT broker on a raspberry pi which was connected to my local wifi network. The robot was also connected to this same network. Then this python script was used to send MQTT messages when any of the arrow keys on the raspi keyboard were pressed:
import paho.mqtt.client as paho
from sshkeyboard import listen_keyboard
broker="localhost"
port=1883
def on_publish(client,userdata,result): #create function for callback
print("data published \n")
pass
client1= paho.Client("control1") #create client object
client1.on_publish = on_publish #assign function to callback
client1.connect(broker,port)
def press(key):
if key == "up":
print("up pressed")
ret= client1.publish("testTopic","u")
elif key == "down":
print("down pressed")
ret= client1.publish("testTopic","d")
elif key == "left":
print("left pressed")
ret= client1.publish("testTopic","l")
elif key == "right":
print("right pressed")
ret= client1.publish("testTopic","r")
elif key == "space":
print("right pressed")
ret= client1.publish("testTopic","s")
listen_keyboard(on_press=press)
And then on the robot this script changed motor directions based on MQTT messages received:
import machine
import time
from umqtt.robust import MQTTClient
def do_connect():
import network
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('connecting to network...')
sta_if.active(True)
sta_if.connect('VM5035215', 'v67tjrzjRdje')
while not sta_if.isconnected():
pass
print('network config:', sta_if.ifconfig())
def sub_cb(topic, msg):
print((topic, msg))
if msg==b"l":
left()
if msg==b"r":
right()
if msg==b"u":
straight()
if msg==b"d":
reverse()
if msg==b"s":
motors_off()
def mqtt_receive():
c = MQTTClient("", 'raspberrypi.local', user='', password='')
c.connect()
c.DEBUG = True
c.set_callback(sub_cb)
print("New session being set up")
c.subscribe(b"testTopic")
while 1:
c.wait_msg()
c.disconnect()
led.off()
motors_off()
while(but.value()==1): ##wait until button is pressed to start
pass
led.on()
do_connect()
mqtt_receive()
The umqtt library used was taken from the micropython-lib github repo. I’ve found that the “robust” library is really good at handling poor wifi/wifi dropouts so anytime I’m doing MQTT stuff with an ESP I use it.
MQTT wouldn’t be my first choice for message transport if the idea was to just have one remote control and one robot. The idea would be to have many robots, only one of which is controlled by a human. The way MQTT is structured with the whole topics and subscribing functionality should lend itself to that type of use.