Hi3861 OpenHarmony嵌入式应用入门--wifi sta

news2024/11/16 13:28:39

鸿蒙WiFi STA模式相关的API接口文件路径

foundation/communication/interfaces/kits/wifi_lite/wifiservice/wifi_device.h

所使用的API接口有:

API

接口说明

WifiErrorCode EnableWifi(void);

开启STA

WifiErrorCode DisableWifi(void);

关闭STA

int IsWifiActive(void);

查询STA是否已开启

WifiErrorCode Scan(void);

触发扫描

WifiErrorCode GetScanInfoList(WifiScanInfo* result, unsigned int* size);

获取扫描结果

WifiErrorCode AddDeviceConfig(const WifiDeviceConfig* config, int* result);

添加热点配置,成功会通过result传出netld

WifiErrorCode GetDeviceConfigs(WifiDeviceConfig* result, unsigned int* size);

获取本机所有热点配置

WifiErrorCode RemoveDevice(int networkId);

删除热点配置

WifiErrorCode ConnectTo(int networkId);

连接到热点

WifiErrorCode Disconnect(void);

断开热点连接

WifiErrorCode GetLinkedInfo(WifiLinkedInfo* result);

获取当前连接热点信息

WifiErrorCode RegisterWifiEvent(WifiEvent* event);

注册事件监听

WifiErrorCode UnRegisterWifiEvent(const WifiEvent* event);

解除事件监听

WifiErrorCode GetDeviceMacAddress(unsigned char* result);

获取Mac地址

WifiErrorCode AdvanceScan(WifiScanParams *params);

高级搜索

Hi3861 SDK的DHCP客户端接口:

API

描述

netifapi_netif_find

按名称查找网络接口

netifapi_dhcp_start

启动DHCP客户端

netifapi_dhcp_stop

停止DHCP客户端

代码编写

修改D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\BUILD.gn文件

# Copyright (c) 2023 Beijing HuaQing YuanJian Education Technology 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. 

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

lite_component("demo") {
  features = [
    #"base_00_helloworld:base_helloworld_example",
    #"base_01_led:base_led_example",
    #"base_02_loopkey:base_loopkey_example",
    #"base_03_irqkey:base_irqkey_example",
    #"base_04_adc:base_adc_example",
    #"base_05_pwm:base_pwm_example",
    #"base_06_ssd1306:base_ssd1306_example",
    #"kernel_01_task:kernel_task_example",
    #"kernel_02_timer:kernel_timer_example",
    #"kernel_03_event:kernel_event_example",
    #"kernel_04_mutex:kernel_mutex_example",
    #"kernel_05_semaphore_as_mutex:kernel_semaphore_as_mutex_example",
    #"kernel_06_semaphore_for_sync:kernel_semaphore_for_sync_example",
    #"kernel_07_semaphore_for_count:kernel_semaphore_for_count_example",
    #"kernel_08_message_queue:kernel_message_queue_example",
    #"wifi_09_hotspot:wifi_hotspot_example",
    "wifi_10_sta:wifi_sta_example",
  ]
}

创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\wifi_10_sta文件夹

文件夹中创建D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\wifi_10_sta\wifi_sta_example.c文件D:\DevEcoProjects\test\src\vendor\rtplay\rt_hi3861\demo\wifi_10_sta\BUILD.gn文件

