Neptune开发板 使用libemqtt 点亮LED和关闭LED 原创

远道可思
发布于 2021-5-7 18:27
浏览
2收藏

通过对Neptune开发板 W800 SDK 内置libemqtt的学习和W800 mqtt示例代码分析

通过对W800 mqtt示例代码稍加增加完成了对LED灯的开关

主要增加

            if(strcmp(msg,on)==0){
                GpioSetOutputVal(WIFI_IOT_GPIO_PB_08, WIFI_IOT_GPIO_VALUE0);//打开LED8灯
            }
            else if(strcmp(msg,off)==0){
                GpioSetOutputVal(WIFI_IOT_GPIO_PB_08, WIFI_IOT_GPIO_VALUE1);//关闭LED8灯
            }

代码如下:(MQTT服务器-然也物联测试服务器)

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#include "wifi_connecter.h"

#include "lwip/inet.h"
#include "wm_sockets2.0.3.h"

#include <libemqtt.h>
#include "wifiiot_gpio.h"
#include "wifiiot_gpio_ex.h"
#include "wifiiot_gpio_w800.h"
#define MQTT_DEMO_RECV_BUF_LEN_MAX      1024

#define MQTT_DEMO_CMD_START             0x1
#define MQTT_DEMO_CMD_HEART             0x2
#define MQTT_DEMO_CMD_LOOP              0x3
#define MQTT_DEMO_READ_TIMEOUT        (-1000)

#define MQTT_DEMO_READ_TIME_SEC         1
#define MQTT_DEMO_READ_TIME_US          0

#define MQTT_DEMO_CLIENT_ID            "wm_mqtt_client"            //ID
#define MQTT_DEMO_TX_PUB_TOPIC         "test2020"                  //订阅主题
#define MQTT_DEMO_RX_PUB_TOPIC         "test2049"                  //发布主题

#define MQTT_DEMO_SERVER_ADDR          "test.ranye-iot.net"         //IP地址 //http://www.ranye-iot.net/iot-platform.html 测试服务器
#define MQTT_DEMO_SERVER_PORT           1883                        //端口

static uint8_t pcaket_buffer[MQTT_DEMO_RECV_BUF_LEN_MAX];
static int socket_id;
static int mqtt_keepalive = 300;
static mqtt_broker_handle_t mqtt_broker;

static int mqtt_demo_close_socket(mqtt_broker_handle_t *broker)
{
    int fd = broker->socketid;
    return closesocket(fd);
}

static int mqtt_demo_send_packet(int socket_info, const void *buf, unsigned int count)
{
    int fd = socket_info;
    return send(fd, buf, count, 0);
}

static int mqtt_demo_read_packet(int sec, int us)
{
    int ret = 0;

    if ((sec >= 0) || (us >= 0))
    {
        fd_set readfds;
        struct timeval tmv;

        // 初始化文件描述符集
        FD_ZERO (&readfds);
        FD_SET (socket_id, &readfds);

        // 初始化超时数据结构
        tmv.tv_sec = sec;
        tmv.tv_usec = us;

        // 如果超时,1如果输入可用,则选择返回0,如果错误,则为1
        ret = select(socket_id + 1, &readfds, NULL, NULL, &tmv);
        if(ret < 0)
            return -2;
        else if(ret == 0)
            return MQTT_DEMO_READ_TIMEOUT;

    }

    int total_bytes = 0, bytes_rcvd, packet_length;
    memset(pcaket_buffer, 0, sizeof(pcaket_buffer));

    if((bytes_rcvd = recv(socket_id, (pcaket_buffer + total_bytes), MQTT_DEMO_RECV_BUF_LEN_MAX, 0)) <= 0)
    {
        //printf("%d, %d\r\n", bytes_rcvd, socket_id);
        return -1;
    }
    //printf("recv [len=%d] : %s\n", bytes_rcvd, pcaket_buffer);
    total_bytes += bytes_rcvd; // 保持总字节的计数
    if (total_bytes < 2)
        return -1;

    // now we have the full fixed header in pcaket_buffer
    // parse it for remaining length and number of bytes
    uint16_t rem_len = mqtt_parse_rem_len(pcaket_buffer);
    uint8_t rem_len_bytes = mqtt_num_rem_len_bytes(pcaket_buffer);

    //packet_length = pcaket_buffer[1] + 2; // Remaining length + fixed header length
    // total packet length = remaining length + byte 1 of fixed header + remaning length part of fixed header
    packet_length = rem_len + rem_len_bytes + 1;

    while(total_bytes < packet_length) // 读数据包
    {
        if((bytes_rcvd = recv(socket_id, (pcaket_buffer + total_bytes), MQTT_DEMO_RECV_BUF_LEN_MAX, 0)) <= 0)
            return -1;
        total_bytes += bytes_rcvd; // 保持总字节的计数
    }

    return packet_length;
}

