Skip to content

Instantly share code, notes, and snippets.

@jul
Created February 1, 2026 08:12
Show Gist options
  • Select an option

  • Save jul/0f53f236f9c87500b1b2a891ebde34d6 to your computer and use it in GitHub Desktop.

Select an option

Save jul/0f53f236f9c87500b1b2a891ebde34d6 to your computer and use it in GitHub Desktop.
example of piloted mqtt device
import paho.mqtt.client as mqtt
from time import time, sleep
from confined import parse, Value, pop
stack = []
client_id = "sub"
show_must_go = False
def on_connect(client, userdata, flags, reason_code, properties):
print(f"Connected with result code {reason_code}")
client.subscribe(f"BUS/{client_id}")
client.subscribe(f"BUS")
def on_lun(*a, **kw):
kw["ctx"]["state"]="RAZ"
def on_ping(*a, **kw):
global client_id
client = kw["ctx"]["client"]
client.publish("RES", f"'{client_id}':PONG")
def on_sel(stack, **kw):
global client_id, show_must_go
print(stack)
if stack.pop().str == client_id:
show_must_go = True
def on_unsel(stack, **kw):
global client_id, show_must_go
if stack.pop().str == client_id:
show_must_go = False
ctx = dict(
cap=["www", "forth" ],
dispatch=dict(
lun=on_lun,
ping=on_ping,
sel=on_sel,
unsel=on_unsel
),
)
def on_message(client, userdata, msg):
global stack, ctx
ctx["client"] = client
client.publish(
"RES",
str(parse(
ctx,
msg.payload.decode(),
data=stack,
)
)
)
mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id=client_id)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.username = "sub"
mqttc.password= "sub"
mqttc.tls_set(
keyfile="./cfg/sub.key",
certfile="./cfg/sub.crt",
ca_certs="./cfg/RootCA.crt",
tls_version=2
)
mqttc.connect("badass.home", 8883, 60)
mqttc.loop_start()
# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
while True:
if show_must_go:
mqttc.publish("RES", "hello")
sleep(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment