首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

ESP32移植Openharmony物联网实战 - LwIP+巴法云TCP服务器

  • 25-03-08 00:01
  • 2089
  • 10606
blog.csdn.net

目录

巴法云平台域名

巴法云平台搭建

TCP简介

订阅、发布简介

代码示例

wifi_sta_connect.c

wifi_sta_example.c

移植步骤

巴法云TCP客户端接入详解

命令字段说明

订阅主题

发布

订阅主题,并获取一条历史消息

获取一次时间

获取一次已发消息

发送心跳

set 指令

up 指令

app 指令

编译并烧录

实验现象


巴法云云平台官网

巴法开放平台_巴法云_巴法物联网云平台

巴法云云平台搭建

  1. 进入巴法云平台登录注册
  2. 点击TCP设备云

  1. 在最右边输入框中输入主题名,主题命名并无强制性要求,也可以参考主题类型命名说明:

比如我们这里将主题命名为ledtest,点击新建主题

创建成功后可以看到下面出现了一个主题

TCP简介

TCP 是一种面向连接的、可靠的、基于字节流的传输层通信协议,传输层协议常用的有TCP和UDP,像常见的http协议或mqtt协议,都是在TCP上传输的,TCP用途广泛,一般可以联网的设备,都支持TCP协议传输。

订阅、发布简介

通俗的来讲,订阅、发布是两种不同的信号
订阅:订阅某一个主题,订阅之后,就可以收到发往该主题的消息。
发布:向某个主题发送消息。
例如:当某个设备订阅了主题“X”,这时向主题“X”发送的任何消息,设备都可以收到,因为设备已经订阅上了该主题。

直接上干货!

代码示例

