← 返回
未分类 中文

Mqtt Client

Universal MQTT Client for OpenClaw with Node.js/mqtt.js. Enables Connection Management, Subscription Management, Message Handling and OpenClaw Integration fo...
基于Node.js/mqtt.js的OpenClaw通用MQTT客户端,支持连接管理、订阅管理、消息处理及OpenClaw集成。
sanwebgit sanwebgit 来源
未分类 clawhub v1.2.2 1 版本 100000 Key: 无需
★ 1
Stars
📥 544
下载
💾 5
安装
1
版本
#latest

概述

📡 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

版本历史

共 1 个版本

  • v1.2.2 当前
    2026-03-30 18:43 安全 安全

安全检测

腾讯云安全 (Keen)

安全,无风险
查看报告

腾讯云安全 (Sanbu)

安全,无风险
查看报告

🔗 相关推荐

it-ops-security

Iobroker Simple Api

sanwebgit
通过 iobroker simple-api 适配器完整访问 ioBroker,可读取状态、对象、历史数据,写入状态、执行脚本等。
★ 1 📥 459
dev-programming

Mcporter

steipete
使用 mcporter CLI 直接列出、配置、认证及调用 MCP 服务器/工具(支持 HTTP 或 stdio),涵盖临时服务器、配置编辑及 CLI/类型生成功能。
★ 195 📥 67,668
dev-programming

CodeConductor.ai

larsonreever
AI驱动平台,提供快速全栈开发、智能体、工作流自动化及低代码AI集成的可扩展产品创建。
★ 72 📥 181,884