# Copyright (c) 2023 Beijing HuaQing YuanJian Education Technology 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("wifi_sta_example") {
    sources = [
        "wifi_sta_example.c"
    ]

    include_dirs = [
        "//utils/native/lite/include",
        "//kernel/liteos_m/kal",
        "//foundation/communication/wifi_lite/interfaces/wifiservice",
    ]
}
/*
 * Copyright (c) 2020, HiHope Community.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the copyright holder nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

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

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

#include "lwip/netifapi.h"
#include "lwip/api_shell.h"

#define STACK_SIZE     10240
#define AP_SSID        "HarmonyOS"
#define AP_SKEY        "1234567890"

#define IDX_0          0
#define IDX_1          1
#define IDX_2          2
#define IDX_3          3
#define IDX_4          4
#define IDX_5          5

#define DELAY_TICKS_10     (10)
#define DELAY_TICKS_50     (50)
#define DELAY_TICKS_100    (100)
#define DELAY_TICKS_200    (200)

#define COUNTER            (60)

static void PrintLinkedInfo(WifiLinkedInfo* info)
{
    if (!info) return;

    static char macAddress[32] = {0};
    unsigned char* mac = info->bssid;
    // int ret = snprintf(macAddress, sizeof(macAddress), "%02X:%02X:%02X:%02X:%02X:%02X",
    int ret = snprintf_s(macAddress, sizeof(macAddress), sizeof(macAddress) - 1, "%02X:%02X:%02X:%02X:%02X:%02X",
        mac[IDX_0], mac[IDX_1], mac[IDX_2], mac[IDX_3], mac[IDX_4], mac[IDX_5]);
    if (ret < 0) {
        return;
    }
    printf("bssid: %s, rssi: %d, connState: %d, reason: %d, ssid: %s\r\n",
        macAddress, info->rssi, info->connState, info->disconnectedReason, info->ssid);
}

static int g_connected = 0;
static void OnWifiConnectionChanged(int state, WifiLinkedInfo* info)
{
    if (!info) return;

    printf("%s %d, state = %d, info = \r\n", __FUNCTION__, __LINE__, state);
    PrintLinkedInfo(info);

    if (state == WIFI_STATE_AVALIABLE) {
        g_connected = 1;
    } else {
        g_connected = 0;
    }
}

static void OnWifiScanStateChanged(int state, int size)
{
    printf("%s %d, state = %X, size = %d\r\n", __FUNCTION__, __LINE__, state, size);
}

static void WifiConnectTask(void)
{
    WifiErrorCode errCode;
    WifiEvent eventListener = {
        .OnWifiConnectionChanged = OnWifiConnectionChanged,
        .OnWifiScanStateChanged = OnWifiScanStateChanged
    };
    WifiDeviceConfig apConfig = {};
    int netId = -1;

    osDelay(DELAY_TICKS_10);
    errCode = RegisterWifiEvent(&eventListener);
    printf("RegisterWifiEvent: %d\r\n", errCode);

    // setup your AP params
    // strcpy(apConfig.ssid, "ABCD");
    // strcpy(apConfig.preSharedKey, "147258369");
    strcpy_s(apConfig.ssid, WIFI_MAX_SSID_LEN, AP_SSID);
    strcpy_s(apConfig.preSharedKey, WIFI_MAX_KEY_LEN, AP_SKEY);
    apConfig.securityType = WIFI_SEC_TYPE_PSK;

    int timeoutCounter = COUNTER * COUNTER;
    while (timeoutCounter--) {
        errCode = EnableWifi();
        printf("EnableWifi: %d\r\n", errCode);
        osDelay(DELAY_TICKS_10);

        errCode = AddDeviceConfig(&apConfig, &netId);
        printf("AddDeviceConfig: %d\r\n", errCode);

        g_connected = 0;
        errCode = ConnectTo(netId);
        printf("ConnectTo(%d): %d\r\n", netId, errCode);

        while (!g_connected) {
            osDelay(DELAY_TICKS_10);
        }
        printf("g_connected: %d\r\n", g_connected);
        osDelay(DELAY_TICKS_50);

        // 联网业务开始
        struct netif* iface = netifapi_netif_find("wlan0");
        if (iface) {
            err_t ret = netifapi_dhcp_start(iface);
            printf("netifapi_dhcp_start: %d\r\n", ret);

            osDelay(DELAY_TICKS_200); // wait DHCP server give me IP
            ret = netifapi_netif_common(iface, dhcp_clients_info_show, NULL);
            printf("netifapi_netif_common: %d\r\n", ret);
        }

        // 模拟一段时间的联网业务
        int timeout = COUNTER;
        while (timeout--) {
            osDelay(DELAY_TICKS_100);
            printf("after %d seconds, I'll disconnect WiFi!\n", timeout);
        }

        // 联网业务结束
        err_t ret = netifapi_dhcp_stop(iface);
        printf("netifapi_dhcp_stop: %d\r\n", ret);

        Disconnect(); // disconnect with your AP

        RemoveDevice(netId); // remove AP config

        errCode = DisableWifi();
        printf("DisableWifi: %d\r\n", errCode);
        osDelay(DELAY_TICKS_200);
    }
}

static void WifiConnectDemo(void)
{
    osThreadAttr_t attr;

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

    if (osThreadNew(WifiConnectTask, NULL, &attr) == NULL) {
        printf("[WifiConnectDemo] Falied to create WifiConnectTask!\n");
    }
}

APP_FEATURE_INIT(WifiConnectDemo);

使用build,编译成功后,使用upload进行烧录。

ready to OS start
sdk ver:Hi3861V100R001C00SPC025 2020-09-03 18:10:00
formatting spiffs...
FileSystem mount ok.
wifi init success!
hilog will init.


hiview init success.
RegisterWifiEvent: 0
EnableWifi: 0
AddDeviceConfig: 0
ConnectTo(1): 0
+NOTICE:SCANFINISH
+NOTICE:CONNECTED
OnWifiConnectionChanged 80, state = 1, info = 
bssid: 4A:AD:9A:1C:00:D9, rssi: 0, connState: 0, reason: 0, ssid: HarmonyOS
g_connected: 1
netifapi_dhcp_start: 0
server :
        server_id : 192.168.137.1
        mask : 255.255.255.0, 1
        gw : 192.168.137.1
        T0 : 604800
        T1 : 302400
        T2 : 453600
clients <1> :
        mac_idx mac             addr            state   lease   tries   rto     
        0       94c9601e15d0    192.168.137.66  10      0       1       2       
netifapi_netif_common: 0
after 59 seconds, I'll disconnect WiFi!
after 58 seconds, I'll disconnect WiFi!
after 57 seconds, I'll disconnect WiFi!
after 56 seconds, I'll disconnect WiFi!
after 55 seconds, I'll disconnect WiFi!
after 54 seconds, I'll disconnect WiFi!
after 53 seconds, I'll disconnect WiFi!
after 52 seconds, I'll disconnect WiFi!
after 51 seconds, I'll disconnect WiFi!
after 50 seconds, I'll disconnect WiFi!
after 49 seconds, I'll disconnect WiFi!
after 48 seconds, I'll disconnect WiFi!
after 47 seconds, I'll disconnect WiFi!
after 46 seconds, I'll disconnect WiFi!
after 45 seconds, I'll disconnect WiFi!
after 44 seconds, I'll disconnect WiFi!
after 43 seconds, I'll disconnect WiFi!
after 42 seconds, I'll disconnect WiFi!
after 41 seconds, I'll disconnect WiFi!
after 40 seconds, I'll disconnect WiFi!
after 39 seconds, I'll disconnect WiFi!
after 38 seconds, I'll disconnect WiFi!
after 37 seconds, I'll disconnect WiFi!
after 36 seconds, I'll disconnect WiFi!
after 35 seconds, I'll disconnect WiFi!
after 34 seconds, I'll disconnect WiFi!
after 33 seconds, I'll disconnect WiFi!
after 32 seconds, I'll disconnect WiFi!
after 31 seconds, I'll disconnect WiFi!
after 30 seconds, I'll disconnect WiFi!
after 29 seconds, I'll disconnect WiFi!
after 28 seconds, I'll disconnect WiFi!
after 27 seconds, I'll disconnect WiFi!
after 26 seconds, I'll disconnect WiFi!
after 25 seconds, I'll disconnect WiFi!
after 24 seconds, I'll disconnect WiFi!
after 23 seconds, I'll disconnect WiFi!
after 22 seconds, I'll disconnect WiFi!
after 21 seconds, I'll disconnect WiFi!
after 20 seconds, I'll disconnect WiFi!
after 19 seconds, I'll disconnect WiFi!
after 18 seconds, I'll disconnect WiFi!
after 17 seconds, I'll disconnect WiFi!
after 16 seconds, I'll disconnect WiFi!
after 15 seconds, I'll disconnect WiFi!
after 14 seconds, I'll disconnect WiFi!
after 13 seconds, I'll disconnect WiFi!
after 12 seconds, I'll disconnect WiFi!
after 11 seconds, I'll disconnect WiFi!
after 10 seconds, I'll disconnect WiFi!
after 9 seconds, I'll disconnect WiFi!
after 8 seconds, I'll disconnect WiFi!
after 7 seconds, I'll disconnect WiFi!
after 6 seconds, I'll disconnect WiFi!
after 5 seconds, I'll disconnect WiFi!
after 4 seconds, I'll disconnect WiFi!
after 3 seconds, I'll disconnect WiFi!
after 2 seconds, I'll disconnect WiFi!
after 1 seconds, I'll disconnect WiFi!
after 0 seconds, I'll disconnect WiFi!
netifapi_dhcp_stop: 0
+NOTICE:DISCONNECTED

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1884932.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

20240701给NanoPi R6C开发板编译友善之臂的Android12系统

20240701给NanoPi R6C开发板编译友善之臂的Android12系统 2024/7/1 14:19 本文采取这个模式编译&#xff1a;11.6.3 编译Android Tablet版本(首次编译) echo "ROCKCHIP_DEVICE_DIR : device/rockchip/rk3588/nanopi6" > .rockchip_device.mk # export INSTALL_GAP…

LangChain 开发智能Agent,你学会了吗?

Prompt Enginnering 是打开LLM宝库的一把金钥匙&#xff0c;如果prompt得法&#xff0c;并能将其技巧与某项工作深度结合&#xff0c;那必将大大增效。今天我们来聊聊如何优化Prompt设计、Prompt Template管理等技术和体力活&#xff0c;并赋能老喻干货店的营销活动。 LLM Pro…

ollama open-webui安装后报错401

查看日志 docker logs open-webui "GET /ollama/api/tags HTTP/1.1" 500 Internal Server Error "GET /ollama/api/version HTTP/1.1" 500 Internal Server Error "GET /openai/api/models HTTP/1.1" 401 Unauthorized 浏览器console报错

提升ChatGLM效能:仅需简单模型调整

本文作者&#xff1a; 赵桢、罗成、李亭骞、邹文艺 引言 自大语言模型 (LLM) 成为热点话题以来&#xff0c;涌现了一大批中文大语言模型并在优化平台中得到了积极部署。ChatGLM 正是广受好评的主流中文大语言模型之一。 然而&#xff0c;由于 ChatGLM 模型尚未成为 Transfo…

Echarts 问题集锦

最近公司集中做统计图表&#xff0c;新手小白&#xff0c;真被Echarts折腾地不轻&#xff0c;怕自己年老记忆衰退&#xff0c;特地做一些记录。以备后面查阅。 1、X轴的 数据显示不全&#xff0c;间或不显示 很奇葩&#xff0c;我发现数据里有一个值为0.0&#xff0c;当这条记…

Windows 解决文件包含病毒或潜在的垃圾软件

注意确保软件没问题&#xff0c;保护个人数据隐私 问题描述 解决步骤

科普文:一文搞懂jvm原理(三)执行引擎之垃圾回收器

概叙 科普文&#xff1a;一文搞懂jvm(一)jvm概叙-CSDN博客 科普文&#xff1a;一文搞懂jvm原理(二)类加载器-CSDN博客 科普文&#xff1a;一文搞懂jvm原理(三)执行引擎-CSDN博客 科普文&#xff1a;一文搞懂jvm原理(四)运行时数据区-CSDN博客 前面我们介绍了jvm&#xff0c…

基于java+springboot+vue实现的电影院购票系统(文末源码+Lw)274

摘 要 传统办法管理信息首先需要花费的时间比较多&#xff0c;其次数据出错率比较高&#xff0c;而且对错误的数据进行更改也比较困难&#xff0c;最后&#xff0c;检索数据费事费力。因此&#xff0c;在计算机上安装电影院购票系统软件来发挥其高效地信息处理的作用&#xf…

Flink 容错机制

一致性检查点&#xff08;checkpoint&#xff09; 什么是 Checkpoint &#xff1f; Flink 故障恢复机制的核心&#xff0c;就就是应用状态的一致性检查点&#xff1b;有状态流应用的一直检查点&#xff0c;其实就是所有任务的状态&#xff0c;在某一时间点的一份拷贝&#xff…

月之暗面kimi底层推理系统原理

太长不看版&#xff08;作者大佬自己的在知乎碎碎念&#xff09;&#xff1a; 本论文与很多 Prefill/Decoding 分离的论文不同的是&#xff0c;这套方案已经在大规模集群上进行几个月的验证并证明了方案的有效性。目前这套系统承载了 Kimi 线上80% 以上的流量&#xff0c; 效果…

(18)GPS/指南针(一)

文章目录 前言 1 GPS/指南针 2 RTK GPS 3 GPS驱动程序选项 4 GPS自动切换 5 高级用途 前言 Copter/Plane/Rover 支持与 GPS、指南针和其他定位技术的整合&#xff1a; 1 GPS/指南针 Avionics Anonymous GNSS CompassAvionics Anonymous CompassBeitain BN-220 GPS / B…

《梦醒蝶飞:释放Excel函数与公式的力量》8.1 COUNT函数

8.1 COUNT函数 在Excel中&#xff0c;COUNT函数及其相关变体用于统计单元格中的数据量。它们能够帮助我们快速统计数据的数量&#xff0c;常用于数据分析和报表制作。 8.1.1 函数简介 COUNT函数用于统计指定区域内的数值单元格数量。它只统计数值&#xff0c;不包括文本或空…

XD3C03P1G、XD3C01N3F比例方向控制阀放大板

XD3A01N2G、XD3A03N2G、XD3C03N1F、XD3C03P1G、XD3C01N3F、XD3C03N2F、XD3C01P4G、XD3C03P3G、XD3C03N2F、XD3C03N2G、XDP3A01P1F、XDP3C03N2G、XDP3A03P3G、XDP3C01NAF、XDP3C03P6G、XDP3A03PAG、XDP3A03N3F液压比例方向阀是液压系统中的关键元件&#xff0c;用于实现对流量、…

二叉树的右视图-二叉树

199. 二叉树的右视图 - 力扣&#xff08;LeetCode&#xff09; 层序遍历&#xff0c;广度优先 queue先进后出&#xff0c;每层从左往右进树&#xff0c;最后一个就是最右边的数&#xff1b;pop掉这层的。push下一层&#xff1b; class Solution { public:vector<int> r…

考研生活day2--王道课后习题2.3.1、2.3.2、2.3.3

2.3.1 题目描述&#xff1a; 这题和曾经做过的LeetCode203.移除元素一模一样&#xff0c;所以我们就使用LeetCode进行书写&#xff0c;题目链接203. 移除链表元素 - 力扣&#xff08;LeetCode&#xff09; 解题思路 大家的第一反应肯定是根据书上所学的书写方法一样书写&…

【linux网络(七)】数据链路层详解

&#x1f493;博主CSDN主页:杭电码农-NEO&#x1f493;   ⏩专栏分类:Linux从入门到精通⏪   &#x1f69a;代码仓库:NEO的学习日记&#x1f69a;   &#x1f339;关注我&#x1faf5;带你学更多操作系统知识   &#x1f51d;&#x1f51d; Linux网络 1. 前言2. 认识MAC…

C++视觉开发 三.缺陷检测

一.距离变换 1.概念和功能 距离变换是一种图像处理技术&#xff0c;用于计算图像中每个像素到最近的零像素&#xff08;背景像素&#xff09;的距离。它常用于图像分割、形态学操作和形状分析等领域。它计算图像中每个像素到最近的零像素&#xff08;背景像素&#xff09;的距…

CAM350删除铺铜?

CAM350删除铺铜&#xff1f; 1、选择菜单栏Add 2、选择Polygon Void→Line... 3、然点击需要操作的铜箔&#xff0c;使其高亮 4、用鼠标框选需要删除的部分&#xff0c;然后右击 5、删除后如下图所示 The Layer Bar controls are part of the new Navigation Pane and can also…

dledger原理源码分析系列(一)-架构,核心组件和rpc组件

简介 dledger是openmessaging的一个组件&#xff0c; raft算法实现&#xff0c;用于分布式日志&#xff0c;本系列分析dledger如何实现raft概念&#xff0c;以及dledger在rocketmq的应用 本系列使用dledger v0.40 本文分析dledger的架构&#xff0c;核心组件&#xff1b;rpc组…

MySQL 9.0创新版发布!功能又进化了!

作者&#xff1a;IT邦德 中国DBA联盟(ACDU)成员&#xff0c;10余年DBA工作经验&#xff0c; Oracle、PostgreSQL ACE CSDN博客专家及B站知名UP主&#xff0c;全网粉丝10万 擅长主流Oracle、MySQL、PG、高斯及Greenplum备份恢复&#xff0c; 安装迁移&#xff0c;性能优化、故障…