# MQTT Client

> 向 MQTT Broker 发布消息。

Source: https://docs.sommatic.ai/zh/nodes/io.mqtt/

- 标识: `io.mqtt`
- 类别: 输入与输出
- 版本: 1.0.0
- 状态: 部分可用. 始终执行发布（忽略声明的 `action`），且仅支持 QoS 0。
- 执行方式: async

向 MQTT Broker 发布消息。

## 配置

- `connection_id` (string, 必填): MQTT Broker 的凭据。接受 `basic-auth`（用户名 + 密码 + 主机 + 端口）、`connection-string`（mqtt:// / mqtts:// URI）或 `object`（高级 MQTT 配置）类型的凭据。
- `topic` (string, 必填)
- `message` (string, 必填): 消息载荷
- `retain` (boolean, 可选): 默认值: `false`.
- `action` (string, 可选): 默认值: `publish`. 可选值: `publish`.

## 输出端口

- `out` (默认): 消息发布成功
- `error`: 发布失败

## 输入契约

- `connection_id` (string, 必填)
- `topic` (string, 必填)
- `message` (string, 必填)
- `retain` (boolean, 可选)
- `action` (string, 可选)

## 输出契约

- `published` (boolean, 可选): 发布是否成功

## 在表达式中

后续节点可通过 `$("MQTT Client").item.json.<路径>` 读取此节点输出中的内容（请把 `MQTT Client` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `out` 返回的路径，依据“端口”一节所示的输出。

- `$("MQTT Client").item.json.published` (boolean): 发布是否成功 **worker 不返回：读取结果为 undefined.**
- `$("MQTT Client").item.json.result` (object) = `{…}` (编辑器不提示)
- `$("MQTT Client").item.json.result.published` (boolean) = `true` (编辑器不提示)
- `$("MQTT Client").item.json.result.topic` (string) = `"plant/line-2/commands"` (编辑器不提示)


## 工作原理

连接 MQTT broker，向一个主题发布一条消息后断开连接。

1. 解析配置。`connection_id`、`topic`、`message` 和 `retain`（默认 false）缺失时回退到输入 payload 中的同名键；前三项为必填。
2. 解析凭据：broker URL 为 `config.url`，或 `mqtt://<config.host>:<config.port>`（端口默认 1883）；密钥中存在 `username` 和 `password` 时使用它们。
3. 建立连接，带 `retain` 标志向 `topic` 发布 `message`，然后关闭连接。
4. 从 `out` 返回 `{ result: { published: true, topic } }`；任何失败都从 `error` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-publish-command",
  "label": "Publish line command",
  "operator_slug": "io.mqtt",
  "operator_version": "1.0.0",
  "config": {
    "connection_id": "pi-credential-xxxx",
    "topic": "plant/line-2/commands",
    "message": "{{ JSON.stringify($json.command) }}",
    "retain": false
  }
}
```

### Envelope

```json
{
  "ok": true,
  "data": {
    "result": {
      "published": true,
      "topic": "plant/line-2/commands"
    }
  },
  "port": "out"
}
```

## 输出端口 (代码中的行为)

### `out`

broker 已接受发布。

```json
{
  "result": {
    "published": true,
    "topic": "plant/line-2/commands"
  }
}
```

### `error`

缺少必填字段、无法解析凭据，或连接/发布失败。

```json
{
  "error": "connect ECONNREFUSED 203.0.113.10:1883"
}
```

## 代码中的行为

- `connection_id`: broker 地址取自凭据配置（`url`，或 `host` + `port`）；`username` 和 `password` 取自对象类型密钥（`basic-auth`、`object`）。`connection-string` 类型的密钥不会被解析：请将 URI 写入凭据配置的 `url`。以 `mqtt://`、`mqtts://`、`ws://` 或 `wss://` 开头的值会直接用作 broker URL，不带凭据。
- `action`: 被忽略：节点始终执行发布，不支持订阅。
- `message`: 作为原始 payload 发送。如需发布 JSON，请先构造字符串，例如 `{{ JSON.stringify($json.command) }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `connection_id is required` | `error` | 未选择 broker 凭据。 |
| `topic is required` | `error` | 配置和输入 payload 中的主题均为空。 |
| `message is required` | `error` | 消息为空。空字符串同样会失败：请至少发布一个字符。 |
| `Connection refused: Not authorized` | `error` | broker 拒绝了凭据中的用户名或密码。 |

## 说明与限制

- 使用客户端默认的 QoS 0 发布，未提供 QoS 选项。每次运行都会新建并关闭连接。
- 输出契约将 `published` 声明在顶层，但 worker 将其放在 `result` 内返回。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "io.mqtt",
  "name": "MQTT Client",
  "category": "io",
  "version": "1.0.0",
  "description": "Publish to MQTT Broker.",
  "capabilities": [
    "mqtt",
    "iot",
    "messaging"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string",
        "title": "MQTT Broker Credential",
        "description": "Credential for the MQTT broker. Accepts credentials of type `basic-auth` (username + password + host + port), `connection-string` (mqtt:// / mqtts:// URI), or `object` (advanced MQTT config).",
        "ui_widget": "connection_picker",
        "ui_options": {
          "credential_types": [
            "basic-auth",
            "connection-string",
            "object"
          ],
          "types": [
            "mqtt"
          ]
        }
      },
      "topic": {
        "type": "string"
      },
      "message": {
        "type": "string",
        "description": "Message payload"
      },
      "retain": {
        "type": "boolean",
        "default": false
      },
      "action": {
        "type": "string",
        "enum": [
          "publish"
        ],
        "default": "publish"
      }
    },
    "required": [
      "connection_id",
      "topic",
      "message"
    ]
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "connection_id": {
        "type": "string"
      },
      "topic": {
        "type": "string"
      },
      "message": {
        "type": "string"
      },
      "retain": {
        "type": "boolean"
      },
      "action": {
        "type": "string"
      }
    },
    "required": [
      "connection_id",
      "topic",
      "message"
    ]
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "published": {
        "type": "boolean",
        "description": "Publish success"
      }
    }
  },
  "ports": [
    {
      "port_id": "out",
      "label": "Published",
      "description": "Message successfully published",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "description": "Publish failed",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "required_resources": [],
  "compatible_worker_pools": [
    "standard-io",
    "iot"
  ],
  "tags": [
    "iot",
    "messaging"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_link_loom",
    "profile": {
      "name": "Link Loom",
      "verified": true,
      "url": "https://me.veripass.com/link-loom",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string",
      "title": "MQTT Broker Credential",
      "description": "Credential for the MQTT broker. Accepts credentials of type `basic-auth` (username + password + host + port), `connection-string` (mqtt:// / mqtts:// URI), or `object` (advanced MQTT config).",
      "ui_widget": "connection_picker",
      "ui_options": {
        "credential_types": [
          "basic-auth",
          "connection-string",
          "object"
        ],
        "types": [
          "mqtt"
        ]
      }
    },
    "topic": {
      "type": "string"
    },
    "message": {
      "type": "string",
      "description": "Message payload"
    },
    "retain": {
      "type": "boolean",
      "default": false
    },
    "action": {
      "type": "string",
      "enum": [
        "publish"
      ],
      "default": "publish"
    }
  },
  "required": [
    "connection_id",
    "topic",
    "message"
  ]
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "connection_id": {
      "type": "string"
    },
    "topic": {
      "type": "string"
    },
    "message": {
      "type": "string"
    },
    "retain": {
      "type": "boolean"
    },
    "action": {
      "type": "string"
    }
  },
  "required": [
    "connection_id",
    "topic",
    "message"
  ]
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "published": {
      "type": "boolean",
      "description": "Publish success"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "out",
    "label": "Published",
    "description": "Message successfully published",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "description": "Publish failed",
    "is_default": false,
    "supports_condition": false
  }
]
```
