MQTT(MQ Telemetry Transport)是一种消息传递协议,创建该协议是为了满足对向低功耗设备(如工业应用中使用的设备)传输数据的简单而轻量级方法的需求。
随着物联网(IoT)设备的日益普及,MQTT的使用也在增加,导致其被OASIS和ISO标准化。
该协议支持单一的消息传递模式,即发布-订阅模式:客户端发送的每条消息都包含一个相关的“主题”,代理使用该主题将其路由到订阅的客户端。主题名称可以是像“oiltemp”这样的简单字符串,也可以是像字符串“motor/1/rpm”这样的路径。

为了接收消息,客户端使用一个或多个主题的确切名称或包含支持的通配符之一的字符串(“#”表示多级主题,“+”表示单层主题)订阅一个或更多个主题。

安装mosquitto:

安装完成, 检查服务:
2修改文件: mosquitto.conf 追加2如下2行:
listener 1883 127.0.0.1
allow_anonymous true

在最下方(可以在任意位置修改),主要要修改三个值第一个是listener:该值的格式为 端口号/ip地址(mqtt默认的端口号是1883)我就写1883了,那我的listener就是1883/192.168.1.106 第二个allow_anonymous该值是是否允许匿名登入我这边写的是false就是不允许匿名登入,填入true就是允许匿名登入;第三个是password_file该值的意思是用户信息的位置,我的位置就是在该目录下所以我的写入的值就是E:\mqtt\mosquitto\pwfile.example
原文链接:https://blog.youkuaiyun.com/wh_xia_jun/article/details/140217724
3、部署完后重启下mqtt服务,win+r后输入services.msc找到Mosquitto Broker点击重启动即可。
启动mqtt 服务
在最下方(可以在任意位置修改),主要要修改三个值第一个是listener:该值的格式为 端口号/ip地址(mqtt默认的端口号是1883)我就写1883了,那我的listener就是1883/192.168.1.106 第二个allow_anonymous该值是是否允许匿名登入我这边写的是false就是不允许匿名登入,填入true就是允许匿名登入;第三个是password_file该值的意思是用户信息的位置,我的位置就是在该目录下所以我的写入的值就是E:\mqtt\mosquitto\pwfile.example
4.部署完后重启下mqtt服务,win+r后输入services.msc找到Mosquitto Broker点击重启动即可。
三.增加用户信息
1.在mosquitto目录下的上方输入cmd按下回车

2. mosquitto_passwd -c pwfile.example 用户名:该命令相当于清楚所有的用户然后添加该用户mosquitto_passwd pwfile.example 用户名:该命令就是直接追加用户了那我这边就直接追加一个用户

用户名是user4,密码是1234。注意:密码不显示的,直接输入即可
我直接一共就有了4个用户user1、user2、user3、user4密码均是1234
四.部署mqttx
1.点击左边的加号


Name、Client ID随便填、Host的后面写入内网ip地址,也可就写入本机地址127.0.0.1,Username和Password要填入正确的,我这边填入的就是user1connect就行了。
openharmony 操作步骤:
1 找到产品给的代码
【2】课程文档配套例程\mqtt_test
在app 下面 创建 \mqtt_test 文件夹
把厂家的代码 copy 到这个目录下:
mqtt_entry.c :
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include <unistd.h>
#include "hi_wifi_api.h"
//#include "wifi_sta.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#define APP_INIT_VAP_NUM 2
#define APP_INIT_USR_NUM 2
int wifi_ok_flg = 0;
static struct netif *g_lwip_netif = NULL;
/* clear netif's ip, gateway and netmask */
void hi_sta_reset_addr(struct netif *pst_lwip_netif)
{
ip4_addr_t st_gw;
ip4_addr_t st_ipaddr;
ip4_addr_t st_netmask;
if (pst_lwip_netif == NULL) {
printf("hisi_reset_addr::Null param of netdev\r\n");
return;
}
IP4_ADDR(&st_gw, 0, 0, 0, 0);
IP4_ADDR(&st_ipaddr, 0, 0, 0, 0);
IP4_ADDR(&st_netmask, 0, 0, 0, 0);
netifapi_netif_set_addr(pst_lwip_netif, &st_ipaddr, &st_netmask, &st_gw);
}
void wifi_wpa_event_cb(const hi_wifi_event *hisi_event)
{
if (hisi_event == NULL)
return;
switch (hisi_event->event) {
case HI_WIFI_EVT_SCAN_DONE:
printf("WiFi: hi,Scan results available\n");
break;
case HI_WIFI_EVT_CONNECTED:
printf("WiFi: Connected\n");
netifapi_dhcp_start(g_lwip_netif);
wifi_ok_flg = 1;
osDelay(500); // 单位:ms(200 = 2秒,LiteOS-M 的 osDelay 单位是 10ms 时基)
if (g_lwip_netif != NULL && g_lwip_netif->ip_addr.u_addr.ip4.addr !=0) {
printf("STA IP: %s\n", ip4addr_ntoa(&g_lwip_netif->ip_addr)); // 局域网 IP(如 192.168.1.100)
printf("STA Gateway: %s\n", ip4addr_ntoa(&g_lwip_netif->gw)); // 网关(通常是路由器 IP)
printf("STA Netmask: %s\n", ip4addr_ntoa(&g_lwip_netif->netmask)); // 子网掩码
} else {
printf("WiFi: DHCP failed, no IP obtained\n");
}
break;
case HI_WIFI_EVT_DISCONNECTED:
printf("WiFi: Disconnected\n");
netifapi_dhcp_stop(g_lwip_netif);
hi_sta_reset_addr(g_lwip_netif);
break;
case HI_WIFI_EVT_WPS_TIMEOUT:
printf("WiFi: wps is timeout\n");
break;
default:
break;
}
}
int hi_wifi_start_connect(void)
{
int ret;
errno_t rc;
hi_wifi_assoc_request assoc_req = {0};
/* copy SSID to assoc_req */
rc = memcpy_s(assoc_req.ssid, HI_WIFI_MAX_SSID_LEN + 1, "x", 8); /* 9:ssid length */
if (rc != EOK) {
return -1;
}
//热点加密方式
assoc_req.auth = HI_WIFI_SECURITY_WPA2PSK;
/* 热点密码 */
memcpy(assoc_req.key, "12345678", 11);
ret = hi_wifi_sta_connect(&assoc_req);
if (ret != HISI_OK) {
return -1;
}
return 0;
}
int hi_wifi_start_sta(void)
{
int ret;
char ifname[WIFI_IFNAME_MAX_SIZE + 1] = {0};
int len = sizeof(ifname);
const unsigned char wifi_vap_res_num = APP_INIT_VAP_NUM;
const unsigned char wifi_user_res_num = APP_INIT_USR_NUM;
unsigned int num = WIFI_SCAN_AP_LIMIT;
//这里不需要重复进行WiFi init,因为系统启动后就自己会做WiFi init
#if 0
printf("_______>>>>>>>>>> %s %d \r\n", __FILE__, __LINE__);
ret = hi_wifi_init(wifi_vap_res_num, wifi_user_res_num);
if (ret != HISI_OK) {
return -1;
}
#endif
ret = hi_wifi_sta_start(ifname, &len);
if (ret != HISI_OK) {
return -1;
}
/* register call back function to receive wifi event, etc scan results event,
* connected event, disconnected event.
*/
ret = hi_wifi_register_event_callback(wifi_wpa_event_cb);
if (ret != HISI_OK) {
printf("register wifi event callback failed\n");
}
/* acquire netif for IP operation */
g_lwip_netif = netifapi_netif_find(ifname);
if (g_lwip_netif == NULL) {
printf("%s: get netif failed\n", __FUNCTION__);
return -1;
}
/* 开始扫描附件的WiFi热点 */
ret = hi_wifi_sta_scan();
if (ret != HISI_OK) {
return -1;
}
sleep(5); /* sleep 5s, waiting for scan result. */
hi_wifi_ap_info *pst_results = malloc(sizeof(hi_wifi_ap_info) * WIFI_SCAN_AP_LIMIT);
if (pst_results == NULL) {
return -1;
}
//把扫描到的热点结果存储起来
ret = hi_wifi_sta_scan_results(pst_results, &num);
if (ret != HISI_OK) {
free(pst_results);
return -1;
}
//打印扫描到的所有热点
for (unsigned int loop = 0; (loop < num) && (loop < WIFI_SCAN_AP_LIMIT); loop++) {
printf("SSID: %s\n", pst_results[loop].ssid);
}
free(pst_results);
/* 开始接入热点 */
ret = hi_wifi_start_connect();
if (ret != 0) {
return -1;
}
return 0;
}
void wifi_sta_task(void *arg)
{
arg = arg;
//连接热点
hi_wifi_start_sta();
while(wifi_ok_flg == 0)
{
usleep(30000);
}
usleep(2000000);
//开始进入MQTT测试
mqtt_test();
}
void wifi_sta_entry(void)
{
osThreadAttr_t attr;
attr.name = "wifi_sta_demo";
attr.attr_bits = 0U;
attr.cb_mem = NULL;
attr.cb_size = 0U;
attr.stack_mem = NULL;
attr.stack_size = 4096;
attr.priority = 26;
if (osThreadNew((osThreadFunc_t)wifi_sta_task, NULL, &attr) == NULL) {
printf("[wifi_sta_demo] Falied to create wifi_sta_demo!\n");
}
}
SYS_RUN(wifi_sta_entry);
mqtt_test.c:
#include <stdio.h>
#include <unistd.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "hi_wifi_api.h"
#include "lwip/ip_addr.h"
#include "lwip/netifapi.h"
#include "lwip/sockets.h"
#include "MQTTClient.h"
static MQTTClient mq_client;
unsigned char *onenet_mqtt_buf;
unsigned char *onenet_mqtt_readbuf;
int buf_size;
Network n;
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
//消息回调函数
void mqtt_callback(MessageData *msg_data)
{
size_t res_len = 0;
uint8_t *response_buf = NULL;
char topicname[45] = { "$crsp/" };
LOS_ASSERT(msg_data);
printf("topic %.*s receive a message\r\n", msg_data->topicName->lenstring.len, msg_data->topicName->lenstring.data);
printf("message is %.*s\r\n", msg_data->message->payloadlen, msg_data->message->payload);
}
int mqtt_connect(void)
{
int rc = 0;
NetworkInit(&n);
NetworkConnect(&n, "192.168.165.195", 1883);
buf_size = 4096+1024;
onenet_mqtt_buf = (unsigned char *) malloc(buf_size);
onenet_mqtt_readbuf = (unsigned char *) malloc(buf_size);
if (!(onenet_mqtt_buf && onenet_mqtt_readbuf))
{
printf("No memory for MQTT client buffer!");
return -2;
}
MQTTClientInit(&mq_client, &n, 1000, onenet_mqtt_buf, buf_size, onenet_mqtt_readbuf, buf_size);
MQTTStartTask(&mq_client);
data.keepAliveInterval = 30;
data.cleansession = 1;
data.clientID.cstring = "ohos_hi3861";
data.username.cstring = "user4";
data.password.cstring = "1234";
data.cleansession = 1;
mq_client.defaultMessageHandler = mqtt_callback;
//连接服务器
rc = MQTTConnect(&mq_client, &data);
//订阅消息,并设置回调函数
//MQTTSubscribe(&mq_client, "ohossub", 0, mqtt_callback);
// 订阅消息,并设置回调函数
int sub_rc = MQTTSubscribe(&mq_client, "ohossub", 0, mqtt_callback);
if (sub_rc != 0) {
printf("Subscription failed! Error code: %d\r\n", sub_rc);
} else {
printf("Subscription topic 'ohossub' success\r\n");
}
while(1)
{
MQTTMessage message;
message.qos = QOS1;
message.retained = 0;
message.payload = (void *)"openharmony";
message.payloadlen = strlen("openharmony");
//发送消息
if (MQTTPublish(&mq_client, "ohospub", &message) < 0)
{
printf("MQTTPublish faild !\r\n");
}
usleep(1000000);
}
return 0;
}
void mqtt_test(void)
{
mqtt_connect();
}
mqtt_test.h:
/*
* Copyright (c) 2020 HiSilicon (Shanghai) Technologies CO., LIMITED.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __MQTT_TEST_H__
#define __MQTT_TEST_H__
void mqtt_test(void);
#endif /* __MQTT_TEST_H__ */
BUILD.gn
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
static_library("mqtt_test") {
sources = [
"mqtt_test.c",
"mqtt_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/MQTTClient-C/src",
"//third_party/pahomqtt/MQTTClient-C/src/liteOS",
]
#表示需要a_myparty 软件包
deps = [
"//third_party/pahomqtt:pahomqtt_static",
]
}

2549

被折叠的 条评论
为什么被折叠?



