MQTT
The MQTT API enables scripts to publish and subscribe to MQTT topics, allowing integration with IoT platforms and message brokers.
Overview
The MQTT global object provides functionality to:
- Check MQTT connection status
- Subscribe to topics and receive messages
- Publish messages to topics
- Handle connection/disconnection events
MQTT must be enabled and configured in the device settings before scripts can use MQTT functionality.
API Reference
MQTT.isConnected()
Checks if the device is connected to an MQTT broker.
Syntax:
MQTT.isConnected() -> boolean
Returns: true if connected, false otherwise
Example:
if (MQTT.isConnected()) {
console.log("MQTT is connected");
MQTT.publish("device/status", "online");
} else {
console.log("MQTT is not connected");
}
MQTT.subscribe()
Subscribes to an MQTT topic.
Syntax:
MQTT.subscribe(topic, callback[, userdata]) -> undefined
| Property | Type | Description | ||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| string | Topic filter to subscribe to (supports wildcards) | ||||||||||||
| function | Function called when message is received
| ||||||||||||
| any | Optional data to pass to callback |
Throws exception if:
- Parameters are invalid
- MQTT is disabled
- Subscription limit reached (max 10 per script)
- Invalid topic filter
Example:
// Subscribe to a specific topic
MQTT.subscribe("sensors/temperature", function(topic, message) {
console.log("Received on", topic, ":", message);
let temp = parseFloat(message);
if (temp > 30) {
Shelly.call("Switch.Set", {id: 0, on: true}); // Turn on cooling
}
});
// Subscribe with wildcards
MQTT.subscribe("sensors/+/status", function(topic, message, ud) {
console.log("Sensor status update:", topic, "=", message);
console.log("User data:", ud);
}, "my_context");
MQTT.unsubscribe()
Unsubscribes from a previously subscribed topic.
Syntax:
MQTT.unsubscribe(topic) -> boolean
| Property | Type | Description |
|---|---|---|
| string | Topic to unsubscribe from |
Returns: true if unsubscribed, false if subscription doesn't exist
Example:
// Unsubscribe from a topic
if (MQTT.unsubscribe("sensors/temperature")) {
console.log("Unsubscribed successfully");
}
MQTT.publish()
Publishes a message to an MQTT topic.
Syntax:
MQTT.publish(topic, message[, qos[, retain]]) -> boolean
| Property | Type | Description |
|---|---|---|
| string | Topic to publish to |
| string | Message payload |
| number | Quality of Service: 0 (at most once), 1 (at least once), 2 (exactly once). Default: 0 |
| boolean | If true, message is retained by broker. Default: false |
Returns: true if message was queued, false if MQTT is disconnected
Example:
// Simple publish
MQTT.publish("device/status", "online");
// Publish with QoS and retain
MQTT.publish("device/config", JSON.stringify({
id: Shelly.getDeviceInfo().id,
uptime: Shelly.getUptimeMs()
}), 1, true);
// Publish sensor data
let temp = Shelly.getComponentStatus("temperature", 0);
if (temp) {
MQTT.publish("sensors/temperature", String(temp.tC), 0, false);
}
MQTT.setConnectHandler()
Sets a handler for MQTT connection established events.
Syntax:
MQTT.setConnectHandler(callback[, userdata])
| Property | Type | Description | ||||||
|---|---|---|---|---|---|---|---|---|
| function | Function called when MQTT connects
| ||||||
| any | Optional data to pass to callback |
Example:
MQTT.setConnectHandler(function() {
console.log("MQTT connected!");
// Subscribe to topics on connect
MQTT.subscribe("commands/+", handleCommand);
// Publish online status
MQTT.publish("device/status", "online", 0, true);
});
MQTT.setDisconnectHandler()
Sets a handler for MQTT connection closed events.
Syntax:
MQTT.setDisconnectHandler(callback[, userdata])
| Property | Type | Description | ||||||
|---|---|---|---|---|---|---|---|---|
| function | Function called when MQTT disconnects
| ||||||
| any | Optional data to pass to callback |
Example:
MQTT.setDisconnectHandler(function() {
console.log("MQTT disconnected!");
// Perform cleanup or store state
});
Complete Examples
Temperature Monitor with MQTT
// Publish temperature readings every minute
Timer.set(60000, true, function() {
if (!MQTT.isConnected()) {
console.log("MQTT not connected, skipping");
return;
}
let temp = Shelly.getComponentStatus("temperature", 0);
if (temp) {
let payload = JSON.stringify({
temperature: temp.tC,
humidity: temp.rh || null,
timestamp: Date.now()
});
MQTT.publish("sensors/shelly/temperature", payload, 1, false);
console.log("Published temperature:", temp.tC);
}
});
MQTT Command Handler
// Handle commands via MQTT
MQTT.subscribe("shelly/commands", function(topic, message) {
try {
let cmd = JSON.parse(message);
switch(cmd.action) {
case "switch":
Shelly.call("Switch.Set", {
id: cmd.id || 0,
on: cmd.state
});
MQTT.publish("shelly/response", JSON.stringify({
success: true,
action: cmd.action
}));
break;
case "reboot":
MQTT.publish("shelly/response", "Rebooting...");
Shelly.call("Shelly.Reboot");
break;
default:
MQTT.publish("shelly/response", JSON.stringify({
error: "Unknown command"
}));
}
} catch(e) {
MQTT.publish("shelly/response", JSON.stringify({
error: e.toString()
}));
}
});
// Connection management
MQTT.setConnectHandler(function() {
console.log("Ready to receive commands");
MQTT.publish("shelly/status", "ready", 1, true);
});
Bridge Pattern
// Bridge between MQTT and HTTP
MQTT.subscribe("bridge/http/request", function(topic, message) {
let request = JSON.parse(message);
Shelly.call("HTTP.Request", {
method: request.method || "GET",
url: request.url,
body: request.body || null,
headers: request.headers || null
}, function(response, error_code) {
let result = {
id: request.id,
success: error_code === 0,
response: response,
error: error_code
};
MQTT.publish("bridge/http/response", JSON.stringify(result));
});
});
Topic Wildcards
MQTT supports wildcards in topic filters:
+- Single level wildcard#- Multi-level wildcard
// Subscribe to all temperature sensors
MQTT.subscribe("sensors/+/temperature", handler);
// Subscribe to all sensor data
MQTT.subscribe("sensors/#", handler);
// Subscribe to all device commands
MQTT.subscribe("devices/+/commands/+", handler);
QoS Levels
| Level | Name | Description |
|---|---|---|
| 0 | At most once | Fire and forget, no guarantee |
| 1 | At least once | Guaranteed delivery, possible duplicates |
| 2 | Exactly once | Guaranteed single delivery |
Resource Limits
- Maximum 10 topic subscriptions per script
- Message size limited by available memory
- Topic length limited to 256 characters
- Subscriptions cleared when script stops