mqtt-client

Universal MQTT Client for OpenClaw with Node.js/mqtt.js. Enables Connection Management, Subscription Management, Message Handling and OpenClaw Integration for arbitrary MQTT-based automation.

Safety Notice

This listing is from the official public ClawHub registry. Review SKILL.md and referenced scripts before running.

Copy this and send it to your AI assistant to learn

Install skill "mqtt-client" with this command: npx skills add sanwebgit/mqtt-client-openclaw

📡 MQTT OpenClaw Skill

Production-ready MQTT client for OpenClaw automation. Universal - not bound to specific systems.

Universal MQTT Client for OpenClaw with Node.js/mqtt.js. Connect to any MQTT broker to subscribe to topics, publish messages, and react to state changes. The client automatically handles reconnection, supports wildcards for flexible topic patterns, and can trigger alerts when values cross thresholds (e.g., battery below 10% or temperature above 30°C). Use this skill to integrate OpenClaw with smart home systems such as ioBroker, Home Assistant, Zigbee2MQTT, Shelly devices, other OpenClaw instances (to communicate between them), or any other MQTT-based system.


🚀 Quick Start

Prerequisites

npm install mqtt

Minimal Example

const { MqttClient } = require('./scripts/mqtt-client.js');

const client = new MqttClient({
  broker: process.env.MQTT_BROKER,
  username: process.env.MQTT_USERNAME,
  password: process.env.MQTT_PASSWORD
});

client.on('message', (topic, payload) => console.log(`${topic}: ${payload}`));

await client.connect();
await client.subscribe('home/#');

⚙️ Configuration

Environment Variables

VariableDefaultDescription
MQTT_BROKERlocalhostBroker URL (with or without protocol)
MQTT_BROKER_PORT1883Broker port
MQTT_USERNAME-Username (optional)
MQTT_PASSWORD-Password (optional)
MQTT_CLIENT_IDauto-generatedClient ID (max 23 chars)
MQTT_SUBSCRIBE_TOPIC#Default topic to subscribe
MQTT_KEEPALIVE60Keep-alive interval (seconds)
MQTT_RECONNECT_PERIOD5000Reconnect interval (ms)

Auto-Setup

When first used, the skill automatically creates config in ~/.openclaw/openclaw.json:

{
  "skills": {
    "entries": {
      "mqtt-client": {
        "enabled": true,
        "env": {
          "MQTT_BROKER": "localhost",
          "MQTT_BROKER_PORT": "1883"
        }
      }
    }
  }
}

⚠️ Existing values are NOT overwritten.


🔌 Connection Management

Auto-Reconnect

const client = new MqttClient({
  broker: 'mqtt://localhost:1883',
  reconnectPeriod: 5000,
  connectTimeout: 30000,
  maxReconnectAttempts: 10
});

Keep-Alive

const client = new MqttClient({
  broker: 'mqtt://localhost:1883',
  keepalive: 60  // seconds
});

LWT (Last Will & Testament)

const client = new MqttClient({
  will: {
    topic: 'openclaw/status',
    payload: JSON.stringify({ status: 'offline' }),
    qos: 1,
    retain: true
  }
});

Graceful Disconnect

await client.disconnect();  // with timeout
await client.disconnect(5000);

📬 Subscription Management

Basic Subscribe

// Single topic
await client.subscribe('home/bridge/info');

// Multiple topics
await client.subscribe(['home/bridge/info', 'home/bridge/state']);

Wildcards

WildcardDescriptionExample
+Single levelhome/+/temperature
#Multi levelhome/sensors/#

QoS Levels

LevelNameDescription
0At most onceFire and forget
1At least onceAcknowledged delivery
2Exactly onceHandshake protocol
await client.subscribe('topic', { qos: 2 });

Dynamic Subscribe/Unsubscribe

await client.subscribe('new/topic');
await client.unsubscribe('old/topic');
await client.unsubscribeAll();

📤 Message Handling

Publish

// Simple
await client.publish('home/lights/set', 'ON');

// With options
await client.publish('home/lights/set', 'ON', { qos: 1, retain: true });