static int mqtt_demo_init_socket(mqtt_broker_handle_t *broker, const char *hostname, short port, int keepalive)
{
    int flag = 1;
    struct hostent *hp;

    // 创建套接字
    if((socket_id = socket(PF_INET, SOCK_STREAM, 0)) < 0)
        return -1;

    // 禁用Nagle算法
    if (setsockopt(socket_id, IPPROTO_TCP, 0x01, (char *)&flag, sizeof(flag)) < 0)
    {
        mqtt_demo_close_socket(&mqtt_broker);
        return -2;
    }

    // 查询主机IP启动
    hp = gethostbyname(hostname);
    if (hp == NULL )
    {
        mqtt_demo_close_socket(&mqtt_broker);
        return -2;
    }

    struct sockaddr_in socket_address;
    memset(&socket_address, 0, sizeof(struct sockaddr_in));
    socket_address.sin_family = AF_INET;
    socket_address.sin_port = htons(port);
    memcpy(&(socket_address.sin_addr), hp->h_addr, hp->h_length);

    // 连接套接字
    if((connect(socket_id, (struct sockaddr *)&socket_address, sizeof(socket_address))) < 0)
    {
        mqtt_demo_close_socket(&mqtt_broker);
        return -1;
    }

    // MQTT stuffs
    mqtt_set_alive(broker, mqtt_keepalive);
    broker->socketid = socket_id;
    broker->mqttsend = mqtt_demo_send_packet;
    //printf("socket id = %d\n", socket_id);
    return 0;
}


