【开发板试用】XR806使用tcp socket与手机通信

极术社区 极术社区 2021-12-30 11:28:09

本文为极术社区XR806开发板活动试用文章。
参考:基于星辰处理器的全志XR806开源鸿蒙开发板上手体验 搭建环境。并成功编译。

项目源码 : https://gitee.com/kingwho/smart-home

在同一个局域网中,手机与xr806连接后,手机 APP 每隔 1s,发送按键的值给xr806,用于控制xr806的led,然后xr806在返回按键,温度,适度(温度,适度为模拟数据)数据给手机app显示。

将 smart_home 放入 device/xradio/xr806/ohosdemo 下的目录,并修改 device/xradio/xr806/ohosdemo/BUILD.gn 为

group("ohosdemo") {
    deps = [
        #"hello_demo:app_hello",
        #"iot_peripheral:app_peripheral",
        #"wlan_demo:app_WlanTest",
        "smart_home:app_smart_home",
    ]
}

目录结构

.
├── BUILD.gn
└── src
    ├── main.c
    ├── tcp_net_socket.c
    └── tcp_net_socket.h

使用 WIFI 编译时会报错,进行如下操作即可,在随后的编译中可能还会出现,再次如下操作执行即可。

cd device/xradio/xr806/xr_skylark/project/demo/wlan_ble_demo/image/xr806
cp image_wlan_ble.cfg image_wlan_ble.cfg.bk
cat image_auto_cal.cfg > image_wlan_ble.cfg

cjson使用这些宏会报错,建议直接使用 cjson 宏定义后面函数。

#define cJSON_AddNullToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateNull())
#define cJSON_AddTrueToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateTrue())
#define cJSON_AddFalseToObject(object,name) cJSON_AddItemToObject(object, name, cJSON_CreateFalse())
#define cJSON_AddBoolToObject(object,name,b) cJSON_AddItemToObject(object, name, cJSON_CreateBool(b))
#define cJSON_AddNumberToObject(object,name,n) cJSON_AddItemToObject(object, name, cJSON_CreateNumber(n))
#define cJSON_AddStringToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateString(s))
#define cJSON_AddRawToObject(object,name,s) cJSON_AddItemToObject(object, name, cJSON_CreateRaw(s))

xr806连接WIFI后 IP地址可由串口输出打印查看

[net INF] msg <wlan scan success>
GetScanInfoList Success.
AddDeviceConfig Success.
[net INF] no need to switch wlan mode 0
en1: Trying to associate with 94:83:c4:0e:70:be (SSID='GL-MT300N-V2-0be' freq=2437 MHz)
ConnectTo Success
en1: Associated with 94:83:c4:0e:70:be
en1: WPA: Key negotiation completed with 94:83:c4:0e:70:be [PTK=CCMP GTK=CCMP]
en1: CTRL-EVENT-CONNECTED - Connection to 94:83:c4:0e:70:be completed [id=0 id_str=]
[net INF] msg <wlan connected>
[net INF] netif is link up
[net INF] start DHCP...
[net INF] netif (IPv4) is up
[net INF] address: 192.168.8.248
[net INF] gateway: 192.168.8.1
[net INF] netmask: 255.255.255.0
[net INF] msg <network IPv6 state>
[net INF] IPv6 addr state change: 0x0 --> 0x1
[net INF] msg <>

xr806 的固件更新后,需要使用下载器软件重新加载下固件,否则下载的可能还是上次的固件。

BUILD.gn

import("//device/xradio/xr806/liteos_m/config.gni")

static_library("app_smart_home") {
   configs = []
   sources = [
      "src/main.c",
      "src/tcp_net_socket.c",
   ]
   cflags = board_cflags
   include_dirs = board_include_dirs
   include_dirs += [
      "//kernel/liteos_m/kernel/arch/include",
     "//base/iot_hardware/peripheral/interfaces/kits",
      "//utils/native/lite/include",
      "//foundation/communication/wifi_lite/interfaces/wifiservice",
      "//third_party/lwip/src/include",
      "//third_party/cJSON",
   ]
}

