MQTT
Server
-
Username+password required, anonymous connections not allowed.
-
mqtt:// - not available
-
mqtts:// - server
mqtt.renert.housegordon.com tcp port 8883
-
ws:// - not available (websockets over HTTP, not encrypted)
-
wss:// - server
mqtt.renert.housegordon.com tcp port 433 path /mqtt.
i.e: wss://USERNAME:PW@mqtt.renert.housegordon.com:443/mqtt
Command Line
Install mosquitto-clients debian package:
apt-get install mosquitto-clients
Publish:
mosquitto_pub -L mqtts://USERNAME:PW@mqtt.renert.housegordon.com/mytopic -m MyMessage
Subscribe:
mosquitto_sub -L mqtts://USERNAME:PW@mqtt.renert.housegordon.com/mytopic
Python 3
Install paho-mqtt python package.
NOTE: paho-mqtt version 2.0.0 and later had a breaking change, many examples online are using the
pre-2.0.0 and will need adjustment (darn python developers...)
Publish
from paho.mqtt import client as mqtt_client
import sys
client_id = 'My-Python-Client-ID'
broker = 'mqtt.renert.housegordon.com'
port = 8883
username = 'USERNAME'
pw = 'PW'
client = mqtt_client.Client(client_id=client_id,
callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2)
client.tls_set()
client.username_pw_set(username,pw)
res = client.connect(broker,port)
if res != 0:
sys.exit("Failed to connect to MQTT server")
res = client.publish("mytopic","my-python-message")
if res[0] != 0:
sys.exit("Failed to publish message")
Subscribe
from paho.mqtt import client as mqtt_client
import sys
client_id = 'My-Python-Client-ID'
broker = 'mqtt.renert.housegordon.com'
port = 8883
username = 'USERNAME'
pw = 'PW'
topic = "mytopic"
def on_connect(client, userdata, flags, rc, properties):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
def on_message(client, userdata, msg):
print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
## Connect
client = mqtt_client.Client(client_id=client_id,
callback_api_version=mqtt_client.CallbackAPIVersion.VERSION2)
client.tls_set()
client.username_pw_set(username, pw)
client.on_connect = on_connect
client.connect(broker, port)
## Subscribe
client.subscribe(topic)
client.on_message = on_message
## Receive loop
print("Connected to MQTT broker - waiting for messages with topic: ", topic)
client.loop_forever()
MicroPython (e.g. ESP32)
Tested with MicroPython v1.24.1 built 2024-11-20 (Python 3.4.0)
Running on ESP32s2 with 4MB PSRAM.
Uses the umqtt.simple module (docs).
TODO: look at umqtt.simple2.
Publish
import network
import ssl
import time
import umqtt.simple as MQTTClient
## Wifi Setup
wifi_ssid = "SSID"
wifi_pw = "WIFI-PW"
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(wifi_ssid, wifi_pw)
while True:
time.sleep(0.5)
if sta_if.isconnected():
break
print("Wifi not connected yet, sleeping and re-trying...")
## MQTT
client_id = "My-MicroPython-Client"
broker = "mqtt.renert.housegordon.com"
port = 8883
username = "USERNAME"
pw = "PW"
topic = "mytopic"
message = "fooBAZ"
# Ugly Hack Alert: the 'ssl' parameter points to the SSL Module directly.
# It seems to just work. No clue if the SSL certificate is actually verified.
client = MQTTClient(client_id, broker, port, username, pw, ssl=ssl)
res = client.connect()
if res == 0:
client.publish(topic, message)
else:
print("ERROR Connecting to MQTT: ", res)
Subscribe
import network
import ssl
import time
import umqtt.simple as MQTTClient
## Wifi Setup
wifi_ssid = "SSID"
wifi_pw = "WIFI-PW"
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect(wifi_ssid, wifi_pw)
while True:
time.sleep(0.5)
if sta_if.isconnected():
break
print("Wifi not connected yet, sleeping and re-trying...")
## MQTT
client_id = "My-MicroPython-Client"
broker = "mqtt.renert.housegordon.com"
port = 8883
username = "USERNAME"
pw = "PW"
topic = "mytopic"
message = "fooBAZ"
def on_message(topic,message):
#NOTE:
# topic and message will be BYTEs, not STRs
print("Got Message! topic = ", topic, " message = ", message)
# Ugly Hack Alert: the 'ssl' parameter points to the SSL Module directly.
# It seems to just work. No clue if the SSL certificate is actually verified.
client = MQTTClient(client_id, broker, port, username, pw, ssl=ssl)
res = client.connect()
if res != 0:
sys.exit("ERROR Connecting to MQTT: ", res)
client.subscribe(topic)
client.set_callback(on_message)
# "wait_msg()" will block until one message is received (and AFTER 'on_message' is called).
# use "check_msg()" for non-blocking equivalent.
client.wait_msg()
Javascript (Browser)
code from:
https://gist.github.com/narutaro/6461c0524f7d7ff01e21c2ecb0be84ca
and
https://www.emqx.com/en/blog/mqtt-js-tutorial
<script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script>
<script>
// Create an MQTT client instance
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'My-JS-Client',
username: 'USERNAME',
password: 'PASSWORD',
}
let topic = "mytopic" ;
let message = "fooBar9" ;
// if the MQTT.js library wasn't loaded, this will be undefined
console.log("MQTT library = ", mqtt );
let client = mqtt.connect('wss://mqtt.renert.housegordon.com/mqtt', options );
// Client will be a valid MQTT object, even if the connection failed or hasn't completed yet
console.log("MQTT Client = ", client);
client.on('connect', function () {
//TODO:
// "connect" will not be called if there's a connection error,
// consider using a timeout to detect connection errors.
console.log('Connected to MQTT')
console.log("Subscribing to a topic");
client.subscribe(topic);
console.log("publishing message...");
client.publish(topic, message);
});
client.on('message', function (topic, message) {
// The message parameter is a UInt8Array Buffer,
console.log("Got Message! topic = ", topic, " message = ", message) ;
// if you know the message is a string, decode it like so (might fail with UTF-8 characters):
var str = String.fromCharCode.apply(null, message);
console.log("Message as string: ", str);
});
//If/when you need to:
//client.end();
</script>