请选择 进入手机版 | 继续访问电脑版

『瀚思彼岸』» 智能家居技术论坛

 找回密码
 立即注册
查看: 17309|回复: 16

[经验分享] MQTT

[复制链接]

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
发表于 2017-7-29 18:31:52 | 显示全部楼层 |阅读模式
本帖最后由 xzhang 于 2017-7-29 19:15 编辑

MQTT(也称MQ遥测传输)是基于TCP/IP的机器对机器/物联网连接协议。 它允许非常轻量级的发布/订阅消息传输。

MQTT 和 Home Assistant工作的第一步就是选择一个broker

要将MQTT集成到 Home Assistant 中,请将以下部分添加到 configuration.yaml 文件中。 请记住,使用 embedded MQTT broker 将运行最小的:
# Example configuration.yaml entry
mqtt:

要连接到您自己的 MQTT broker
# Example configuration.yaml entry
mqtt:
  broker: IP_ADDRESS_BROKER

附加功能
回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:53 | 显示全部楼层
本帖最后由 xzhang 于 2017-7-29 18:30 编辑

MQTT 证书

使用证书将为您提供额外的MQTT通信安全层。
要将 MQTT 证书集成到 Home Assistant 中,请将以下部分添加到 configuration.yaml 文件中:
# Example configuration.yaml entry
mqtt:
  certificate: /home/paulus/dev/addtrustexternalcaroot.crt

配置变量:
  • certificate(可选): auto'或被该客户端信任的证书颁发机构的证书文件。 'auto'使用捆绑的证书。 如果指定了文件,文件应包含签署代理证书的证书颁发机构的根证书,但可能包含多个证书。 示例: /home/user/identrust-root.pem
  • client_key (可选): 客户端密钥,例如 /home/user/owntracks/cookie.key.
  • client_cert(可选): 客户端证书,例如 /home/user/owntracks/cookie.crt.
回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:54 | 显示全部楼层
本帖最后由 xzhang 于 2017-7-29 17:21 编辑

MQTT Discovery

MQTT 设备的 discovery 将使一个人能够在 Home Assistant 中使用最小配置便可工作。 设备使用的主题和配置在设备自身完成。 类似于HTTP binary sensorHTTP sensor
MQTT discovery支持:
要启用MQTT discovery,请将以下内容添加到您的 configuration.yaml 文件中
# Example configuration.yaml entry
mqtt:
  discovery: true
  discovery_prefix: homeassistant

配置变量:
  • discovery (可选):MQTT discovery 是否启用。 默认为 False。
  • discovery_prefix (可选):discovery topic 的前缀。 默认为 homeassistant。
discovery topic 需要遵循特定格式:
<discovery_prefix>/<component>/[<node_id>/]<object_id>/<>

  • <component>: 支持的组件之一,例如. binary_sensor.
  • <node_id>: (可选)提供 topic 的节点的ID。
  • <object_id>: 设备的ID。 这将成为 Home Assistant 中 的 entity_id。
  • <>: The topic config or state which defines the current action.
如果添加了新的设备,那么有效载荷将像您的 configuration.yaml文件中的条目一样被检查。 这意味着缺少的变量将被平台的默认值填充。 所有必需的配置变量必须存在于发给 /config 的初始有效载荷(payload)中。
客户端可以使用 <node_id> 级别,只能通过使用一个通配符主题(如 <discovery_prefix>/+/<node_id>/+/set)来订阅自己的(命令)主题。
例子
您的花园的运动检测设备可以由 binary sensor 表示,该设备将其配置作为 JSON payload 发送到 Configuration topic。 config 收到第一条消息后,发送到状态主题的 MQTT 消息将更新 Home Assistant 中的状态。
  • Configuration topic: homeassistant/binary_sensor/garden/config
  • State topic: homeassistant/binary_sensor/garden/state
  • Payload: {"name": "garden", "device_class": "motion"}
手动创建新传感器。 有关更多详细信息,请参阅 MQTT testing section.
$ mosquitto_pub -h 127.0.0.1 -p 1883 -t "homeassistant/binary_sensor/garden/config" -m '{"name": "garden", "device_class": "motion"}'

更新状态:
$ mosquitto_pub -h 127.0.0.1 -p 1883 -t "homeassistant/binary_sensor/garden/state" -m ON

设置 switch 是类似的但是需要设置 command_topic ,请参考 MQTT switch documentation.
  • Configuration topic: homeassistant/switch/irrigation/config
  • State topic: homeassistant/switch/irrigation/state
  • Payload: {"name": "garden", "command_topic": "homeassistant/switch/irrigation/set"}
$ mosquitto_pub -h 127.0.0.1 -p 1883 -t "homeassistant/switch/irrigation/config" \
  -m '{"name": "garden", "command_topic": "homeassistant/switch/irrigation/set"}'

设置状态:
$ mosquitto_pub -h 127.0.0.1 -p 1883 -t "homeassistant/switch/irrigation/set" -m ON