tcp_net_socket.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "lwip/sockets.h"

int tcp_server_init(int port)
{
    int sfd = 0;
    struct sockaddr_in saddr;
    sfd = socket(AF_INET,SOCK_STREAM,0);
    
    memset(&saddr, 0, sizeof(struct sockaddr));
    saddr.sin_family  = AF_INET;
    saddr.sin_port    = htons(port);
    saddr.sin_addr.s_addr = INADDR_ANY;
    bind(sfd, (struct  socket*)&saddr, sizeof(struct sockaddr));

    listen(sfd,5);

    return sfd;
}

int tcp_server_accept(int sfd)
{
    int cfd = 0;
    struct  sockaddr_in caddr;
    memset(&caddr, 0, sizeof(struct sockaddr));
    int addrl = sizeof(struct sockaddr);
    cfd = accept(sfd , (struct sockaddr*)&caddr , &addrl);
    return cfd;
}

main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ohos_init.h"
#include "kernel/os/os.h"
#include "iot_gpio.h"
#include "wifi_device.h"
#include "cJSON.h"
#include "lwip/sockets.h"
#include "tcp_net_socket.h"


static void wifi_connect(char *ssid, char *passwd);
static OS_Thread_t g_main_thread;

static void MainThread(void *arg)
{

    unsigned int led_pin = 21; /* GPIOA_PIN21 */
    unsigned int key_pin = 11; /* GPIOA_PIN11 */
    IotGpioValue key_value;
    int led_value = 0;
    unsigned int tem = 0, hum = 0, s = 0;
    cJSON* dev_dat = NULL;

    int sfd = 0;
    int cfd = 0;
    char send_buf[512] = {0};
    char recv_buf[512] = {0};

    wifi_connect("GL-MT300N-V2-0be", "goodlife");

    IoTGpioInit(led_pin);
    IoTGpioSetDir(led_pin, IOT_GPIO_DIR_OUT);
    IoTGpioInit(key_pin);
    IoTGpioSetDir(key_pin, IOT_GPIO_DIR_IN);

    sfd = tcp_server_init(8080);
    cfd = tcp_server_accept(sfd);

    while (1) {

        srand( s++ );
        tem = rand()%10 + 20;
        hum = rand()%20 + 40;
        IoTGpioGetInputVal(key_pin, &key_value);
        printf("kw : hello world! key : %d tem : %d hum : %d\r\n", key_value, tem, hum);
        IoTGpioSetOutputVal(led_pin, led_value);

        recv(cfd, recv_buf, sizeof(recv_buf), 0);
        memset(send_buf, 0, sizeof(send_buf));

        sprintf(send_buf, "{\"led\":\"%d\",\"key\":\"%d\",\"tem\":\"%d\",\"hum\":\"%d\"}",\

                        led_value, key_value, tem, hum);        

        send(cfd,send_buf, strlen(send_buf),0);
        dev_dat = cJSON_Parse(recv_buf);
        led_value = cJSON_GetObjectItem(dev_dat, "led")->valuestring[0] - '0';        
        printf("led data : %d\r\n", led_value);
        cJSON_Delete(dev_dat);
    }

}