static int mqtt_demo_init(void)
{
    int packet_length, ret = 0;
    uint16_t msg_id, msg_id_rcv;

    printf("step1: init mqtt lib.\r\n");              //步骤1:MQTT初始化
    mqtt_init(&mqtt_broker, MQTT_DEMO_CLIENT_ID);

    printf("step2: establishing TCP connection.\r\n");//步骤2:建立TCP连接
    ret = mqtt_demo_init_socket(&mqtt_broker, MQTT_DEMO_SERVER_ADDR, MQTT_DEMO_SERVER_PORT, mqtt_keepalive);
    if(ret)
    {
        printf("init_socket ret=%d\n", ret);
        return -4;
    }

    printf("step3: establishing mqtt connection.\r\n");//步骤3:建立MQTT连接
    ret = mqtt_connect(&mqtt_broker);
    if(ret)
    {
        printf("mqtt_connect ret=%d\n", ret);
        return -5;
    }

    packet_length = mqtt_demo_read_packet(MQTT_DEMO_READ_TIME_SEC, MQTT_DEMO_READ_TIME_US);
    if(packet_length < 0)
    {
        printf("Error(%d) on read packet!\n", packet_length);
        mqtt_demo_close_socket(&mqtt_broker);
        return -1;
    }

    if(MQTTParseMessageType(pcaket_buffer) != MQTT_MSG_CONNACK||pcaket_buffer[3] != 0x00)
    {
        printf("CONNACK expected or failed!\n");
        mqtt_demo_close_socket(&mqtt_broker);
        return -2;
    }

    printf("step4: subscribe mqtt\r\n");                    //步骤4:订阅MQTT
    mqtt_subscribe(&mqtt_broker, MQTT_DEMO_TX_PUB_TOPIC, &msg_id);

    packet_length = mqtt_demo_read_packet(MQTT_DEMO_READ_TIME_SEC, MQTT_DEMO_READ_TIME_US);
    if(packet_length < 0)
    {
        printf("Error(%d) on read packet!\n", packet_length);
        mqtt_demo_close_socket(&mqtt_broker);
        return -1;
    }

    if(MQTTParseMessageType(pcaket_buffer) != MQTT_MSG_SUBACK)
    {
        printf("SUBACK expected!\n");
        mqtt_demo_close_socket(&mqtt_broker);
        return -2;
    }

    msg_id_rcv = mqtt_parse_msg_id(pcaket_buffer);
    if(msg_id != msg_id_rcv)
    {
        printf("%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
        mqtt_demo_close_socket(&mqtt_broker);
        return -3;
    }
    return 1;
}

static int mqtt_demo_loop(void)
{
    int packet_length = 0;
    int counter = 0;
    int ret;
    char* payload = "Hello HarmonyOS!";
    char* msg;
    char on[]="ON";
    char off[]="OFF";
    int payloadlen = strlen(payload);

    counter++;
    packet_length = mqtt_demo_read_packet(0, 1);
    if(packet_length > 0)
    {
        if (MQTTParseMessageType(pcaket_buffer) == MQTT_MSG_PUBLISH)
        {
            uint8_t topic[255];
            uint16_t len;
            len = mqtt_parse_pub_topic(pcaket_buffer, topic);
            topic[len] = '\0'; // for printf
            len = mqtt_parse_publish_msg(pcaket_buffer,&msg);
            msg[len] = '\0'; // for printf
            printf("recvd: %s >>> %s\n",topic,msg);
            if(strcmp(msg,on)==0){
                GpioSetOutputVal(WIFI_IOT_GPIO_PB_08, WIFI_IOT_GPIO_VALUE0);//打开LED8灯
            }
            else if(strcmp(msg,off)==0){
                GpioSetOutputVal(WIFI_IOT_GPIO_PB_08, WIFI_IOT_GPIO_VALUE1);//关闭LED8灯
            }
        }
      
    }
    ret=mqtt_publish(&mqtt_broker, (const char *)MQTT_DEMO_RX_PUB_TOPIC, (const char *)payload,payloadlen,0);//每一秒发布一次消息
    if(ret<=0)
    {
        printf("Publish Failed!\n");
    }
    osDelay(500);
}

void Mqtt_test(void){
    printf("[MQTT]Start MQTT\r\n");
    if(mqtt_demo_init()==1){
        while (1)
        {
            mqtt_demo_loop();
        }
    }
}

static void MQTT_DemoTask(void)
{
    WifiDeviceConfig config = {0};

	strcpy(config.ssid, PARAM_HOTSPOT_SSID);
    strcpy(config.preSharedKey, PARAM_HOTSPOT_PSK);
    config.securityType = PARAM_HOTSPOT_TYPE;
    int netId = ConnectToHotspot(&config);//连接WIFI
    int timeout = 10;
    while (timeout--) {
        printf("After %d seconds, I will start test!\r\n", timeout);
        osDelay(100);
    }
    osDelay(500);

    Mqtt_test();
}

static void MQTT_Demo(void)
{
    osThreadAttr_t attr;

    GpioInit();
    GpioSetDir(WIFI_IOT_GPIO_PB_08, WIFI_IOT_GPIO_DIR_OUTPUT);

    attr.name = "MQTT_DemoTask";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = osPriorityNormal;

    if (osThreadNew((osThreadFunc_t)MQTT_DemoTask, NULL, &attr) == NULL) {
        printf("[MQTT_Demo] Falied to create MQTT_DemoTask!\n");
    }
}
APP_FEATURE_INIT(MQTT_Demo);

BUILD.gn

static_library("mqtt_sample") {
    sources = [
        "mqtt_sample1.c",
    ]
    cflags = [ "-Wno-unused-variable" ]
    cflags += [ "-Wno-unused-but-set-variable" ]

    include_dirs = [
        "//utils/native/lite/include",
        "//kernel/liteos_m/components/cmsis/2.0",
        "//base/iot_hardware/interfaces/kits/wifiiot_lite",
        "//foundation/communication/interfaces/kits/wifi_lite/wifiservice",
    ]
    if (board_name == "w800" || board_name == "hi3861v100") {
        sources += ["wifi_connecter.c",]
    }

    if (board_name == "w800") {
        include_dirs += [
            "//vendor/winnermicro/w800/src/network/lwip2.0.3/include/",
            "//vendor/winnermicro/w800/src/app/mqtt",
            "//vendor/winnermicro/w800/include/arch/xt804/csi_core",
            "//vendor/winnermicro/w800/include/arch/xt804",
            "//vendor/winnermicro/w800/include/platform",
            "//vendor/winnermicro/w800/include/os",
            "//vendor/winnermicro/w800/include/net",
            "//vendor/winnermicro/w800/include/app",
            "//vendor/winnermicro/w800/include/wifi",
            "//vendor/winnermicro/w800/include",
        ]
    }
}

修改wifi_connecter.h

#define PARAM_HOTSPOT_SSID "XXXXXX"  // your AP SSID
#define PARAM_HOTSPOT_PSK  "XXXXXX"  // your AP PSK

效果如下:

程序中一秒发布一次:

Neptune开发板 使用libemqtt 点亮LED和关闭LED-鸿蒙开发者社区

订阅主题收到消息:

Neptune开发板 使用libemqtt 点亮LED和关闭LED-鸿蒙开发者社区

Neptune开发板 使用libemqtt 点亮LED和关闭LED-鸿蒙开发者社区

先这样吧!后续把上云搞出来..................................

 

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
mqtt_sample.rar 6.82K 72次下载
已于2021-5-7 18:27:39修改
2
收藏 2
回复
举报
2条回复
按时间正序
/
按时间倒序
红叶亦知秋
红叶亦知秋

感谢分享

回复
2021-5-8 09:43:33
wg_caddBjEB
wg_caddBjEB

楼主,最后一张图看不到呀

回复
2021-5-8 14:36:39
回复