回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:55 | 显示全部楼层
MQTT 发布服务

MQTT 组件将注册允许向 MQTT 主题发布消息的 publish 服务。 有两种方式来指定你的 payload。 您可以使用 payload 来硬编码一个payload,也可以使用 payload_template 来指定一个将被渲染以生成 payload 的template
{
  "topic": "home-assistant/light/1/command",
  "payload": "on"
}

{
  "topic": "home-assistant/light/1/state",
  "payload_template": "{{ states('device_tracker.paulus') }}"
}

回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:56 | 显示全部楼层
MQTT Birth and Last Will

MQTT 支持所谓的出生和最后遗嘱(LWT)消息。 前者用于在服务启动后发送消息,后者用于通知其他客户端关于未正确断开的客户端。

要将 MQTT Birth 和 Last Will 消息集成到 Home Assistant 中,请将以下部分添加到 configuration.yaml 文件中:
# Example configuration.yaml entry
mqtt:
  birth_message:
    topic: 'hass/status'
    payload: 'online'
  will_message:
    topic: 'hass/status'
    payload: 'offline'

配置变量:
  • birth_message (可选):
    • topic (必需):发布消息的MQTT主题。
    • payload (必需):消息内容。
    • qos (可选):主题的最大QoS级别。 默认值为0。
    • retain (可选):发布的消息是否应该保留标志。 默认为 True.
  • will_message (可选):
    • topic(必需):发布消息的MQTT主题。
    • payload (必需):消息内容。
    • qos (可选):主题的最大QoS级别。 默认值为0。
    • retain(可选):发布的消息是否应该保留标志。 默认为 True.

回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:57 | 显示全部楼层
MQTT Testing
The mosquitto broker package ships commandline tools (often as *-clients package) to send and receive MQTT messages. As an alternative have a look at hbmqtt_pub and hbmqtt_sub which are provided by HBMQTT. For sending test messages to a broker running on localhost check the example below:
mosquitto 代理程序包括命令行工具(通常作为 *-clients包)发送和接收 MQTT 消息。 另外看一下 HBMQTT 提供的 hbmqtt_pubhbmqtt_sub 。 要将测试消息发送到本地运行的代理,请查看以下示例:
$ mosquitto_pub -h 127.0.0.1 -t home-assistant/switch/1/on -m "Switch is ON"


如果使用嵌入式MQTT代理,则命令看起来有所不同,因为您需要添加MQTT协议版本。
$ mosquitto_pub -V mqttv311 -t "hello" -m world



或者如果您使用 API 密码:
$ mosquitto_pub -V mqttv311 -u homeassistant -P <your api password> -t "hello" -m world



Another way to send MQTT messages by hand is to use the “Developer Tools” in the Frontend. Choose “Call Service” and then mqtt/mqtt_send under “Available Services”. Enter something similar to the example below into the “Service Data” field.手动发送 MQTT 消息的另一种方法是在前端使用“Developer Tools”。 选择““Call Service”,然后选择“Available Services”下的 mqtt/mqtt_send 。 在Service Data”字段中输入类似于以下示例的内容。
{
   "topic":"home-assistant/switch/1/on",
   "payload":"Switch is ON"
}


消息应出现在总线上:
... [homeassistant] Bus:Handling <Event MQTT_MESSAGE_RECEIVED[L]: topic=home-assistant/switch/1/on, qos=0, payload=Switch is ON>



For reading all messages sent on the topic home-assistant to a broker running on localhost:
要查看在本地主机上运行的代理发给 home-assistant 主题所有消息:
$ mosquitto_sub -h 127.0.0.1 -v -t "home-assistant/#"


对于嵌入式MQTT代理,命令如下所示:
$ mosquitto_sub -v -V mqttv311 -t "#"


如果需要,请添加用户名 homeassistant 和您的 API 密码。

回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:58 | 显示全部楼层
MQTT Logging
The logger component 允许记录收到的 MQTT 消息。
# Example configuration.yaml entry
logger:
  default: warning
  logs:
    homeassistant.components.mqtt: debug


回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:31:59 | 显示全部楼层
Processing JSON
MQTT  switch 和  sensor 平台支持在 MQTT 消息中处理 JSON,并使用 JSONPath 进行解析。 JSONPath 允许您指定要使用的值所在的位置。 以下示例将始终返回值100。

JSONPath queryJSON
somekey{ 'somekey': 100 }
somekey[0]{ 'somekey': [100] }
somekey[0].value{ 'somekey': [ { value: 100 } ] }
To use this, add the following key to your configuration.yaml:
switch:
  platform: mqtt
  state_format: 'json:somekey[0].value'

也可以使用值模板提取 JSON 值:
switch:
  platform: mqtt
  value_template: '{{ value_json.somekey[0].value }}'

More information about the full JSONPath syntax can be found in their documentation.
回复

使用道具 举报

5

主题

45

帖子

258

积分

论坛积极会员

积分
258
金钱
213
HASS币
0
 楼主| 发表于 2017-7-29 18:32:00 | 显示全部楼层
