成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

OpenHarmony Socket通信—DAYU200遙控3861小車

系統 OpenHarmony
筆者最近學習了OpenHarmony Socket通信相關內容,制作了一個DAYU200(OpenHarmony標準系統)遙控3861小車(OpenHarmony輕量系統)的樣例。

想了解更多關于開源的內容,請訪問:

51CTO 開源基礎軟件社區

https://ost.51cto.com

一、DAYU200和3861小車簡單介紹

  • 潤開鴻OpenHarmony標準系統開發板 DAYU200https://gitee.com/hihope_iot/docs/tree/master/HiHope_DAYU200
  • 購買鏈接:https://item.taobao.com/item.htm?spm=a230r.7195193.1997079397.7.6e3855b0FokvDV&id=655971020101&abbucket=15

[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區

3861小車 ,購買鏈接:https://item.taobao.com/item.htm?spm=a230r.7195193.1997079397.35.2cb75ea4PUqbMk&id=632728730350&abbucket=15。

    [OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區

二、DAYU200遙控HiSpark-Pegasus智能小車樣例介紹

  • 本樣例通過TCP socket通信實現DAYU200開發板(OpenHarmony標準系統) 遙控 HiSpark-Pegasus智能小車(OpenHarmony輕量系統)前進、后退、左轉、右轉、停止等操作,實現了一個簡單的OpenHarmony南北向開發互通案例。
  • 樣例開發分成3568端小車控制hap應用和3861端c代碼

1、3568端小車控制hap應用代碼講解

  • Socket連接 https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/connectivity/socket-connection.md
  • @ohos.net.socket (Socket連接) https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-socket.md#onmessage7-1

3568端小車控制hap應用基于 (需要特別注意開發環境!!!OpenHarmony應用開發更新速度很快)。

  • OpenHarmony3.2release
  • DevEco Studio 3.1.0.500
  • sdk 3.2.12.2

DAYU200通過tcp socket與3861建立通信,hap應用主要實現代碼:https://gitee.com/hihope_iot/hispark-pegasus-smart-car/blob/master/DAYU200遙控HiSpark-Pegasus智能小車樣例/DAYU200(3568)/car_socket_control/entry/src/main/ets/pages/Index.ets。

[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區

hap應用TCP協議進行通信大致步驟:

  • import需要的socket模塊。
  • 創建一個TCPSocket連接,返回一個TCPSocket對象。
  • (可選)訂閱TCPSocket相關的訂閱事件。
  • 綁定IP地址和端口,端口可以指定或由系統隨機分配。
  • 連接到指定的IP地址和端口。
  • 發送數據/接收數據。
  • Socket連接使用完畢后,關閉。

添加獲取wifi信息和網絡的權限,在entry\src\main\module.json5中。

"requestPermissions": [
      {
        "name": "ohos.permission.INTERNET",
        "usedScene": {
          "abilities": [
            "ohos.samples.socket.EntryAbility"
          ],
          "when": "always"
        }
      },
      {
        "name": "ohos.permission.GET_WIFI_INFO",
        "usedScene": {
          "abilities": [
            "ohos.samples.socket.EntryAbility"
          ],
          "when": "always"
        }
      }
    ]

建立tcp通信需要首先獲取本地ip地址和端口號。

//為了獲取本地IP地址,需要導入@ohos.wifiManager
import wifiManager from '@ohos.wifiManager';

// 解析標準系統開發板(3568)端本地IP地址
export function resolveIP(ip: number): string {
  if (ip < 0 || ip > 0xFFFFFFFF) {
    throw ('The number is not normal!');
  }
  return (ip >>> 24) + '.' + (ip >> 16 & 0xFF) + '.' + (ip >> 8 & 0xFF) + '.' + (ip & 0xFF);
}

// 獲取標準系統開發板(3568)端本地IP地址
let localAddress = resolveIP(wifiManager.getIpInfo().ipAddress);

// 標準系統開發板(3568)本地ip地址和端口
let bindAddress = {
  address: localAddress,
  port: 5678, // 綁定端口,如1234
  family: 1
};

...
...

        //用一個test組件顯示本地IP地址
        Text(this.message0)
          .fontSize(25)
          .margin({top:0})
          .fontWeight(FontWeight.Normal)
          .backgroundColor(Color.White)

        //用一個test組件顯示本地socket端口號
        Text(this.message1)
          .fontSize(25)
          .margin({top:0})
          .fontWeight(FontWeight.Normal)
          .backgroundColor(Color.White)

tcp初始化,訂閱TCPSocket相關的訂閱事件,綁定本地ip地址和端口。

// 訂閱TCPSocket相關的訂閱事件
            tcp.on('message',value => {
              this.message_recv = this.resolveArrayBuffer(value.message)
              console.log(`TCP_data` + this.message_recv);
            });

            tcp.on('connect', () => {
              console.log("on connect")
            });
            tcp.on('close', () => {
              console.log("on close")
            });

            // 綁定本地ip地址和端口
            tcp.bind(bindAddress, err => {
              if (err) {
                promptAction.showToast({
                  message: '[3861_car_control] bind fail',
                  duration: 3000,
                  bottom: 10
                });
                console.log('[3861_car_control] bind fail');
                return;
              }
              promptAction.showToast({
                message: '[3861_car_control] bind success',
                duration: 3000,
                bottom: 10
              });
              console.log('[3861_car_control] bind success');
            });

綁定輕量系統(3861)的ip地址和端口。

// 3861 IP地址和端口
            let connectAddress = {
              address: this.car_ipaddress,
              port: num, // 端口號
              family: 1
            };

            //連接到指定的3861IP地址和端口
            tcp.connect({
              address: connectAddress, timeout: 6000
            }, err => {
              if (err) {
                promptAction.showToast({
                  message: '[3861_car_control] connect'+this.car_ipaddress+' fail',
                  duration: 3000,
                  bottom: 10
                });
                console.log('[3861_car_control] connect'+this.car_ipaddress+' fail');
                return;
              }
              promptAction.showToast({
                message: '[3861_car_control] connect'+this.car_ipaddress+' success',
                duration: 3000,
                bottom: 10
              });
              console.log('[3861_car_control] connect'+this.car_ipaddress+' success');
            });

3568發送數據至3861。

tcp.send({
              data: '0'
            }, err => {
             if (err) {
                console.log('[3861_car_control] send fail');
                return;
              }
              console.log('[3861_car_control] send success');
            })

3568接收3861發送的數據。

//解析標準系統開發板(3568)接收到的 輕量系統(3861)發送的數據
  resolveArrayBuffer(message: ArrayBuffer): string {
    if (message instanceof ArrayBuffer) {
      let dataView = new DataView(message)
      console.info(`length ${dataView.byteLength}`)
      let str = ""
      for (let i = 0;i < dataView.byteLength; ++i) {
        let c = String.fromCharCode(dataView.getUint8(i))
        if (c !== "\n") {
          str += c
        }
      }
      console.info(`message aray buffer:${str}`)
      return str;
    }
  }

...
...

            // 訂閱TCPSocket相關的訂閱事件
            tcp.on('message',value => {
              this.message_recv = this.resolveArrayBuffer(value.message)
              console.log(`TCP_data` + this.message_recv);
            });

···
···

        //用一個text顯示標準系統開發板(3568)接收到輕量系統(3861)發出的數據
        Text('接收到的3861發送的數據:' + this.message_recv)
          .fontSize(25)
          .margin({top:0})
          .fontWeight(FontWeight.Normal)
          .backgroundColor(Color.White)

關閉tcp連接。

tcp.close((err) => {
              promptAction.showToast({
                message: '[3861_car_control] close socket.',
                duration: 3000,
                bottom: 10
              });
              console.log('[3861_car_control] close socket.')
            });
            tcp.off('message');
            tcp.off('connect');
            tcp.off('close');

完成代碼實現請查看: https://gitee.com/hihope_iot/hispark-pegasus-smart-car/blob/master/DAYU200遙控HiSpark-Pegasus智能小車樣例/DAYU200(3568)/car_socket_control/entry/src/main/ets/pages/Index.ets。

如果要修改hap應用的名稱,在car_socket_control\entry\src\main\resources\zh_CN\element\string.json文件中修改EntryAbility_label屬性。

[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區

如果要修改應用圖標修改car_socket_control\entry\src\main\resources\base\media下icon.png(像素大小為114×114)。

[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區[OpenHarmony Socket通信]DAYU200遙控3861小車-開源基礎軟件社區

2、3861端小車代碼講解

代碼地址: https://gitee.com/hihope_iot/hispark-pegasus-smart-car/tree/master/DAYU200遙控HiSpark-Pegasus智能小車樣例/HiSpark-Pegasus-smart-car(3861)/car_tcp_control。

文件名

說明

BUILD.gn

OpenHarmony構建腳本

demo_entry_cmsis.c

OpenHarmony liteos-m程序入口

net_common.h

系統網絡接口頭文件

net_demo.h

demo腳手架頭文件

net_params.h

網絡參數,包括WiFi熱點信息、端口信息

car_tcp_server_test.c

TCP socket控制小車實現代碼

wifi_connecter.c

OpenHarmony WiFi STA模式API的封裝實現文件

wifi_connecter.h

OpenHarmony WiFi STA模式API的封裝頭文件

本篇文章主要講解主要實現代碼car_tcp_server_test.c (筆者在代碼提交了比較詳細的注釋)

3861tcp發送數據。

//3861發送數據
        retval = send(connfd, request, strlen(request), 0);
        if (retval <= 0) {

           //3568側斷開與3861的tcp連接后進行的處理
           printf("_______________________________________\r\n");
           printf("send response failed, %ld!\r\n", retval);
           printf("do_reconnect...\r\n");
           sleep(DELAY_1S);
           close(connfd);//關閉與客戶端的連接
           sleep(DELAY_1S); // for debug

           break;//跳出while循環
           car_stop();//小車進入停止狀態

        }else{
           printf("The data responsed to the client is %s\r\n", request);
        }

3861接收數據。

//3861接收數據
       retval = recv(connfd, request, sizeof(request), 0);
       if (retval < 0) {

           //3568側斷開與3861的tcp連接后進行的處理
           printf("_______________________________________\r\n");
           printf("recv request failed, %ld!\r\n", retval);
           printf("do_reconnect...\r\n");
           sleep(DELAY_1S);
           close(connfd);//關閉與客戶端的連接
           sleep(DELAY_1S); // for debug
           
           break;//跳出while循環
           car_stop();//小車進入停止狀態

        }else{
           printf("_______________________________________\r\n");
           printf("The data received from the client is %s \r\n", request);
        }

當3568與3861斷開連接后,可以進行重新連接。相關代碼:

while (1) {

    connfd = accept(sockfd, (struct sockaddr *)&clientAddr, &clientAddrLen);
    if (connfd < 0) {
        printf("accept failed, %d, %d\r\n", connfd, errno);
        continue;
    }else{
    printf("_______________________________________\r\n");
    printf("accept success, connfd = %d!\r\n", connfd);
    printf("client addr info: host = %s, port = %hu\r\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port));
    }

/***********************************socket收、發的部分************************************************/

       // 后續 收、發 都在 表示連接的 socket 上進行;
       while (1) {
       char request[128] = "";
      .................
      .................
/*************************************************************************************************/

    }

    }

想了解更多關于開源的內容,請訪問:

51CTO 開源基礎軟件社區

https://ost.51cto.com

責任編輯:jianghua 來源: 51CTO 開源基礎軟件社區
相關推薦

2022-05-30 15:21:27

Hi3861TCP通信

2022-05-23 10:45:34

DAYU200鴻蒙

2022-04-14 11:53:38

HarmonyRelease鴻蒙

2022-07-05 16:31:49

MPPT鴻蒙

2022-04-01 15:26:06

Harmony操作系統鴻蒙

2022-10-25 14:51:11

設備開發鴻蒙

2022-05-31 15:52:50

智能小車鴻蒙

2022-05-31 14:32:23

Stack堆疊容器

2022-06-01 22:30:15

滑動容器堆疊容器

2022-05-17 11:30:34

Stage模型瀏覽器鴻蒙

2021-09-09 10:06:09

鴻蒙HarmonyOS應用

2022-09-07 15:35:49

設備開發鴻蒙

2024-02-07 11:41:51

大語言模型鴻蒙alpaca模型

2022-09-20 14:40:55

開源鴻蒙操作系統

2022-06-06 10:44:10

C++語言鴻蒙

2022-05-26 15:28:03

網絡管理Socket 模塊

2022-05-27 15:04:53

鴻蒙操作系統

2022-07-05 16:13:37

ArkUI-eTS智能晾曬系統

2024-02-19 15:59:52

鴻蒙應用開發操作系統

2024-06-06 08:06:19

鴻蒙大語言模型LLM模型
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 黄色网页在线 | 日本一区二区三区在线观看 | 狼人伊人影院 | 91欧美精品成人综合在线观看 | 黄色一级电影免费观看 | 国产96在线 | 97人人草| 在线小视频| 国产精品一区在线 | 麻豆精品一区二区三区在线观看 | 精品一区二区电影 | 欧美一区二区三区四区视频 | 久久久精品视 | 国产一级毛片视频 | 91污在线| 精品一区在线 | 成人av免费 | 国产午夜精品一区二区三区四区 | 亚洲中午字幕 | 麻豆91精品91久久久 | 综合久久综合久久 | 在线成人av| 综合九九 | 久久久久一区 | 毛片电影| 欧美一区二区三区在线播放 | 日韩欧美三级 | 亚洲精品1区 | 亚洲高清成人 | 草比av| 国产成人aⅴ | 一级毛片观看 | 久久噜 | 殴美黄色录像 | 欧美色人 | 国产区第一页 | 亚洲一区视频在线播放 | 男女爱爱网站 | 在线欧美视频 | 成人做爰www免费看视频网站 | 一级毛片色一级 |