鸿蒙之连接MQTT

鸿蒙之连接MQTT

  • 移植MQTT
  • 修改文件
  • 编写测试代码
  • 运行
  • 后续

移植MQTT

鸿蒙系统中通过移植第3方软件包 paho mqtt去实现MQTT协议功能
首先下载MQTT移植文件

https://download.csdn.net/download/qq_44629109/79195528

我们在鸿蒙系统源码的 third_party 文件夹下创建一个 pahomqtt 文件夹,然后把解压后的所有文件都拷贝到 pahomqtt 文件夹下
下一步,我们在pahomqtt 文件夹下面新建BUILD.gn文件,用来构建编译。其内容如下

import("//build/lite/config/component/lite_component.gni")
import("//build/lite/ndk/ndk.gni")

config("pahomqtt_config") {
    include_dirs = [
        "MQTTPacket/src",
        "MQTTClient-C/src",
        "MQTTClient-C/src/liteOS",
        "//kernel/liteos_m/components/cmsis/2.0",
    ]
}

pahomqtt_sources = [
"MQTTClient-C/src/liteOS/MQTTLiteOS.c",
"MQTTClient-C/src/MQTTClient.c",

"MQTTPacket/src/MQTTConnectClient.c",
"MQTTPacket/src/MQTTConnectServer.c",
"MQTTPacket/src/MQTTDeserializePublish.c",
"MQTTPacket/src/MQTTFormat.c",
"MQTTPacket/src/MQTTPacket.c",
"MQTTPacket/src/MQTTSerializePublish.c",
"MQTTPacket/src/MQTTSubscribeClient.c",
"MQTTPacket/src/MQTTSubscribeServer.c",
"MQTTPacket/src/MQTTUnsubscribeClient.c",
"MQTTPacket/src/MQTTUnsubscribeServer.c",
]

lite_library("pahomqtt_static") {
    target_type = "static_library"
    sources = pahomqtt_sources
    public_configs = [ ":pahomqtt_config" ]
}

lite_library("pahomqtt_shared") {
    target_type = "shared_library"
    sources = pahomqtt_sources
    public_configs = [ ":pahomqtt_config" ]
}

ndk_lib("pahomqtt_ndk") {
    if (board_name != "hi3861v100") {
        lib_extension = ".so"
        deps = [
            ":pahomqtt_shared"
        ]
    } else {
        deps = [
            ":pahomqtt_static"
        ]
    }
    head_files = [
        "//third_party/pahomqtt"
    ]
}

打开vendor\hisi\hi3861\hi3861\BUILD.gn 文件,
在lite_component(“sdk”) 中增加
“//third_party/pahomqtt:pahomqtt_static”
鸿蒙之连接MQTT_第1张图片

修改文件

打开 third_party\pahomqtt\MQTTPacket\samples\transport.c 文件,这个文件也是我们主要移植的文件,我们需要实现 socket相关的操作,包括发送、接收数据。其实移植就3步。

(1)在transport.c导入三个头文件

#include "lwip/ip_addr.h"
#include "lwip/sockets.h"
#include "lwip/netifapi.h"

(2)修改 transport_sendPacketBuffer 函数:

int transport_sendPacketBuffer(int sock, unsigned char* buf, int buflen)
{
	int rc = 0;
	rc = send(sock, buf, buflen, 0);
	return rc;
}

(3)修改 transport_close 函数:

int transport_close(int sock)
{
int rc;
	rc = shutdown(sock, SHUT_WR);
	rc = recv(sock, NULL, (size_t)0, 0);
	rc = lwip_close(sock);
 return rc;
 }

编写测试代码

在./applications/sample/wifi-iot/app路径下新建一个目录(或一套目录结构),用于存放业务源码文件。
其中有四个文件:

  1. BUILD.gn
static_library("mqtt_test_at") {
    sources = [
        "mqtt_test.c",
        "at_entry.c"
    ]
 
    include_dirs = [
        "//utils/native/lite/include",
        "//kernel/liteos_m/components/cmsis/2.0",
        "//base/iot_hardware/interfaces/kits/wifiiot_lite",
        "//vendor/hisi/hi3861/hi3861/third_party/lwip_sack/include",
        "//foundation/communication/interfaces/kits/wifi_lite/wifiservice",
        "//third_party/pahomqtt/MQTTPacket/src",
        "//third_party/pahomqtt/MQTTPacket/samples",
        "//vendor\hisi\hi3861\hi3861\components\at\src"
    ]
}
  1. at_entry.c
