跳到主要内容

MQTT

MQTT topic & Wildcards

https://www.emqx.com/zh/blog/advanced-features-of-mqtt-topics

topic 通过 / 进行分层。

单层通配符

+ 匹配单层

example:

  • +
  • sensor/+
  • sensor/+/temperature

多层通配符

# 用于匹配任意层级的通配符。在使用多层通配符时,它比需占据整个层级并且必须是主题的最后一个字符

example:

  • sensor/#
  • sensor/temperature/#
  • sensor/+/temperature/#

不同场景的 topic 设计

智能家居

  • myhome/bedroom/temperature
  • myhome/bedroom/humidity
  • myhome/bedroom/airquality
  • myhome/livingroom/temperature
  • myhome/livingroom/humidity
  • myhome/livingroom/airquality
  • myhome/kitchen/temperature
  • myhome/kitchen/humidity
  • myhome/kitchen/airquality
  1. 获取卧室的温度、湿度、空气质量 myhome/bedroom/#
  2. 获取三个房间的温度数据 myhome/+/temperature
  3. 获取所有的数据 myhome/#

充电桩

  • 上行:ocpp/cp/${cid}/notify/${action}
  • 下行:ocpp/cp/${cid}/reply/${action}
  1. 充电桩上线时发送上线请求: ocpp/cp/${cid}/notify/bootNotification
  2. 发布充电请求: ocpp/cp/${cid}/notify/startTransaction
  3. 上前订阅该 topic 接收上线应答: ocpp/cp/${cid}/reply/bootNotification
  4. 充电前订阅该 topic 接收充电应答: ocpp/cp/${cid}/reply/startTransaction

及时消息

  • 一对一聊天 chat/user/${user_id}/inbox
  • 群聊 chat/group/${group_id}/inbox
  • 添加好友 req/user/${user_id}/add
  • 接收好友申请 resp/user/${user_id}/add
  • 用户在线状态 user/${user_id}/status

Topic 的建议

  • 不建议使用 # 订阅所有主题
  • 不建议主题以 / 开头或结尾,例如 /chatchat/
  • 不建议在主题里添加空格及非 ASCII 特殊字符
  • 同一主题层级建议使用下划线_或横杠-连接单词(或使用驼峰命名)
  • 尽量使用较少的主题层级
  • 当使用通配符时,将唯一值的主题层(例如设备号)越靠近第一层越好。例如 device/001/command/#device/command/001/# 更好