wifi_sta_connect.c
  1. /*
  2. * Copyright (c) 2022 Hunan OpenValley Digital Industry Development Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. #include "securec.h"
  19. #include "cmsis_os2.h"
  20. #include "ohos_init.h"
  21. #include "wifi_device.h"
  22. #include "lwip/ip4_addr.h"
  23. #include "lwip/netif.h"
  24. #include "lwip/netifapi.h"
  25. #include "wifi_error_code.h"
  26. #define DEF_TIMEOUT 15
  27. #define ONE_SECOND 1
  28. #define SELECT_WLAN_PORT "wlan0"
  29. #define SELECT_WIFI_SECURITYTYPE WIFI_SEC_TYPE_OPEN
  30. #define STD_TIMEZONE_OFFSET (+8)
  31. #define OD_DELAY_100 100
  32. #define OD_DELAY_200 200
  33. static int g_staScanSuccess = 0;
  34. static int g_ConnectSuccess = 0;
  35. static int ssid_count = 0;
  36. static WifiErrorCode wifi_error;
  37. static WifiEvent g_wifiEventHandler = {0};
  38. static int wifi_sta_init_state = 0;
  39. int sock_fd;
  40. int addr_length;
  41. const int timeZone = 8;
  42. static void WiFiInit(void);
  43. static void WaitScanResult(void);
  44. static int WaitConnectResult(void);
  45. static void OnWifiScanStateChangedHandler(int state, int size);
  46. static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info);
  47. static void OnHotspotStaJoinHandler(StationInfo *info);
  48. static void OnHotspotStateChangedHandler(int state);
  49. static void OnHotspotStaLeaveHandler(StationInfo *info);
  50. void DisableWIFI(void)
  51. {
  52. DisableWifi();
  53. }
  54. static void OnHotspotStaJoinHandler(StationInfo *info)
  55. {
  56. (void)info;
  57. printf("STA join AP\n");
  58. return;
  59. }
  60. static void OnHotspotStaLeaveHandler(StationInfo *info)
  61. {
  62. (void)info;
  63. printf("HotspotStaLeave:info is null.\n");
  64. return;
  65. }
  66. static void OnHotspotStateChangedHandler(int state)
  67. {
  68. printf("HotspotStateChanged:state is %d.\n", state);
  69. return;
  70. }
  71. static void WiFiInit(void)
  72. {
  73. printf("<--Wifi Init-->\r\n");
  74. g_wifiEventHandler.OnWifiScanStateChanged = OnWifiScanStateChangedHandler;
  75. g_wifiEventHandler.OnWifiConnectionChanged = OnWifiConnectionChangedHandler;
  76. g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler;
  77. g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler;
  78. g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler;
  79. wifi_error = RegisterWifiEvent(&g_wifiEventHandler);
  80. if (wifi_error != WIFI_SUCCESS)
  81. {
  82. printf("register wifi event fail!\r\n");
  83. }
  84. else
  85. {
  86. printf("register wifi event succeed!\r\n");
  87. }
  88. }
  89. static void OnWifiScanStateChangedHandler(int state, int size)
  90. {
  91. (void)state;
  92. if (size > 0)
  93. {
  94. ssid_count = size;
  95. g_staScanSuccess = 1;
  96. }
  97. return;
  98. }
  99. static int result;
  100. int WifiConnect(const char *ssid, const char *psk)
  101. {
  102. WifiScanInfo *info = NULL;
  103. unsigned int size = WIFI_SCAN_HOTSPOT_LIMIT;
  104. static struct netif *g_lwip_netif = NULL;
  105. WifiDeviceConfig select_ap_config = {0};
  106. osDelay(OD_DELAY_200);
  107. printf("<--System Init-->\r\n");
  108. WiFiInit();
  109. if (EnableWifi() != WIFI_SUCCESS)
  110. {
  111. printf("EnableWifi failed, wifi_error = %d\n", wifi_error);
  112. return -1;
  113. }
  114. if (IsWifiActive() == 0)
  115. {
  116. printf("Wifi station is not actived.\n");
  117. return -1;
  118. }
  119. info = malloc(sizeof(WifiScanInfo) * WIFI_SCAN_HOTSPOT_LIMIT);
  120. if (info == NULL)
  121. {
  122. printf("faild to create wifiscanInfo.\n");
  123. return -1;
  124. }
  125. do
  126. {
  127. ssid_count = 0;
  128. g_staScanSuccess = 0;
  129. Scan();
  130. WaitScanResult();
  131. wifi_error = GetScanInfoList(info, &size);
  132. } while (g_staScanSuccess != 1);
  133. strcpy_s(select_ap_config.ssid, sizeof(select_ap_config.ssid), ssid);
  134. printf("[%s][%s] \r\n", select_ap_config.ssid, select_ap_config.preSharedKey);
  135. select_ap_config.securityType = SELECT_WIFI_SECURITYTYPE;
  136. if (AddDeviceConfig(&select_ap_config, &result) == WIFI_SUCCESS)
  137. {
  138. if (ConnectTo(result) == WIFI_SUCCESS && WaitConnectResult() == 1)
  139. {
  140. printf("WiFi connect succeed!\r\n");
  141. wifi_sta_init_state = 1;
  142. }
  143. }
  144. osDelay(OD_DELAY_100);
  145. return 0;
  146. }
  147. static int WaitConnectResult(void)
  148. {
  149. int ConnectTimeout = DEF_TIMEOUT;
  150. while (ConnectTimeout > 0)
  151. {
  152. sleep(1);
  153. ConnectTimeout--;
  154. if (g_ConnectSuccess == 1)
  155. {
  156. printf("WaitConnectResult:wait success[%d]s\n", (DEF_TIMEOUT - ConnectTimeout));
  157. break;
  158. }
  159. }
  160. if (ConnectTimeout <= 0)
  161. {
  162. printf("WaitConnectResult:timeout!\n");
  163. return 0;
  164. }
  165. return 1;
  166. }
  167. static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info)
  168. {
  169. (void)info;
  170. if (state > 0)
  171. {
  172. g_ConnectSuccess = 1;
  173. printf("callback function for wifi connect\r\n");
  174. }
  175. else
  176. {
  177. g_ConnectSuccess = 0;
  178. printf("connect wifi_error, please check password, state:%d, try connect again\r\n", state);
  179. esp_wifi_connect();
  180. }
  181. return;
  182. }
  183. static void WaitScanResult(void)
  184. {
  185. int scanTimeout = DEF_TIMEOUT;
  186. while (scanTimeout > 0)
  187. {
  188. sleep(ONE_SECOND);
  189. scanTimeout--;
  190. if (g_staScanSuccess == 1)
  191. {
  192. printf("WaitScanResult:wait success[%d]s\n", (DEF_TIMEOUT - scanTimeout));
  193. break;
  194. }
  195. }
  196. if (scanTimeout <= 0)
  197. {
  198. printf("WaitScanResult:timeout!\n");
  199. }
  200. }

wifi_sta_example.c
  1. /*
  2. * Copyright (c) 2022 Hunan OpenValley Digital Industry Development Co., Ltd.
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. #include <stdio.h>
  16. #include "securec.h"
  17. #include "cmsis_os2.h"
  18. #include "ohos_run.h"
  19. #include "lwip/sockets.h"
  20. #include "lwip/ip_addr.h"
  21. #include "wifi_device.h"
  22. #include <string.h>
  23. #define OPEN_WIFI_NAME "test"
  24. // #define SERVER_IP "192.168.31.67"
  25. #define SERVER_IP "119.91.109.180"
  26. #define SERVER_PORT 8344
  27. #define OD_DELAY_1000 1000
  28. #define OD_DELAY_100 100
  29. #define RECV_LEN 511
  30. #define STACK_SIZE 4096
  31. #define PRIORITY 25
  32. osThreadId_t wifi_test_id = NULL;
  33. void wifi_test(void)
  34. {
  35. int sock = -1;
  36. struct sockaddr_in client_addr;
  37. char recv_data[512] = {0};
  38. int recv_data_len;
  39. WifiConnect(OPEN_WIFI_NAME);
  40. printf("start wifi_test test\r\n");
  41. while (1)
  42. {
  43. sock = socket(AF_INET, SOCK_STREAM, 0);
  44. if (sock < 0)
  45. {
  46. printf("Socket error\n");
  47. osDelay(OD_DELAY_100);
  48. continue;
  49. }
  50. memset_s(&(client_addr), sizeof(client_addr), 0, sizeof(client_addr));
  51. client_addr.sin_family = AF_INET;
  52. client_addr.sin_port = htons(SERVER_PORT);
  53. client_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
  54. printf("try connect to server " SERVER_IP " :%d \n", SERVER_PORT);
  55. if (connect(sock, (struct sockaddr *)&client_addr, sizeof(struct sockaddr)) == -1)
  56. {
  57. closesocket(sock);
  58. osDelay(OD_DELAY_1000);
  59. continue;
  60. }
  61. printf("Connect to tcp server successful!\n");
  62. write(sock, "cmd=1&uid=4e2a189d769e4511bd5885742aa3edcb&topic=ledtest\r\n", strlen("cmd=1&uid=4e2a189d769e4511bd5885742aa3edcb&topic=ledtest\r\n"));
  63. while (1)
  64. {
  65. recv_data_len = recv(sock, recv_data, RECV_LEN, 0);
  66. if (recv_data_len <= 0)
  67. {
  68. break;
  69. }
  70. else
  71. {
  72. recv_data[recv_data_len] = '\0';
  73. printf("recv: %s\n", recv_data);
  74. }
  75. }
  76. }
  77. }
  78. static void wifi_test_example(void)
  79. {
  80. osThreadAttr_t attr;
  81. attr.name = "wifi_test";
  82. attr.attr_bits = 0U;
  83. attr.cb_mem = NULL;
  84. attr.cb_size = 0U;
  85. attr.stack_mem = NULL;
  86. attr.stack_size = STACK_SIZE;
  87. attr.priority = PRIORITY;
  88. wifi_test_id = osThreadNew((osThreadFunc_t)wifi_test, NULL, &attr);
  89. if (wifi_test_id == NULL)
  90. {
  91. printf("Failed to create wifi_test thread!\n");
  92. }
  93. }
  94. OHOS_APP_RUN(wifi_test_example);

BUILD.gn

  1. # Copyright (c) 2022 Hunan OpenValley Digital Industry Development Co., Ltd.
  2. # Licensed under the Apache License, Version 2.0 (the "License");
  3. # you may not use this file except in compliance with the License.
  4. # You may obtain a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS,
  10. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. # See the License for the specific language governing permissions and
  12. # limitations under the License.
  13. import("//kernel/liteos_m/liteos.gni")
  14. module_name = get_path_info(rebase_path("."), "name")
  15. kernel_module(module_name) {
  16. sources = [
  17. "wifi_sta_example.c",
  18. "wifi_sta_connect.c"
  19. ]
  20. include_dirs = [
  21. "//foundation/communication/wifi_lite/interfaces/wifiservice",
  22. "//device/board/esp/esp32/liteos_m/hals/driver/wifi_lite"
  23. ]
  24. }

移植步骤

移植本代码中有几个部分需要注意:

  1. 所连接的热点必须是开放的2.4G热点(没有密码)

修改连接热点名方法:将wifi_sta_example.c中OPEN_WIFI_NAME的宏定义修改为热点名即可

  1. 参考巴法云平台接入文档 - TCP协议中 接口地址应是:

但经笔者测试,直接填入"bemfa.com"无法连接上该服务器,推测是无法进行DNS解析,所以我们直接连接IP地址,可以通过cmd打开windows终端 - ping bemfa.com查看域名对应的IP地址

  1. 巴法云提供的TCP服务器是基于订阅/发布(简化版MQTT)的服务,我们可以通过向服务器发送命令的方式对主题进行订阅与发布。

巴法云TCP客户端接入详解

命令字段说明

cmd:消息类型

  1. cmd=1 时为订阅消息,当设备发送一次此消息类型,之后就可以收到发往该主题的消息
  2. cmd=2 时为发布消息,向订阅该主题的设备发送消息
  3. cmd=3 是订阅消息,和cmd=1相同,并且会拉取一次已发送过的消息
  4. cmd=7 是获取时间,获取当前北京时间
  5. cmd=9 为遗嘱消息,拉取一次已经发送的消息

uid:用户私钥

可在控制台获取

topic:用户主题

可以在控制台创建主题,格式为英文或数字,相当于设备标识

msg: 为消息体

用户想要发送到某个主题的数据

符号说明

  1. \r\n: 为回车换符,每条指令后都需要有回车换行。
  2. &: 为连接符,各字段间用'&'隔离。

心跳说明

  1. 发送任意数据 为心跳消息,包括上述指令也算是心跳,但要以回车换行结尾。
  2. 心跳消息是告诉服务器设备还在线,建议60秒发送一次,超过65秒未发送心跳会掉线。

订阅主题

订阅主题,单次最多订阅八个主题

cmd=1&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=xxx1,xxx2,xxx3,xxx4\r\n

正常返回:

cmd=1&res=1

发布
cmd=2&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=light002&msg=off\r\n

正常返回:

cmd=2&res=1
订阅主题,并获取一条历史消息
cmd=3&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=light002\r\n

正常返回:

cmd=3&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=light002&msg=on
获取一次时间
cmd=7&uid=xxxxxxxxxxxxxxxxxxxxxxx&type=1\r\n

正常返回:

2021-06-11 16:39:27
  1. type=1 获取当前日期和时间,例如:2021-06-11 17:20:54
  2. type=2 获取当前时间,例如:17:20:54
  3. type=3 获取当前时间戳,例如:1623403325
获取一次已发消息
cmd=9&uid=7d54f85af42976ee3c2693e6xxxxxxxx&topic=light002\r\n

正常返回:

cmd=9&uid=xxxxxxxxxxxxxxxxxxxxxxx&topic=light002&msg=on
发送心跳
ping\r\n

正常返回:

cmd=0&res=1

发送任意数据,并以\r\n结尾,都为心跳消息,包括上述发布、订阅指令也都算是心跳。 心跳消息是告诉服务器设备还在线,建议60秒发送一次,超过65秒未发送心跳会掉线。

set 指令

推送消息时:主题名后加/set推送消息,表示向所有订阅这个主题的设备们推送消息,假如推送者自己也订阅了这个主题,消息不会被推送给它自己,以防止自己推送的消息被自己接收。 例如向主题 light002推送数据,可为 light002/set 。

示例:

cmd=2&uid=4d9ec352e0376f2110a0c601a2857225&topic=light002/set&msg=on
up 指令

推送消息时:主题名后加/up推送消息,表示只更新云端数据,不进行任何推送。 例如向主题 light002推送数据,可为light002/up。

示例:

cmd=2&uid=4d9ec352e0376f2110a0c601a2857225&topic=light002/up&msg=on
app 指令

订阅时:主题名后加/app订阅主题,不会占用设备在线状态,即不会显示设备在线,可用于app、小程序等订阅时使用。

示例:

cmd=1&uid=4d9ec352e0376f2110a0c601a2857225&topic=light002/app

编译并烧录

在源码根目录下使用hb工具对写好的代码进行编译

选择mini级系统

同理 产品选择esp公司下的esp32

选择完毕后在源码根目录下执行hb build -f 进行编译

编译完成后会有如下界面,并且编译后的代码固件位于:out\esp32\esp32

使用烧录软件进行烧录:

点击start,等待烧录完成

实验现象

按下ESP32开发板上的EN键,即可观察到实验现象:

可以看到我们已经成功连接上TCP服务器,我们打开云平台查看是否有客户端对主题ledtest进行了订阅

我们尝试在云平台进行手动发布信息:hello openharmony!

在串口助手上成功打印出了该信息

后续大家自行将手动发布信息改成使用命令的方式进行发布即可!订阅相同主题的设备都可以收到发布的信息!
​​​​​​​ 本项目代码已上传至gitee:ESP32_Oh: ESP32移植Openharmony

注:本文转载自blog.csdn.net的王子娱乐的文章"https://blog.csdn.net/2301_77659368/article/details/144188846"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

121
服务器
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2024 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top