#include 
#include 
#include "ohos_init.h"
#include "cmsis_os2.h"
#include 
#include 
#include 
#include "hi_wifi_api.h"
#include "mqtt_test.h"
void mqtt_test_thread(void * argv)
{
    argv = argv;
    mqtt_test();
}
hi_u32 at_exe_mqtt_test_cmd(void)
{
    osThreadAttr_t attr;
    attr.name = "wifi_config_thread";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 4096;
    attr.priority = 36;

    if (osThreadNew((osThreadFunc_t)mqtt_test_thread, NULL, &attr) == NULL) {
        printf("[LedExample] Falied to create LedTask!\n");
    }
    AT_RESPONSE_OK;
    return HI_ERR_SUCCESS;
}
const at_cmd_func g_at_mqtt_func_tbl[] = {
    {"+MQTTTEST", 9, HI_NULL, HI_NULL, HI_NULL, (at_call_back_func)at_exe_mqtt_test_cmd},
};
void AtExampleEntry(void)
{
    hi_at_register_cmd(g_at_mqtt_func_tbl, sizeof(g_at_mqtt_func_tbl)/sizeof(g_at_mqtt_func_tbl[0]));
}
SYS_RUN(AtExampleEntry);
  1. mqtt_test.c
#include 

#include 

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

#include 
#include "hi_wifi_api.h"
//#include "wifi_sta.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"

#include "lwip/sockets.h"

#include "MQTTPacket.h"
#include "transport.h"

int toStop = 0;

int mqtt_connect(void)
{
	MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
	int rc = 0;
	int mysock = 0;
	unsigned char buf[200];
	int buflen = sizeof(buf);
	int msgid = 1;
	MQTTString topicString = MQTTString_initializer;
	int req_qos = 0;
	char* payload = "hello HarmonyOS";
	int payloadlen = strlen(payload);
	int len = 0;
	char *host = "MQTT服务器的ip地址";
	int port = 1883;


	mysock = transport_open(host, port);
	if(mysock < 0)
		return mysock;

	printf("Sending to hostname %s port %d\n", host, port);

	data.clientID.cstring = "me";
	data.keepAliveInterval = 20;
	data.cleansession = 1;
	data.username.cstring = "testuser";
	data.password.cstring = "testpassword";

	len = MQTTSerialize_connect(buf, buflen, &data);
	rc = transport_sendPacketBuffer(mysock, buf, len);

	/* wait for connack */
	if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK)
	{
		unsigned char sessionPresent, connack_rc;

		if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0)
		{
			printf("Unable to connect, return code %d\n", connack_rc);
			goto exit;
		}
	}
	else
		goto exit;

	/* subscribe */
	topicString.cstring = "substopic";
	len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos);
	rc = transport_sendPacketBuffer(mysock, buf, len);
	if (MQTTPacket_read(buf, buflen, transport_getdata) == SUBACK) 	/* wait for suback */
	{
		unsigned short submsgid;
		int subcount;
		int granted_qos;

		rc = MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen);
		if (granted_qos != 0)
		{
			printf("granted qos != 0, %d\n", granted_qos);
			goto exit;
		}
	}
	else
		goto exit;

	/* loop getting msgs on subscribed topic */
	topicString.cstring = "pubtopic";
	while (!toStop)
	{
		/* transport_getdata() has a built-in 1 second timeout,
		your mileage will vary */
		if (MQTTPacket_read(buf, buflen, transport_getdata) == PUBLISH)
		{
			unsigned char dup;
			int qos;
			unsigned char retained;
			unsigned short msgid;
			int payloadlen_in;
			unsigned char* payload_in;
			int rc;
			MQTTString receivedTopic;
			rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
					&payload_in, &payloadlen_in, buf, buflen);
			printf("message arrived %.*s\n", payloadlen_in, payload_in);

            rc = rc;
        }

		printf("publishing reading\n");
		len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen);
        rc = transport_sendPacketBuffer(mysock, buf, len);
	}

	printf("disconnecting\n");
	len = MQTTSerialize_disconnect(buf, buflen);
	rc = transport_sendPacketBuffer(mysock, buf, len);
exit:
	transport_close(mysock);

    rc = rc;

	return 0;
}


void mqtt_test(void)
{
    mqtt_connect();
}
  1. mqtt_test.h
#ifndef __MQTT_TEST_H__
#define __MQTT_TEST_H__
void mqtt_test(void);
#endif /* __MQTT_TEST_H__ */

烧录进开发板

运行

首先打开MQTT服务器,方法可查看https://blog.csdn.net/qq_44629109/article/details/122779727?spm=1001.2014.3001.5501 ,这篇文章
首先通过AT指令进行联网。
在串口调试助手发送”AT+STARTSTA“, 启动STA模式。
发送” AT+CONN=“BAHUYANG”,2,“123456789” “ 连接指定AP,其中SSID/PASSWORD为待连接的热点名称和密码。
发送”AT+STASTAT” ,查看连接结果。
然后我们输入我们的 MQTT测试的AT指令: AT+MQTTTEST
可以从串口调试助手上看到如下图。
鸿蒙之连接MQTT_第2张图片
然后查看MQTT客户端软件,可以看到右边已经有接收MQTT信息了,主题是 pubtopic,消息内容为 hello HarmonyOS ! ,说明实验成功。
鸿蒙之连接MQTT_第3张图片

后续

可以关注我的程序设计专栏。
关注微信公众号
在这里插入图片描述

编写不易,感谢支持。

你可能感兴趣的:(鸿蒙,harmonyos,物联网,华为)