0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Zephyr(その6:Network)

0
Posted at

Zephyrでネットワーク

RTOSではあるが、ZepherのNetworkは、FreeRTOSなど他のRTOSと比べても充実しているとのこと。そのさわりを確認。これまでは、Wio Terminalを使うことが多かったが、搭載されているChipがZephyrの標準ドライバ(?)ではサポートされておらず、今回は、初代M5Stack(ESP32搭載)を使う。適宜、AIさん利用してトライ&エラー。

題材:「ping ドメイン名」

本家サイトサンプルにコマンド追加を行う。

本サンプルでは、シェルが動作し、各種コマンドが実行できる。まずは、Wifi接続及びIPアドレス取得。

uart:~$ wifi connect -s SSID -p PASSWORD -k 2
Connection requested
Connected
[00:13:03.771,000] <inf> net_dhcpv4: Received: 192.168.10.107
uart:~$

小生の環境では、暗号化方式指定(-k 2: WPA2-PSK-256)が必要であった。次に、Network関連コマンドとして下記が存在する。

uart:~$ net
net - Networking commands
Subcommands:
  allocs     : Print network memory allocations.
  arp        : Print information about IPv4 ARP cache.
  capture    : Configure network packet capture.
  cm         : Control conn_mgr.
  conn       : Print information about network connections.
  dhcpv4     : Manage DHPCv4 services
  dhcpv6     : Manage DHPCv6 services.
  dns        : Show how DNS is configured. Optionally do a query using a given
name.
  events     : Monitor network management events.
  filter     : Print information about network packet filters.
  ftp        : FTP client commands
  gptp       : Print information about gPTP support.
  http       : HTTP commands
  iface      : Print information about network interfaces.
  ipv4       : Print information about IPv4 specific information and
configuration.
  ipv6       : Print information about IPv6 specific information and
configuration.
  mem        : Print information about network memory usage.
  nbr        : Print neighbor information.
  ping       : Ping a network host.
  pkt        : net_pkt information.
  pmtu       : Show PMTU information.
  ppp        : PPP information.
  ptp        : Print information about PTP support.
  qbv        : Qbv commands
  quic       : Print information about Quic connections.
  resume     : Resume a network interface
  route      : Show network route.
  sockets    : Show network sockets.
  stats      : Show network statistics.
  suspend    : Suspend a network interface
  tcp        : Connect/send/close TCP connection.
  udp        : Send/recv UDP packet
  virtual    : Show/manipulate virtual network interfaces.
  vlan       : Show VLAN information.
  websocket  : Print information about WebSocket connections.
  wg         : Show information about the Wireguard VPN connections.
uart:~$ 

pingを実行してみる。

uart:~$ net ping 8.8.8.8
PING 8.8.8.8
28 bytes from 8.8.8.8 to 192.168.10.108: icmp_seq=1 ttl=116 time=28 ms
28 bytes from 8.8.8.8 to 192.168.10.108: icmp_seq=2 ttl=116 time=8 ms
28 bytes from 8.8.8.8 to 192.168.10.108: icmp_seq=3 ttl=116 time=10 ms
uart:~$
uart:~$ net ping abc.com
Invalid IP address

上記のように、サンプルでは、ドメイン名を引数としたpingを実行できない。ここでは、「ping ドメイン名」を可能とするコマンドを作成する。

準備

ESP32で、本サンプルなどのネットワーク周辺を利用するには、追加のパッケージ(ライブラリ?)が必要なようだ。下記によりインストール。

$ west blobs fetch hal_espressif

ソースコード

CMakeLists.txt

CMakeLists.txt
cmake_minimum_required(VERSION 3.20.0)

find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE})
project(TestWiFiwithNC)

