Skip to content

Instantly share code, notes, and snippets.

@virgilvox
Created September 21, 2023 20:31
Show Gist options
  • Save virgilvox/bc367cb374fc0a56e5c1df7d1f4b3aec to your computer and use it in GitHub Desktop.
Save virgilvox/bc367cb374fc0a56e5c1df7d1f4b3aec to your computer and use it in GitHub Desktop.
import explorerhat
import subprocess
import signal
import json
import time
import sys
import os
from paho.mqtt import client as mqtt_client
speed = 50
broker = 'localhost'
clientId = 'robot'
topic = clientId + '/action'
username = 'test'
password = 'test'
port = 1883
useWebsocket = False
# Handle incoming messages and take action
def handleMessage(client, userdata, msg):
message = msg
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
if message.topic == topic:
payload = json.loads(message.payload)
if payload['action'] == 'forward':
explorerhat.motor.forwards(speed)
if payload['action'] == 'backwards':
explorerhat.motor.backwards(speed)
if payload['action'] == 'left':
explorerhat.motor.one.backwards(speed)
explorerhat.motor.two.forwards(speed)
if payload['action'] == 'right':
explorerhat.motor.one.forwards(speed)
explorerhat.motor.two.backwards(speed)
if payload['action'] == 'stop':
explorerhat.motor.stop()
time.sleep(0.2)
explorerhat.motor.stop()
# Init MQTTClient
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client(client_id)
client.username_pw_set(username, password)
client.on_connect = on_connect
client.connect(broker, port)
return client
def subscribe(client: mqtt_client):
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
client.subscribe(topic)
client.on_message = handleMessage
def run():
client = connect_mqtt()
subscribe(client)
client.loop_forever()
run()
time.sleep(2)
while True:
time.sleep(0.2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment