MQTT

WeEvent服务对MQTT协议的支持依赖Mosquitto代理。MosquittoMQTT 协议的一个开源实现。Mosquitto详细内容,请参见Mosquitto官网 。同时需要给Broker配置Zookeeper服务。请参见Broker模块安装

协议介绍

  • MQTT是物联网IoT中的主流接入协议,协议具体内容参见http://mqtt.org/
  • WeEvent支持MQTT 3.1.1

MQTT桥接概念

WeEvent 关于物联网IoT设备接入的流程如下图:

../_images/mqtt.png

WeEvent使用Mosquitto来做MQTT协议代理,也可以使用EMQ等商业软件,支持MQTT 3.1.1就可以。

IoT设备往服务器发布事件,一般用来做数据采集,称为上行通道。对应WeEvent使用mqtt_add_inbound_topic 接口来设置桥接。

服务器往IoT设备发布事件,一般用来做控制命令,称为下行通道。对应WeEvent使用mqtt_add_outbound_topic接口来设置桥接。

配置MQTT桥接

Broker服务中,修改配置文件./conf/weevent.properties,然后重新启动服务。

#mqtt broker
#mosquitto安装所在服务器的ip地址及端口号
mqtt.broker.url=tcp://127.0.0.1:1883
#mosquitto使用的用户名  
mqtt.broker.user=${user}  
#mosquitto使用的密码               
mqtt.broker.password=${password}           
mqtt.broker.qos=2
mqtt.broker.timeout=5000
#mosquitto default 20s
mqtt.broker.keep-alive=15
#zookeeper
#zookeeper安装所在服务器的ip地址及端口号
broker.zookeeper.ip=127.0.0.1:2181     
broker.zookeeper.path=/event_broker
broker.zookeeper.timeout=3000

样例演示

IoT设备数据采集

  • WeEvent中创建主题Topic ,例如 com.weevent.iot.event

    $ curl http://localhost:8080/weevent/rest/open?topic=com.weevent.iot.event
    true
    
  • 通过WeEvent设置上行通道的Topic绑定。

    $ curl http://localhost:8080/weevent/master/mqtt_add_inbound_topic?topic=com.weevent.iot.event
    true
    
  • IoT设备发布事件

    IoT设备和传统方式一样通过MQTT协议发布事件。

    $ mosquitto_pub -h localhost -p 1883 -u ${user} -P ${password} -t "com.weevent.iot.event" -m "{\"timestamp\":133345566,\"key\":\"temperature\",\"value\":10.0}"
    
  • 通过WeEvent订阅事件

    WeEvent上订阅该主题com.weevent.iot.event,就可以得到IoT设备发送上来的数据。

  • 移除绑定,WeEvent不会再收到事件通知

    $ curl http://localhost:8080/weevent/master/mqtt_remove_inbound_topic?topic=com.weevent.iot.event
    

下发IoT设备命令

  • WeEvent里创建主题Topic ,例如com.weevent.iot.control

    $ curl http://localhost:8080/weevent/rest/open?topic=com.weevent.iot.control
    true
    
  • 通过WeEvent设置下行通道的Topic绑定

    $ curl http://localhost:8080/weevent/master/mqtt_add_outbound_topic?topic=com.weevent.iot.control
    true
    
  • WeEvent上发布事件

    $ curl http://localhost:8080/weevent/rest/publish?topic=com.weevent.iot.control&content=hello
    
  • 在设备上可以订阅到这个事件

    $ mosquitto_sub -h localhost -p 1883 -u ${user} -P ${password} -t "com.weevent.iot.control"
    
  • 移除绑定,IoT设备不会再收到事件通知

    $ curl http://localhost:8080/weevent/master/mqtt_add_inbound_topic?topic=com.weevent.iot.control