MQTT Brokers
MQTT 组件需要您运行一个 MQTT 代理。 有四个选项,每个选项具有不同程度的设置和隐私。

Embedded broker

Home Assistant 包含嵌入式 MQTT 代理。 如果没有提供 broker 配置,HBMQTT broker 将被启动,并且 Home Assistant 将连接它。 嵌入式代理默认配置:


SettingValue
Hostlocalhost
Port1883
Protocol3.1.1
Userhomeassistant
PasswordYour API password
Websocket port8080
# Example configuration.yaml entry
mqtt:



Owntracks在 Owntracks 首选项(Android:v1.2.3 +,iOS:v9.5.1 +)中打开配置管理; 找到名为 mqttProtocolLevel 的值,并将其值设置为 4. 应用程序现在将使用MQTT 3.1.1进行连接,这与嵌入式代理兼容。
要将 Owntracks 与内部 broker  一起使用,必须做些小型更改,以便应用程序使用MQTT协议3.1.1(协议级别4)。
设置如果要自定义嵌入式代理的设置,请使用 embedded: 和 HBMQTT Broker配置中显示的值。 这将取代默认配置。
# Example configuration.yaml entry
mqtt:
  embedded:
    # Your HBMQTT config here. Example at:
    # [url]http://hbmqtt.readthedocs.org/en/latest/references/broker.html#broker-configuration[/url]



Run your own这是最私人的选择,但需要更多的工作。 有多个免费和开源的 brokers 可以从中选择:例如Mosquitto, EMQ, or Mosca.
# Example configuration.yaml entry
mqtt:
  broker: 192.168.1.100

Configuration variables:
  • broker (可选):您的MQTT代理的IP地址或主机名,例如192.168.1.32。
  • port (可选):要连接的网络端口。默认为1883。
  • client_id (可选):Home Assistant 将使用的客户端ID。在服务器上必须是唯一的。默认是随机生成的。
  • keepalive(可选):为该客户端发送keep alive消息之间的时间(秒)。默认为60。
  • username (可选):与您的MQTT代理一起使用的用户名。
  • password (可选):与MQTT代理一起使用的用户名的相应密码。
  • protocol(可选):使用协议:3.1或3.1.1。默认情况下,它连接到3.1.1,如果服务器不支持3.1.1,则返回3.1。
  • certificate(可选):证书文件的路径,例如  /home/user/.homeassistant/server.crt.
  • tls_insecure (可选):在服务器证书中设置服务器主机名的验证。
  • tls_version(可选):使用TLS / SSL协议版本。可用的选项有: auto, 1.0, 1.1, 1.2. Defaults to auto.
警告


Ubuntu 14.04 LTS中包含的 Mosquitto 软件包有问题。 在MQTT配置中指定  protocol: 3.1 以解决此问题。 如果你得到这个错误 AttributeError: module 'ssl' has no attribute 'PROTOCOL_TLS',那么你需要设置 tls_version: 1.2.



注意

如果您在不同的服务器上运行一个 Mosquitto 实例,使用适当的 SSL 加密这样的服务,则可能必须将证书设置为操作系统自己的 .crt 证书文件。 在 Ubuntu 的例子中,这将是 certificate: /etc/ssl/certs/ca-certificates.crt




Public broker
Mosquitto 项目运行public broker。 这是最容易设置的,但是没有任何隐私,因为所有的消息都是公开的。 仅用于测试目的,而不是真正跟踪您的设备或控制您的家庭。

CloudMQTTCloudMQTT 是托管的专用 MQTT 实例,最多可免费连接10个设备。 这足以开始比如使用 OwnTracks,并给您一个可能的感觉。

注意
Home Assistant 不隶属于CloudMQTT,也不会收到任何回扣。

  • Create an account (no payment details needed)
  • Create a new CloudMQTT instance(Cute Cat is the free plan)
  • From the control panel, click on the Details button.
  • Create unique users for Home Assistant and each phone to connect
    (CloudMQTT does not allow two connections from the same user)
    • Under manage users, fill in username, password and click add
    • Under ACLs, select user, topic #, check ‘read access’ and ‘write access’
  • Copy the instance info to your configuration.yaml:
mqtt:
  broker: CLOUTMQTT_SERVER
  port: CLOUDMQTT_PORT
  username: CLOUDMQTT_USER
  password: CLOUDMQTT_PASSWORD

注意
如果连接到 CloudMQTT 的加密通道(端口范围20000-30000),Home Assistant 将自动加载正确的证书。



回复

使用道具 举报

123

主题

4620

帖子

1万

积分

管理员

囧死

Rank: 9Rank: 9Rank: 9

积分
15963
金钱
11258
HASS币
45
发表于 2017-7-29 18:48:07 | 显示全部楼层
灌水嫌疑,请把贴子整合到一层,否则将删除扣分。
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Hassbian

GMT+8, 2024-3-29 21:48 , Processed in 0.085648 second(s), 31 queries .

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表