使用案例
mqtt案例大约分为两类:
- 第一种是作为控制端,比如屏幕按下某个按钮,发送一条mqtt消息控制某个物联网设备;
- 第二种作为接收端,订阅消息,被动获取数据或动作,比如收到消息设置某个IO电平;
一、控制端,发送消息控制其他客户端
在页面中的
void app.onWIFI32(int m){
str s;
int msgnum;
msgnum=wifi_getinfo(2);
if (m==2){
//wifi_connect
mqtt_init(); //当wifi连接成功后,立即连接mqtt服务器
mqtt_setv(0,"mqtt://i.a-diy.cn");
mqtt_connect();
s=wifi_getinfo(1);
echo(s);
m1.text=s;
}
super.onWIFI32(m); //处理mqtt等业务
}
//wifi_connect(u,p); //合适的地方启动wifi_connect,在连接成功后直接连接mqtt服务器
在合适的地方,比如按钮的事件中,使用mqtt_pub发布一条消息
void x2.onclick()
{
mqtt_pub("hello",0,"helloworld"); //发布一条消息
}
二、接收端,订阅消息
- appbase全局控件代码
void onWIFI32(int m){
int msgnum;
str s;
msgnum=wifi_getinfo(2);
if (m==7){
//mqtt
if (msgnum==1){
//connect;
mqtt_sub("hello",0); //mqtt服务器连接成功后,立即订阅,进入消息接收状态
}
if (msgnum==6){
//收到消息
str topic;
str data;
int qos;
topic=wifi_getinfo(23);
data=wifi_getinfo(24);
qos=wifi_getinfo(4);
//---在此书写收到的mqtt消息处理
s="topic:"+topic+"\r\ndata:"+data+"\r\nqos:"+qos+"\r\n";
echo(s);
}
}
}
- 页面代码
void app.onWIFI32(int m){
str s;
int msgnum;
msgnum=wifi_getinfo(2);
if (m==2){
//wifi_connect
mqtt_init(); //当wifi连接成功后,立即连接mqtt服务器
mqtt_setv(0,"mqtt://i.a-diy.cn");
mqtt_connect();
}
super.onWIFI32(m); //处理mqtt等业务
}
//wifi_connect(u,p); //合适的地方启动wifi_connect,在连接成功后直接连接mqtt服务器
从上面的代码可以看到,页面代码先执行,连接wifi热点后,在onWIFI32中,连接wifi后立即连接mqtt服务器;
由于使用了super.onWIFI32(m);因此,在mqtt服务器连接成功之后,在appbase中的onWIFI32事件中,直接订阅了hello消息;
当收到订阅的消息后,在appbase中的onWIFI32事件中,可以直接处理消息;