From a72e7c1e885f323a192a517d90759fbf3512b81e Mon Sep 17 00:00:00 2001 From: xiang Date: Wed, 15 Dec 2021 14:23:30 +0800 Subject: [PATCH 1/2] add HttpClient Demo --- applications/app/BUILD.gn | 3 +- applications/app/README.md | 1 + .../app/TW306_Network_httpclient/BUILD.gn | 35 +++ .../app/TW306_Network_httpclient/README.md | 264 +++++++++++++++++ .../include/wifi_connect.h | 24 ++ .../src/http_client.c | 175 +++++++++++ .../src/wifi_connect.c | 277 ++++++++++++++++++ 7 files changed, 778 insertions(+), 1 deletion(-) mode change 100644 => 100755 applications/app/BUILD.gn mode change 100644 => 100755 applications/app/README.md create mode 100755 applications/app/TW306_Network_httpclient/BUILD.gn create mode 100755 applications/app/TW306_Network_httpclient/README.md create mode 100755 applications/app/TW306_Network_httpclient/include/wifi_connect.h create mode 100755 applications/app/TW306_Network_httpclient/src/http_client.c create mode 100755 applications/app/TW306_Network_httpclient/src/wifi_connect.c diff --git a/applications/app/BUILD.gn b/applications/app/BUILD.gn old mode 100644 new mode 100755 index e897b933..ef1e2be6 --- a/applications/app/BUILD.gn +++ b/applications/app/BUILD.gn @@ -45,5 +45,6 @@ lite_component("app") { # "TW304_Network_tcpclient:network_tcpclient_demo", # "TW305_Network_udpclient:network_udpclient_demo", # "TW305_Network_udpserver:network_udpserver_demo", + # "TW306_Network_httpclient:network_httpclient_demo", ] -} +} \ No newline at end of file diff --git a/applications/app/README.md b/applications/app/README.md old mode 100644 new mode 100755 index c08604a0..413be4b2 --- a/applications/app/README.md +++ b/applications/app/README.md @@ -43,4 +43,5 @@ | TW304 | Network | tcpclient | [TCP客户端联网演示](TW304_Network_tcpclient/README.md) | 核心板 | | TW305 | Network | udpserver | [UDP服务端联网演示](TW305_Network_udpserver/README.md) | 核心板 | | TW305 | Network | udpclient | [UDP客户端联网演示](TW305_Network_udpclient/README.md) | 核心板 | +| TW306 | Network | httpclient | [http客户端联网演示](TW306_Network_httpclient/README.md) | 核心板 | | TW402 | APP | oled_u8g2 | [OLED U8G2库综合应用演示](TW402_APP_oled_u8g2/README.md) | 核心板 + OLED扩展板| diff --git a/applications/app/TW306_Network_httpclient/BUILD.gn b/applications/app/TW306_Network_httpclient/BUILD.gn new file mode 100755 index 00000000..6f749b78 --- /dev/null +++ b/applications/app/TW306_Network_httpclient/BUILD.gn @@ -0,0 +1,35 @@ +# Copyright (c) 2021 Talkweb 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("network_httpclient_demo") { + sources = [ + "src/wifi_connect.c", + "src/http_client.c", + ] + + #cflags = [ "-Wno-unused-variable" ] + #cflags += [ "-Wno-unused-but-set-variable" ] + + include_dirs = [ + "//foundation/communication/wifi_lite/interfaces/wifiservice" , + "//third_party/HTTPClient/include/", + "include" , + #"//third_party/mbedtls/include", + # "//device\talkweb\niobe\sdk_liteos\third_party\lwip_sack\include\lwip", + + #"//applications/app/tw_components_ota_lite-master/frameworks/include", + ] + + #deps = ["//applications/app/tw_components_ota_lite-master:tw_ota_demo"] + deps = ["//third_party/HTTPClient:httpclient_lib"] +} \ No newline at end of file diff --git a/applications/app/TW306_Network_httpclient/README.md b/applications/app/TW306_Network_httpclient/README.md new file mode 100755 index 00000000..f67b01ef --- /dev/null +++ b/applications/app/TW306_Network_httpclient/README.md @@ -0,0 +1,264 @@ +# Niobe开发板http客户端联网演示 + +本案例程序将演示怎么在拓维Niobe WiFi IoT Core开发板上编写一个基于cmcc-oneos HttpClient开源库,连接http服务器的业务程序,实现开发板联网上报数据到http服务器。由于https依赖第三方库,待适配,目前不支持https。 + +## 简述 +HTTP(Hypertext Transfer Protocol)协议,即超文本传输协议,HTTP是一个基于TCP/IP通信协议来传递数据(HTML 文件, 图片文件, 查询结果等)。HTTP协议实现主要运用在浏览器访问网页,根据请求的内容,服务器返回相应的请求内容为B/S模式,而嵌入式操作系统中主要运用的式C/S模式,即客户端与服务器的方式,通过系统客户端构造请求的消息,访问服务器,然后服务器返回相应的内容.HTTP协议工作于C/S(客户端/服务器)架构之上。HTTP协议协议最新版本是 HTTP 2.0,目前是用最广泛的是 HTTP 1.1。因为HTTP 1.1已经能满足我们基本需求了。HTTP协议目前有两种传输模式分别是HTTP和HTTPS,其中HTTPS = HTTP + SSL(或TLS)。HTTP传输方式访问的服务器默认端口为80端口。HTTPS传输方式访问的服务器默认端口为443。 + + + +## 结构体详解 + +``` +typedef struct { + int socket; /**< socket ID */ + int remote_port; /**< hTTP or HTTPS port */ + int response_code; /**< response code */ + char *header; /**< request custom header */ + char *auth_user; /**< username for basic authentication */ + char *auth_password; /**< password for basic authentication */ + bool is_http; /**< http connection? if 1, http; if 0, https */ +#ifdef CONFIG_HTTP_SECURE + const char *server_cert; /**< server certification */ + const char *client_cert; /**< client certification */ + const char *client_pk; /**< client private key */ + int server_cert_len; /**< server certification lenght, server_cert buffer size */ + int client_cert_len; /**< client certification lenght, client_cert buffer size */ + int client_pk_len; /**< client private key lenght, client_pk buffer size */ + void *ssl; /**< ssl content */ +#endif +} http_client_t; +``` + +**描述:** + +客户端信息 + +**参数:** + +| 名字 | 描述 | +| ------ | -------- | +|socket| 套接字id| +|remote_port| 服务端的端口号 | +|response_code| 响应编码| +|header| 请求头| +|auth_user| 用户名 | +|auth_password | 密码 | +|is_http | http服务标志位,true表示http,false表示https | +|server_cert | 服务器认证 | +|client_cert | 客户端认证 | +|client_pk | 客户端私钥 | +|server_cert_len | server_cert字符串长度 | +|client_cert_len | client_cert字符串长度 | +|client_pk_len | client_pk字符串长度 | +|ssl | 安全套接字协议 | + +**示例代码如下:** + +``` + struct sockaddr_in server_addr; + bzero(&server_addr,sizeof(server_addr)); // 初始化服务器地址 + server_addr.sin_family = AF_INET; + server_addr.sin_port = htons(_PROT_); + //server_addr.sin_addr.s_addr = htonl(INADDR_ANY); + inet_pton(AF_INET, _SERVER_IP_, &server_addr.sin_addr); +``` + +------------------------------------ + +## 函数详解 + +``` +HTTP_RESULT_CODE http_client_get(http_client_t *client, const char *url, http_client_data_t *client_data); +``` + +**描述:** 在指定的URL上执行GET请求,它会阻塞直到完成 + +**参数:** + +| 名字 | 描述 | +| ----- | ------------------------- | +| client | 存放客户端数据 | +| url | 待请求的网址 | +| client_data | 用于收集请求返回的数据,它还包含要发布的数据。 | + + + +## 软件设计 + +**主要代码分析** + +```c +static void http_get_task(void) +{ + // + http_client_t client = {0}; + http_client_data_t clientData = {0}; + char *url = NULL; + url = str_dup(baiduurl); + if (url == NULL) + { + printf("no memory for create url buffer\n"); + return ; + } + unsigned char *buf = NULL; + int maxPackageLen = 4097; + int maxLen = 0; + unsigned int offset = 0x0; + + buf = malloc(maxPackageLen); + if (buf == NULL) + { + return ; + } + memset(buf, 0, maxPackageLen); + clientData.response_buf = buf; + clientData.response_buf_len = maxPackageLen; + + int ret = http_client_get(&client, (const char *)url, &clientData); + if(ret >=0 ) + { + printf("success\n"); + } + else + { + printf("faild\n"); + } + + if(buf) { + free(buf); + buf=NULL; + } + if(url){ + free(url); + url=NULL; + } + + return; +} +``` + +## 编译调试 + +### 修改对接热点的账号密码 + +修改`tcp_client.c`第30行和31行的WiFi热点SSID和密码,改成自己环境中的WiFi热点。 + +``` +// 默认WiFi名和密码 +#define WIFI_SSID "openharmony" +#define WIFI_PASSWORD "talkweb1996" +``` + +### 修改 BUILD.gn 文件 + +修改 `applications/app/BUILD.gn` 路径中的 BUILD.gn 文件,指定 `network_httpclient_demo` 参与编译。 + +``` + # "TW303_Network_mqttclient:network_mqttclient_example", + # "TW402_APP_oled_u8g2:app_oled_u8g2_example", + # "TW304_Network_tcpserver:network_tcpserver_demo", + # "TW304_Network_tcpclient:network_tcpclient_demo", + # "TW305_Network_udpclient:network_udpclient_demo", + "TW306_Network_httpclient:network_httpclient_demo", +``` + +### 运行结果 + +示例代码编译烧录代码后,按下开发板的RESET按键,通过串口助手查看日志,会打印连接到的Wifi热点信息,以及向服务端请求信息,和服务端返回的信息 + +链接wifi成功,并打印IP信息 +``` +callback function for wifi connect + +WaitConnectResult:wait success[1]s +WiFi connect succeed! +begain to dhcp<-- DHCP state:Inprogress --> + +<-- DHCP state:Inprogress --> + +<-- DHCP state:Inprogress --> + +<-- DHCP state:OK --> +server : + server_id : 192.168.1.1 + mask : 255.255.255.0, 1 + gw : 192.168.1.1 + T0 : 7200 + T1 : 3600 + T2 : 6300 +clients <1> : + mac_idx mac addr state lease tries rto + 0 b4c9b9af6afe 192.168.1.114 10 0 1 3 +``` + +客户端请求头的信息 +``` +request header is GET / HTTP/1.1 +User-Agent: OneOS-HTTP-Client/1.0 +Cache-Control: no-cache +Host: www.baidu.com +``` + + +连接http服务端并得到响应 +``` +Written 99 bytes, socket = 0 +httpclient_send() result:0, client:0xee7ac + +Bdpagetype: 1 +Bdqid: 0x8683b44000036337 +Cache-Control: private +Connection: keep-alive +Content-Type: text/html;charset=utf-8 +Date: Thu, 09 Dec 2021 06:23:39 GMT +Expires: Thu, 09 Dec 2021 06:23:09 GMT +P3p: CP=" OTI DS +Read header : Bdpagetype: 1 +Read header : Bdqid: 0x8683b44000036337 +Read header : Cache-Control: private +Read header : Connection: keep-alive +Read header : Content-Type: text/html;charset=utf-8 +Read header : Date: Thu, 09 Dec 2021 06:23:39 GMT +Read header : Expires: Thu, 09 Dec 2021 06:23:09 GMT +Read header : P3p: CP=" OTI DSP COR IVA OUR IND COM " +Read header : P3p: CP=" OTI DSP COR IVA OUR IND COM " +Read header : Server: BWS/1.1 +Read header : Set-Cookie: BAIDUID=4173C1FA2ED483853AF56AB4819135AC:FG=1; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com +Read header : Set-Cookie: BIDUPSID=4173C1FA2ED483853AF56AB4819135AC; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com +Read header : Set-Cookie: PSTM=1639031019; expires=Thu, 31-Dec-37 23:55:55 GMT; max-age=2147483647; path=/; domain=.baidu.com +Read header : Set-Cookie: BAIDUID=4173C1FA2ED48385DDB272E52F1F187B:FG=1; max-age=31536000; expires=Fri, 09-Dec-22 06:23:39 GMT; domain=.baidu.com; path=/; version=1; comment=bd +Read header : Set-Cookie: BDSVRTM=0; path=/ +Read header : Set-Cookie: BD_HOME=1; path=/ +Read 943 chars; In buf: [Set-Cookie: H_PS_PSSID=34445_35105_31254_34584_34517_35233_34606_35329_35324_26350_35209; path=/; domain=.baidu.com +Traceid: 163903101904392514669692789010002567991 +Vary: Accept-Encoding +Vary: Accept-Encoding +X-Frame-Options: s +in loop http_client_response_parse 880 ret 0 len 1023 +Read header : Set-Cookie: H_PS_PSSID=34445_35105_31254_34584_34517_35233_34606_35329_35324_26350_35209; path=/; domain=.baidu.com +Read header : Traceid: 163903101904392514669692789010002567991 +Read header : Vary: Accept-Encoding +Read header : Vary: Accept-Encoding +Read header : X-Frame-Options: sameorigin +Read header : X-Ua-Compatible: IE=Edge,chrome=1 +Read header : Transfer-Encoding: chunked +in loop http_client_retrieve_content 681 len 716 ret 0 +Retrieving 2839 bytes, len:711 +readLen 2839, len:711 +readLen 2128, len:1023 +readLen 1105, len:1023 +readLen 82, len:82 +memmove 82 82 0 +in loop http_client_retrieve_content 681 len 1021 ret 0 +Retrieving 32768 bytes, len:1015 +readLen 32768, len:1015 +readLen 31753, len:242 +httpclient_recv_data() result:1, client:0xee7ac +No form data info found +httpclient_close() client:0xee7ac +success + +``` + + diff --git a/applications/app/TW306_Network_httpclient/include/wifi_connect.h b/applications/app/TW306_Network_httpclient/include/wifi_connect.h new file mode 100755 index 00000000..c6bb2b6d --- /dev/null +++ b/applications/app/TW306_Network_httpclient/include/wifi_connect.h @@ -0,0 +1,24 @@ +/* +* Copyright (c) 2021 Talkweb 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. +*/ + +#ifndef __WIFI_CONNECT_H__ +#define __WIFI_CONNECT_H__ + +int WifiConnect(const char *ssid,const char *psk); + +#endif /* __WIFI_CONNECT_H__ */ + + + diff --git a/applications/app/TW306_Network_httpclient/src/http_client.c b/applications/app/TW306_Network_httpclient/src/http_client.c new file mode 100755 index 00000000..fd1f9a3c --- /dev/null +++ b/applications/app/TW306_Network_httpclient/src/http_client.c @@ -0,0 +1,175 @@ +/* +* Copyright (c) 2021 Talkweb 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. +*/ + +#include +#include +#include "ohos_init.h" +#include "cmsis_os2.h" +#include "lwip/sockets.h" +#include "wifi_connect.h" + +#include "http_application_api.h" +#include "http.h" + +#include +#include + +/*wifi参数配置*/ +#define WIFI_SSID "openharmony" +#define WIFI_PASSWORD "talkweb1996" + +/* @brief http get sample test */ +char *geturl = "https://open.iot.10086.cn/"; + +char *baiduurl = "http://www.baidu.com/"; + +char *talkweburl = "http://wps.talkweb.com.cn/user/index"; + +/* @brief http delete sample test */ +char *deleteurl = "https://hanyu.baidu.com/zici/s?wd=%E4%B8%80&query=%E4%B8%80&srcid=28232&from=kg0"; + +char *baidubaikeurl = "http://baike.baidu.com/item/1/31661?fr=aladdin"; + +char *talkweblinkurl = "http://172.16.2.254:90/login"; + +/* @brief http request buffer */ +#define BUF_SIZE 4096 + +#ifdef CONFIG_HTTP_SECURE +static const char *ca_cert = \ +{ + \ + "-----BEGIN CERTIFICATE-----\r\n" + "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG\r\n" \ + "A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv\r\n" \ + "b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw\r\n" \ + "MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i\r\n" \ + "YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT\r\n" \ + "aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ\r\n" \ + "jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp\r\n" \ + "xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp\r\n" \ + "1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG\r\n" \ + "snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ\r\n" \ + "U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8\r\n" \ + "9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E\r\n" \ + "BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B\r\n" \ + "AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz\r\n" \ + "yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE\r\n" \ + "38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP\r\n" \ + "AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad\r\n" \ + "DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME\r\n" \ + "HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\r\n" \ + "-----END CERTIFICATE-----" +}; +#endif + +static char *str_dup(char *s) +{ + char *url = NULL; + int len = strlen(s) + 1; + url = malloc(len); + + if(url == NULL) + { + return NULL; + } + + memcpy(url, s, len); + + return url; +} + +static void http_get_task(void) +{ + // + http_client_t client = {0}; + http_client_data_t clientData = {0}; + char *url = NULL; + url = str_dup(talkweblinkurl); + if (url == NULL) + { + printf("no memory for create url buffer\n"); + return ; + } + unsigned char *buf = NULL; + int maxPackageLen = 4097; + int maxLen = 0; + unsigned int offset = 0x0; + + buf = malloc(maxPackageLen); + if (buf == NULL) + { + return ; + } + memset(buf, 0, maxPackageLen); + clientData.response_buf = buf; + clientData.response_buf_len = maxPackageLen; + + int ret = http_client_get(&client, (const char *)url, &clientData); + if(ret >=0 ) + { + printf("success\n"); + } + else + { + printf("faild\n"); + } + + if(buf) { + free(buf); + buf=NULL; + } + if(url){ + free(url); + url=NULL; + } + + return; +} + + +/*http客户端任务*/ +static void HttpClientTask(void) +{ + //连接Wifi + int res = WifiConnect(WIFI_SSID,WIFI_PASSWORD); + if(res !=0) + { + printf("Wifi Connect faild\n"); + return ; + } + + http_get_task(); +} + +static void HttpClientDemo(void) +{ + osThreadAttr_t attr; + + attr.name = "HttpClientTask"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = 1024*12; + attr.priority = osPriorityNormal; + + if (osThreadNew((osThreadFunc_t)HttpClientTask, NULL, &attr) == NULL) + { + printf("[TCPServerDemo] Falied to create HttpClientTask!\n"); + } +} + +APP_FEATURE_INIT(HttpClientDemo); \ No newline at end of file diff --git a/applications/app/TW306_Network_httpclient/src/wifi_connect.c b/applications/app/TW306_Network_httpclient/src/wifi_connect.c new file mode 100755 index 00000000..1acd81a4 --- /dev/null +++ b/applications/app/TW306_Network_httpclient/src/wifi_connect.c @@ -0,0 +1,277 @@ +/* +* Copyright (c) 2021 Talkweb 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. +*/ + +#include +#include +#include + +#include "ohos_init.h" +#include "cmsis_os2.h" + +#include "lwip/netif.h" +#include "lwip/netifapi.h" +#include "lwip/ip4_addr.h" +#include "lwip/api_shell.h" + +#include "wifi_device.h" + +#define DEF_TIMEOUT 15 +#define ONE_SECOND 1 + +#define SELECT_WLAN_PORT "wlan0" +#define SELECT_WIFI_SECURITYTYPE WIFI_SEC_TYPE_PSK + +static int g_staScanSuccess = 0; +static int g_ConnectSuccess = 0; +static int ssid_count = 0; + +WifiErrorCode g_error; +WifiEvent g_wifiEventHandler = {0}; + +static void WiFiInit(void); +static void WaitSacnResult(void); +static int WaitConnectResult(void); +static void OnWifiScanStateChangedHandler(int state, int size); +static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info); +static void OnHotspotStaJoinHandler(StationInfo *info); +static void OnHotspotStateChangedHandler(int state); +static void OnHotspotStaLeaveHandler(StationInfo *info); + +static void OnHotspotStaJoinHandler(StationInfo *info) +{ + (void)info; + printf("STA join AP\n"); + return; +} + +static void OnHotspotStaLeaveHandler(StationInfo *info) +{ + (void)info; + printf("HotspotStaLeave:info is null.\n"); + return; +} + +static void OnHotspotStateChangedHandler(int state) +{ + printf("HotspotStateChanged:state is %d.\n", state); + return; +} + +static void WiFiInit(void) +{ + printf("<--Wifi Init-->\r\n"); + g_wifiEventHandler.OnWifiScanStateChanged = OnWifiScanStateChangedHandler; + g_wifiEventHandler.OnWifiConnectionChanged = OnWifiConnectionChangedHandler; + g_wifiEventHandler.OnHotspotStaJoin = OnHotspotStaJoinHandler; + g_wifiEventHandler.OnHotspotStaLeave = OnHotspotStaLeaveHandler; + g_wifiEventHandler.OnHotspotStateChanged = OnHotspotStateChangedHandler; + g_error = RegisterWifiEvent(&g_wifiEventHandler); + if (g_error != WIFI_SUCCESS) + { + printf("register wifi event fail!\r\n"); + } + else + { + printf("register wifi event succeed!\r\n"); + } +} + +static void OnWifiScanStateChangedHandler(int state, int size) +{ + (void)state; + if (size > 0) + { + ssid_count = size; + g_staScanSuccess = 1; + } + return; +} + +int WifiConnect(const char *ssid, const char *psk) +{ + WifiScanInfo *wifi_info = NULL; + unsigned int size = WIFI_SCAN_HOTSPOT_LIMIT; + static struct netif *g_lwip_netif = NULL; + WifiDeviceConfig select_ap_config = {0}; + + osDelay(200); + printf("<--System Init-->\r\n"); + + // 初始化WIFI + WiFiInit(); + + if (EnableWifi() != WIFI_SUCCESS) + { + printf("EnableWifi failed, error = %d\n", g_error); + return -1; + } + + //判断WIFI是否激活 + if (IsWifiActive() == 0) + { + printf("Wifi station is not actived.\n"); + return -1; + } + + //分配空间,保存WiFi信息 + wifi_info = malloc(sizeof(WifiScanInfo) * WIFI_SCAN_HOTSPOT_LIMIT); + if (wifi_info == NULL) + { + printf("faild to create wifiscanInfo.\n"); + return -1; + } + + do + { + //重置标志位 + ssid_count = 0; + g_staScanSuccess = 0; + //开启wifi扫描 + Scan(); + + //等待扫描结果 + WaitSacnResult(); + + //获取扫描列表 + g_error = GetScanInfoList(wifi_info, &size); + } while (g_staScanSuccess != 1); + + //打印WiFi列表 + printf("********************\r\n"); + for (uint8_t i = 0; i < ssid_count; i++) + { + printf("no:%03d, ssid:%-30s, rssi:%5d\r\n", i + 1, wifi_info[i].ssid, wifi_info[i].rssi / 100); + } + printf("********************\r\n"); + + //插件指定的wifi是否存在 + for (uint8_t i = 0; i < ssid_count; i++) + { + if (strcmp(ssid, wifi_info[i].ssid) == 0) + { + int result; + printf("Select:%3d wireless, Waiting...\r\n", i + 1); + //拷贝要连接的热点信息 + strcpy(select_ap_config.ssid, wifi_info[i].ssid); + strcpy(select_ap_config.preSharedKey, psk); + select_ap_config.securityType = SELECT_WIFI_SECURITYTYPE; + + if (AddDeviceConfig(&select_ap_config, &result) == WIFI_SUCCESS) + { + if (ConnectTo(result) == WIFI_SUCCESS && WaitConnectResult() == 1) + { + printf("WiFi connect succeed!\r\n"); + g_lwip_netif = netifapi_netif_find(SELECT_WLAN_PORT); + break; + } + } + } + + if (i == ssid_count - 1) + { + printf("ERROR: No wifi as expected\r\n"); + while (1) + osDelay(100); + } + } + + //启动DHCP + if (g_lwip_netif) + { + dhcp_start(g_lwip_netif); + printf("begain to dhcp"); + } + + //等待DHCP + for (;;) + { + if (dhcp_is_bound(g_lwip_netif) == ERR_OK) + { + printf("<-- DHCP state:OK -->\r\n"); + + //打印获取到的IP信息 + netifapi_netif_common(g_lwip_netif, dhcp_clients_info_show, NULL); + break; + } + + printf("<-- DHCP state:Inprogress -->\r\n"); + osDelay(100); + } + + osDelay(100); + if (wifi_info != NULL) + { + free(wifi_info); + wifi_info = NULL; + } + return 0; +} + +static int WaitConnectResult(void) +{ + int ConnectTimeout = DEF_TIMEOUT; + while (ConnectTimeout > 0) + { + sleep(1); + ConnectTimeout--; + if (g_ConnectSuccess == 1) + { + printf("WaitConnectResult:wait success[%d]s\n", (DEF_TIMEOUT - ConnectTimeout)); + break; + } + } + if (ConnectTimeout <= 0) + { + printf("WaitConnectResult:timeout!\n"); + return 0; + } + + return 1; +} + +static void OnWifiConnectionChangedHandler(int state, WifiLinkedInfo *info) +{ + (void)info; + + if (state > 0) + { + g_ConnectSuccess = 1; + printf("callback function for wifi connect\r\n"); + } + else + { + printf("connect error,please check ssid and password\r\n"); + } + return; +} + +static void WaitSacnResult(void) +{ + int scanTimeout = DEF_TIMEOUT; + while (scanTimeout > 0) + { + sleep(ONE_SECOND); + scanTimeout--; + if (g_staScanSuccess == 1) + { + printf("WaitSacnResult: wait success [%d] s \n", (DEF_TIMEOUT - scanTimeout)); + break; + } + } + if (scanTimeout <= 0) + { + printf("WaitSacnResult:timeout!\n"); + } +} -- Gitee From 4e193143935daa53f7467afe203f82abc3a43b98 Mon Sep 17 00:00:00 2001 From: xiang Date: Wed, 15 Dec 2021 14:27:41 +0800 Subject: [PATCH 2/2] add httpclient demo --- README.md | 1 + 1 file changed, 1 insertion(+) mode change 100644 => 100755 README.md diff --git a/README.md b/README.md old mode 100644 new mode 100755 index 8c1729d3..1f281183 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ | TW304 | Network | tcpclient | [TCP客户端联网演示](applications/app/TW304_Network_tcpclient/README.md) | 核心板 | | TW305 | Network | udpserver | [UDP服务端联网演示](applications/app/TW305_Network_udpserver/README.md) | 核心板 | | TW305 | Network | udpclient | [UDP客户端联网演示](applications/app/TW305_Network_udpclient/README.md) | 核心板 | +| TW306 | Network | httpclient | [HTTP客户端联网演示](applications/app/TW306_Network_httpclient/README.md) | 核心板 | | TW402 | APP | oled_u8g2 | [OLED U8G2库综合应用演示](applications/app/TW402_APP_oled_u8g2/README.md) | 核心板 + OLED扩展板| ## 五、源码目录简介 -- Gitee