static void wifi_connect(char *ssid, char *passwd)
{

    char *ssid_want_connect = ssid;
    char *psk = passwd;

    if (WIFI_SUCCESS != EnableWifi()) {
        printf("Error: EnableWifi fail.\n");
        return;
    }

    printf("EnableWifi Success.\n");

    if (WIFI_STA_ACTIVE == IsWifiActive())
        printf("Wifi is active.\n");
    OS_Sleep(1);

    if (WIFI_SUCCESS != Scan()) {
        printf("Error: Scan fail.\n");
        return;
    }

    printf("Wifi Scan Success.\n");
    OS_Sleep(1);

    WifiScanInfo scan_results[30];
    unsigned int scan_num = 30;

    if (WIFI_SUCCESS != GetScanInfoList(scan_results, &scan_num)) {
        printf("Error: GetScanInfoList fail.\n");
        return;
    }


    WifiDeviceConfig config = { 0 };
    int netId = 0;

    int i;
    for (i = 0; i < scan_num; i++) {
        if (0 == strcmp(scan_results[i].ssid, ssid_want_connect)) {
            memcpy(config.ssid, scan_results[i].ssid,
                   WIFI_MAX_SSID_LEN);
            memcpy(config.bssid, scan_results[i].bssid,
                   WIFI_MAC_LEN);
            strcpy(config.preSharedKey, psk);
            config.securityType = scan_results[i].securityType;
            config.wapiPskType = WIFI_PSK_TYPE_ASCII;
            config.freq = scan_results[i].frequency;
            break;
        }
    }

    if (i >= scan_num) {
        printf("Error: No found ssid in scan_results\n");
        return;
    }
    printf("GetScanInfoList Success.\n");
    if (WIFI_SUCCESS != AddDeviceConfig(&config, &netId)) {
        printf("Error: AddDeviceConfig Fail\n");
        return;
    }
    printf("AddDeviceConfig Success.\n");

    if (WIFI_SUCCESS != ConnectTo(netId)) {
        printf("Error: ConnectTo Fail\n");
        return;
    }

    printf("ConnectTo Success\n");
    OS_Sleep(3);
    WifiLinkedInfo get_linked_res;

    if (WIFI_SUCCESS != GetLinkedInfo(&get_linked_res)) {
        printf("Error: GetLinkedInfo Fail\n");
        return;
    }
    printf("GetLinkedInfo Success.\n");

    printf("ssid: %s\n", get_linked_res.ssid);
    printf("bssid: ");
    for (int j = 0; j < WIFI_MAC_LEN; j++) {
        printf("%02X", get_linked_res.bssid[j]);
    }

    printf("\n");
    printf("rssi: %d\n", get_linked_res.rssi);

    unsigned char get_mac_res[WIFI_MAC_LEN];
    if (WIFI_SUCCESS != GetDeviceMacAddress(get_mac_res)) {
        printf("Error: GetDeviceMacAddress Fail\n");
        return;
    }
    printf("GetDeviceMacAddress Success.\n");
    for (int j = 0; j < WIFI_MAC_LEN - 1; j++) {
        printf("%02X:", get_mac_res[j]);
    }
    printf("%02X\n", get_mac_res[WIFI_MAC_LEN - 1]);

}
void SmartHome(void)
{
    if (OS_ThreadCreate(&g_main_thread, "MainThread", MainThread, NULL,
                OS_THREAD_PRIO_APP, 8 * 1024) != OS_OK) {
        printf("[ERR] Create MainThread Failed\n");
    }
}
SYS_RUN(SmartHome);
  • 将 SmartHome 导入 APICloude Studio
    html/main.html 对应登录界面, 如下可修改默认 IP 和端口号
    <div id="bt_log">
        <form name="myForm" action="" onsubmit="return validateForm()" method="post">
           <div><label>IP地址</label><input type="text" name="ip" value="192.168.8.248"></div>
            <div><label>端口号</label><input type="text" name="port" value="8080"></div>
            <div><input type="submit" class="btn" value="登录" onmouseover="this.style.backgroundPosition='left -36px'"
                onmouseout="this.style.backgroundPosition='left top'"></div>
        </form>

     </div>

log.jpg

html/user_app.html 对应应用界面,与 xr806 在同一个局域网中,同进行通信,通信使用的为 json 数据。

app.jpg

...全文
244 回复 点赞 打赏 收藏 举报
写回复
回复
切换为时间正序
请发表友善的回复…
发表回复
相关推荐
发帖
极术公开课
加入

3442

社区成员

欢迎加入极术社区,共创中国智能计算生态。依托安谋科技“核芯动力”产品,社区提供智能计算领域的资讯,鼓励技术写作和问答互助,致力促进中国芯片技术的合作创新。地址:https://aijishu.com
帖子事件
编辑了帖子
2022-01-14 14:13
创建了帖子
2021-12-30 11:28
社区公告
暂无公告