数据传输模块-DTU


概述

用于上报的实际案例,串口1收到数据后发往服务器;收到服务器上的数据发往串口1;往服务器发送有缓冲队列,可避免数据丢失的情况;联上网络后发启动包;每分钟发一个心跳包。


代码


var server = "xianhe.tpddns.cn";
var port = 10808;
var issending = false;
var sendbuf = [];

function send_boot()
{
    Net.send(1, "boot");
}

function send_heartbeat()
{
    if(!issending)
        Net.send(1, "heartbeat");
}

function send_data(data)
{
    sendbuf[sendbuf.length] = data;
    if(!issending)
    {
        Timer.stop(1);
        issending = true;
        Net.send(1, sendbuf[0]);
    }
}

function handleNetEvent(m)
{
    switch(m.event)
    {
        case Net.READY:
            Net.connect(1, server, port);
            break;
        case Net.CONN_OK:
            send_boot();
            if(sendbuf.length > 0)
                Timer.start(2, 2000);
            else
                Timer.start(1, 60000);
            break;
        case Net.CONN_FAIL:
            Net.connect(1, server, port);
            break;
        case Net.CONN_CLOSE:
            Net.connect(1, server, port);
            break;
        case Net.RECV:
            UART.send(1, m.data);
            break;
        case Net.SEND_OK:
            if(issending)
            {
                issending = false;
                sendbuf.splice(0, 1);
            }
            if(sendbuf.length > 0)
                Timer.start(2, 500);
            else
                Timer.start(1, 60000);
            break;
        case Net.SEND_FAIL:
            if(issending)
                Net.send(1, sendbuf[0]);
            else
                Timer.start(1, 60000);
            break;
    }
}

function handleTimerOut(id)
{
    switch(id)
    {
        case 1: //send heartbeat packet
        send_heartbeat();
        break;
        case 2: //send data from uart
        issending = true;
        Net.send(1, sendbuf[0]);
    }
}

GPIO.set(GPIO.POWER, 1);
//uart.init(1,115200)
Net.init();

while(true)
{
    var m = Event.get();
    switch(m.msg)
    {
        case Event.NET_EVENT:
            handleNetEvent(m);
            break;
        case Event.UART_RECV:
            if(m.port == 1)
                send_data(m.data);
            break;
        case Event.TIMER_OUT:
            handleTimerOut(m.id);
            break;
    }
}