/**
  * @brief  MQTT协议测试主循环
  * @retval None
  **/
void MQTT_Loop(void)
{
    static int timeout_count = 0;
    int publish_state = 0;
    int exit = 0;
    int j = 0;
    /*初始化MQTT上下文,在该api内部配置了设备ID等信息*/
    if(MqttSample_Init(smpctx) < 0)
    {
        return;
    }
    printf("\r\ndevice id:%s\r\n", MQTT_DEVICE_ID);
    printf("we publish topic:%s %s %s\r\n",DS_TO_PUBLISH,DS_TO_PUBLISH_T,DS_TO_PUBLISH_RH);
    printf("connect to mqtt server\r\n");
    /*发送MQTT连接请求报文*/
    MqttSample_CmdConnect(smpctx);
		printf("\r\n");
    mDelay(2000);
    Mqtt_RecvPkt(smpctx->mqttctx);
    mDelay(2000);
    /*发送MQTT订阅topic报文*/
    MqttSample_CmdSubscribe(smpctx);//开机订阅
		printf("\r\n");
    mDelay(2000);
    Mqtt_RecvPkt(smpctx->mqttctx);
    printf("begin loop\n");
    /*进入主循环*/
    while(!exit)
    {
        j++;
        if(j == 3)
        {
            //MqttSample_CmdPublish(smpctx,TIME_OUT);
            /*周期性发布温湿度和一个状态数据,状态每次取反*/
            publish_state = MqttSample_CmdPublishNormal(smpctx, TIME_OUT);
            if(publish_state < 0)
            {
                timeout_count++;
                if(timeout_count == 5)
                {
                    timeout_count = 0;
                    /*you can do some thing*/
                }
            }
            j = 0;
        }
        if(Mqtt_RecvPkt(smpctx->mqttctx)<0)
				{
					 smpctx->publish_state=0;
				}
				printf("\r\n");
        mDelay(100);
    }
    /*reclaim the resource防止内存泄露*/
    MqttBuffer_Destroy(smpctx->mqttbuf);
    Mqtt_DestroyContext(smpctx->mqttctx);
    printf("bye...\n");
    return;
}
Exemple #2
0
int main(int argc, char **argv)
{
    struct MqttSampleContext smpctx[1];
    int evt_cnt;
    const int evt_max_cnt = 2;
    struct epoll_event events[evt_max_cnt];
    int exit;


    if(MqttSample_Init(smpctx) < 0) {
        return -1;
    }

    (void)MqttSample_CmdHelp(smpctx);

    exit = 0;
    while(!exit && (evt_cnt = epoll_wait(smpctx->epfd, events, evt_max_cnt, -1)) >= 0) {
        int i;
        for(i = 0; i < evt_cnt; ++i) {
            if(STDIN_FILENO == events[i].data.fd) {
                if(MqttSample_HandleStdin(smpctx, events[i].events) < 0) {
                    exit = 1;
                    break;
                }
                events[i].events = EPOLLIN | EPOLLET | EPOLLONESHOT;
                epoll_ctl(smpctx->epfd, EPOLL_CTL_MOD, events[i].data.fd, events + i);
            }
            else {
                if(MqttSample_HandleSocket(smpctx, events[i].events) < 0) {
                    exit = 1;
                    break;
                }
            }
        }
    }

    // reclaim the resource
    MqttBuffer_Destroy(smpctx->mqttbuf);
    Mqtt_DestroyContext(smpctx->mqttctx);

    if(smpctx->epfd >= 0) {
        close(smpctx->epfd);
        smpctx->epfd = -1;
    }

    if(smpctx->mqttfd >= 0) {
        close(smpctx->mqttfd);
        smpctx->mqttfd = -1;
    }

    printf("bye...\n");

    return 0;
}