Mqtt Client

v1.2.2

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

1· 169·0 current·0 all-time
bySanweb@sanwebgit
Security Scan
VirusTotalVirusTotal
Pending
View report →
OpenClawOpenClaw
Benign
high confidence
Purpose & Capability
Name/description describe an MQTT client and the package requires only MQTT-related configuration (broker, username, password, clientId). The code and README implement connection, subscription, publishing, triggers and health monitoring — all coherent with an MQTT client skill.
Instruction Scope
Runtime instructions and examples focus on connecting to an MQTT broker and managing topics/messages. The SKILL.md states the skill will auto-create a config entry in ~/.openclaw/openclaw.json; the library also looks for openclaw.json in several locations. This is within scope for a skill that persists its own configuration, but users should be aware it reads configuration from multiple paths and may create a config file under the user home directory.
Install Mechanism
No install spec is provided (instruction-only skill). The README instructs installing the well-known npm package 'mqtt' — no downloads from arbitrary URLs or archive extraction are present in the bundle. Code files are included in the skill package (no external installers).
Credentials
Environment variables referenced are MQTT-specific (MQTT_BROKER, MQTT_BROKER_PORT, MQTT_USERNAME, MQTT_PASSWORD, etc.). The code reads HOME for config file paths, but does not request unrelated credentials or unrelated system secrets.
Persistence & Privilege
The skill does not request always:true and is user-invocable. It documents auto-creating/updating an entry under ~/.openclaw/openclaw.json to store its enabled state and env defaults. Writing its own config is expected for a skill, but users should confirm they are comfortable with the skill creating a file under their home directory.
Assessment
This skill appears to do what it says: it's an MQTT client and uses only MQTT-related environment variables. Before installing: (1) review and confirm you trust the MQTT broker you will connect to — credentials (username/password) are sent to that broker; (2) be aware the skill may create an entry in ~/.openclaw/openclaw.json and it also reads openclaw.json from several locations (home, cwd, __dirname), so inspect those files if you care about leakage of other config; (3) install the official 'mqtt' npm package as instructed and review the included scripts/mqtt-client.js if you want to verify there are no additional network calls or file writes; (4) run the skill in a limited environment or sandbox if you plan to connect to untrusted brokers. Overall there are no strong red flags, but double-check broker/trust and the created config file before wide deployment.

Like a lobster shell, security has layers — review code before you run it.

latestvk97af8q0zccteej4zfn927nzkx83hh6v
169downloads
1stars
9versions
Updated 3w ago
v1.2.2
MIT-0

📡 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

Comments

Loading comments...