// As JSON (auto-stringified)
await client.publish('home/lights/set', { state: 'ON', brightness: 255 });

Retained Messages

// Set retained
await client.publish('home/announcement', 'Hello', { retain: true });

// Delete retained (empty payload)
await client.publish('home/announcement', '', { retain: true });

JSON Parsing

Automatic parsing - payload is already an object for JSON messages:

client.on('message', (topic, payload) => {
  if (typeof payload === 'object') {
    console.log('JSON:', payload.key);
  }
});

🔔 Threshold Triggers

React to value changes with triggers:

// Battery low trigger
client.addTrigger('battery-low', {
  topic: 'home/+/battery',
  path: 'value',
  operator: '<',
  threshold: 10,
  valueType: 'number',
  cooldown: 60000,
  callback: (event) => console.log('⚠️ Low battery:', event.value)
});

// Temperature high trigger
client.addTrigger('temp-high', {
  topic: 'home/sensors/+/temperature',
  path: 'value',
  operator: '>',
  threshold: 30,
  valueType: 'number',
  callback: (event) => console.log('🔥 Hot:', event.value)
});

Trigger Operators

OperatorDescription
>Greater than
<Less than
>=Greater or equal
<=Less or equal
==Equal
!=Not equal
containsString contains
startsWithString starts with

📊 Health & State

Get Health Status

const health = client.getHealth();
// { connected, reconnecting, lastConnected, messagesReceived, latency }

Get Current State

const state = client.getState();
// { status, broker, subscriptions }

Message History

// Last messages for topic
const history = client.getMessageHistory('home/+/temperature');

// Last message
const last = client.getLastMessage('home/sensors/#');

// Clear history
client.clearHistory();

📋 API Reference

Constructor Options

OptionTypeDefaultDescription
brokerstringenvMQTT Broker URL
usernamestringenvUsername
passwordstringenvPassword
clientIdstringautoClient ID
reconnectPeriodnumber5000Reconnect interval (ms)
connectTimeoutnumber30000Connection timeout (ms)
keepalivenumber60Keep-alive (s)
messageHistorySizenumber50Max history entries
parseJsonbooleantrueAuto JSON parse
logLevelstringinfodebug/info/warn/error

Methods

MethodDescription
connect()Establish connection
disconnect([ms])Graceful disconnect
subscribe(topic, opts)Subscribe to topic(s)
unsubscribe(topic)Unsubscribe
publish(topic, payload, opts)Publish message
getMessageHistory([topic])Get message history
getHealth()Health status
getState()Current state
isConnected()Connection check
addTrigger(id, config)Add threshold trigger
removeTrigger(id)Remove trigger
getTriggers()List triggers

Events

EventDescription
connectSuccessfully connected
disconnectDisconnected
messageMessage received (topic, payload, packet)
errorError occurred
offlineClient offline
reconnectingAttempting reconnect
reconnectSuccessfully reconnected

📁 Resources

scripts/

  • mqtt-client.js - Main library

references/

  • mqtt-topics.md - Topic naming conventions

🔗 External Links

Source Transparency

This detail page is rendered from real SKILL.md content. Trust labels are metadata-based hints, not a safety guarantee.

Related Skills

Related by shared tags or category signals.

Coding

Spicy Ai Video

Turn a 60-second talking head clip into 1080p high-energy edited videos just by typing what you need. Whether it's turning bland footage into visually intens...

Registry SourceRecently Updated
Coding

Video Maker Fast

Get polished MP4 videos ready to post, without touching a single slider. Upload your video clips (MP4, MOV, AVI, WebM, up to 500MB), say something like "trim...

Registry SourceRecently Updated
Coding

Generation Generator

generate text prompts or clips into AI generated videos with this skill. Works with MP4, MOV, PNG, JPG files up to 500MB. marketers, content creators, social...

Registry SourceRecently Updated
Coding

Editor On Android

Get edited MP4 clips ready to post, without touching a single slider. Upload your video clips (MP4, MOV, AVI, WebM, up to 500MB), say something like "trim th...

Registry SourceRecently Updated