FILE(GLOB app_sources src/*.c)
target_sources(app PRIVATE ${app_sources})

ここは特記事項なし。

prj.conf

prj.conf
CONFIG_EARLY_CONSOLE=y

CONFIG_NETWORKING=y
CONFIG_TEST_RANDOM_GENERATOR=y

CONFIG_MAIN_STACK_SIZE=5200
CONFIG_SHELL_STACK_SIZE=5200
CONFIG_NET_TX_STACK_SIZE=2048
CONFIG_NET_RX_STACK_SIZE=2048

CONFIG_NET_PKT_RX_COUNT=10
CONFIG_NET_PKT_TX_COUNT=10
CONFIG_NET_BUF_RX_COUNT=20
CONFIG_NET_BUF_TX_COUNT=20
CONFIG_NET_MAX_CONTEXTS=10
CONFIG_NET_DHCPV4=y

CONFIG_NET_IPV4=y
CONFIG_NET_IPV6=n

CONFIG_NET_TCP=y

CONFIG_NET_LOG=y
CONFIG_INIT_STACKS=y

CONFIG_NET_SHELL=y

CONFIG_NET_STATISTICS=y
CONFIG_NET_STATISTICS_PERIODIC_OUTPUT=n

CONFIG_WIFI=y
CONFIG_WIFI_LOG_LEVEL_ERR=y
CONFIG_NET_L2_WIFI_SHELL=y
# printing of scan results puts pressure on queues in new locking
# design in net_mgmt. So, use a higher timeout for a crowded
# environment.
CONFIG_NET_MGMT_EVENT_QUEUE_TIMEOUT=5000
CONFIG_NET_MGMT_EVENT_QUEUE_SIZE=16

### 追加分
CONFIG_ESP32_USE_UNSUPPORTED_REVISION=y

CONFIG_DNS_RESOLVER=y
CONFIG_DNS_SERVER_IP_ADDRESSES=y

オリジナルサンプルから3つ追加あり(上記追加分以降の行)。

src/main.c

main.c
#include <zephyr/kernel.h>
#include <zephyr/shell/shell.h>
#include <zephyr/net/socket.h>
#include <zephyr/net/net_ip.h>
#include <stdio.h> 

static int cmd_my_ping(const struct shell *sh, size_t argc, char **argv)
{
    if (argc < 2) {
        shell_error(sh, "Usage: my_ping <host_or_ip>");
        return -EINVAL;
    }

    const char *target = argv[1];
    struct zsock_addrinfo hints;
    struct zsock_addrinfo *res = NULL;
    int err;

    memset(&hints, 0, sizeof(hints));
    hints.ai_family = AF_INET;
    hints.ai_socktype = SOCK_RAW;

    shell_print(sh, "Resolving/Parsing: %s...", target);

    // zsock_getaddrinfo:ホスト名・IP文字列の双方対応
    err = zsock_getaddrinfo(target, NULL, &hints, &res);
    if (err != 0 || res == NULL) {
        shell_error(sh, "Failed to resolve %s (err: %d)", target, err);
        return -ENOENT;
    }

    // IPアドレスを文字列に変換
    struct sockaddr_in *ipv4_addr = (struct sockaddr_in *)res->ai_addr;
    char ip_str[INET_ADDRSTRLEN];
    zsock_inet_ntop(AF_INET, &(ipv4_addr->sin_addr), ip_str, sizeof(ip_str));
    shell_print(sh, "Pinging %s [%s]...", target, ip_str);

    zsock_freeaddrinfo(res);

    // サンプルに含まれる「net ping IPアドレス」コマンド作成
    char cmd_buffer[64];
    snprintf(cmd_buffer, sizeof(cmd_buffer), "net ping %s", ip_str);

    // コマンド実行
    err = shell_execute_cmd(sh, cmd_buffer);
    if (err != 0) {
        shell_error(sh, "Failed to execute 'net ping' internal command: %d", err);
    }
    return err;
}

// ルートコマンドとして登録
SHELL_CMD_REGISTER(my_ping, NULL, "Custom ping command (IP or Domain)", cmd_my_ping);

ポイントは下記。

  • zsock_getaddrinfo()によるホスト名解決(IPアドレス化)
  • shell_execute_cmd()を用いて既存コマンド呼び出し
  • SHELL_CMD_REGISTER()によるシェルコマンド登録(my_ping:コマンド名)

なお、コマンド登録については、下記本家サイト参照。

Buildアンド実行

Build及び書き込み。

$ west build -p -b esp32_devkitc/esp32/procpu
$ west flash

実行。

uart:~$ help
Please press the <Tab> button to see all available commands.
You can also use the <Tab> button to prompt or auto-complete all commands or its subcommands.
You can try to call commands with <-h> or <--help> parameter for more information.

Shell supports following meta-keys:
  Ctrl + (a key from: abcdefklnptuw)
  Alt  + (a key from: bf)
Please refer to shell documentation for more details.

Available commands:
  clear    : Clear screen.

<略>

  kernel   : Kernel commands
  my_ping  : Custom ping command (IP or Domain)
  net      : Networking commands

<略>

  shell    : Useful, not Unix-like shell commands.
  wifi     : Wi-Fi commands
uart:~$ 
uart:~$ net ping abc.com
Invalid IP address
uart:~$ 
uart:~$ my_ping abc.com
Resolving/Parsing: abc.com...
Pinging abc.com [3.166.228.2]...

PING 3.166.228.2
28 bytes from 3.166.228.2 to 192.168.10.107: icmp_seq=1 ttl=248 time=16 ms
28 bytes from 3.166.228.2 to 192.168.10.107: icmp_seq=2 ttl=248 time=9 ms
28 bytes from 3.166.228.2 to 192.168.10.107: icmp_seq=3 ttl=248 timeuart:~$ 

成功。

終わりに

今回は単純機能かつまともなSocketコードではないが、ZephyrはLinux系ということもあり、ネットワーク関連のAPIは多数存在しているようだ。下記参照。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?