server/mock-clients/mock-actor.py

36 lines
1.1 KiB
Python
Raw Normal View History

2021-08-18 16:48:17 +00:00
import paho.mqtt.client as mqtt
import logging, coloredlogs
coloredlogs.install(level='INFO', fmt='%(asctime)s - [%(levelname)s] %(message)s')
ACTOR_ID = "101"
ACTOR_PASSWORD = "MgUiSW1dloFt9TVKJM5E"
2021-08-18 16:48:17 +00:00
def on_connect(client, userdata, flags, rc):
global ACTOR_ID
if rc != 0:
logging.error(f"Error connecting to MQTT broker: {rc}")
return
logging.info("Successfully connected to MQTT broker")
client.subscribe(f"mlmAccess/actor/{ACTOR_ID}/action")
client.publish(f"mlmAccess/actor/{ACTOR_ID}/status", "0", retain=True)
2021-08-18 16:48:17 +00:00
def on_message(client, userdata, message):
messageContent = str(message.payload.decode("utf-8"))
logging.info(f"Got request to perform action: {messageContent}")
# report back action to let the backend know that it was executed successfully
client.publish(f"mlmAccess/actor/{ACTOR_ID}/status", messageContent, retain=True)
2021-08-18 16:48:17 +00:00
client = mqtt.Client(client_id=f"actor-{ACTOR_ID}")
client.username_pw_set(f"actor-{ACTOR_ID}", ACTOR_PASSWORD)
2021-08-18 16:48:17 +00:00
client.on_connect = on_connect
client.on_message = on_message
logging.info("Initializing MQTT")
client.connect("localhost", 1883, 60)
2021-08-18 16:48:17 +00:00
client.loop_forever()