MQTT


概述

演示MQTT的基本用法。


代码


var pkt_id = 1;
function handleMQTTData(data)
{
    //print(JSON.stringify(data));
    switch(data.type)
    {
        case Packet.MQTT.CONNACK:
            Net.send(1, Packet.MQTT.subscribe(pkt_id, "test", 1));
            pkt_id++;
            break;
        case Packet.MQTT.PUBLISH:
            if(data.qos == 1)
                Net.send(1, Packet.MQTT.puback(data.id));
            break;
    }
}
var mqtt = Packet.MQTT.Parser.create(handleMQTTData);
function handleNetEvent(m)
{
    switch(m.event)
    {
        case Net.READY:
            print("csq:", Net.csq());
            print("syncTime:", Net.syncTime());
            var t = Box.getTime();
            print(t.year, t.month, t.day,t.hour, t.minute, t.second);
            Net.connect(1, "xianhe.tpddns.cn", 1883);
            break;
        case Net.CONN_OK:
            Net.send(1, Packet.MQTT.connect("easelive", 60, 1));
            Timer.start(1, 20000);
            Timer.start(2, 9000);
            Timer.start(3, 30000);
            Timer.start(4, 50000);
            break;
        case Net.CONN_FAIL:
            print("connect failed");
            break;
        case Net.CONN_CLOSE:
            print("connect closed");
            Timer.stop(1);
            Timer.stop(2);
            break;
        case Net.RECV:
            print(m.data.hex());
            mqtt.parse(m.data);
            break;
    }
}
function handleTimerOut(id)
{
    switch(id)
    {
        case 1: //send heartbeat packet
            Net.send(1, Packet.MQTT.ping());
            Timer.start(1, 30000);
            break;
        case 2: //send publish packet
            Net.send(1, Packet.MQTT.publish("test", Bytes.create("abcdefg"), 1, pkt_id));
            pkt_id++;
            Timer.start(2, 11000);
            break;
        case 3: //send unsubscribe packet
            Net.send(1, Packet.MQTT.unsubscribe(pkt_id, "test"));
            pkt_id++;
            break;
        case 4: //send disconnect packet
            Net.send(1, Packet.MQTT.disconnect());
            break;
    }
}

GPIO.set(GPIO.POWER, 1)
Net.init()
while(true)
{
    var m = Event.get();
    switch(m.msg)
    {
        case Event.NET_EVENT:
            handleNetEvent(m);
            break;
        case Event.TIMER_OUT:
            handleTimerOut(m.id);
            break;
    }
}