Back to tech

ESP-WROOM-02におけるソケット通信

2 min read
Table of Contents

ESP-WROOM-02からESP-WROOM-02へデータを送信するにはどうすればよいのだろうと調べていました

調べるとあるにはあるのですが、ESP-WROOM-02をアクセスポイントとしてサーバーを動かし、クライアントがそこへアクセスするという仕組みが多くあります

個人的にはサーバーはルーターにぶら下がった状態でほしいと思っています(ESP-WROOM-02だけでは電波範囲が弱そうであるため)

色々調査した結果、WebSocket.hを使えばできることを知ったのでこれでいくことにしました

備忘録がてら残しておきます

冒頭でも記述しましたが下の図のようにルーターを噛ませてソケット通信をしたいと考えております

ネットでよく見るのは下記のような接続方法(これじゃない)

導入方法

はじめにWebSocketsのライブラリが必要ですのでライブラリをダウンロード後インクルードしてください

GitHub - Links2004/arduinoWebSockets: arduinoWebSockets
github.com
image

クライアントとソケットのプログラムはGitHubに投げてあるので、下記のURLからCloneをしてきてください

GitHub - Momijinn/Simple_socket_communication_of_ESP-WROOM-02
github.com
image

中には”esp_client”と”esp_server”があります

  • esp_client ・・・ クライアント側のプログラム(データを送信する側)

  • esp_server ・・・ サーバー側のプログラム(データを受信する側)

esp_clientの設定

Server_ip ・・・ サーバーのIP

port ・・・ サーバーのポート

ssid ・・・ ルーターのSSID

password ・・・ ルーターのパスワード

//IP
const char* Server_ip("192.168.11.5"); //server_ip
int port = 81; //server_port

//ssid, pass
const char* ssid = "your-ssid";
const char* password = "your-password";

esp_serverの設定

Serverは固定IPにするようにしています(詳しく見たいひとはここ)

ip ・・・ サーバーのIP

gateway ・・・ ゲートウェイ

subnet ・・・ サブネット

DNS ・・・ DNS

port ・・・ サーバーのポート

ssid ・・・ ルーターのSSID

password ・・・ ルーターのパスワード

//Fit to Router
IPAddress ip(192, 168, 11, 5);
IPAddress gateway(192,168, 11, 1);
IPAddress subnet(255, 255, 255, 0);
IPAddress DNS(192, 168, 11, 1);
int port = 81;

//ssid, pass
const char* ssid = "your-ssid";
const char* password = "your-password";

実行結果

esp_client(クライアント側)

[WSc] Connected to url: /
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok
Send: Hello
[WSc]Recv: ok

esp_server(サーバー側)

[2] Connected from 192.168.11.10 url: /
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world
[2] get Text: hello_world

そのうち何台まで接続できるか試してみます( ˘ω˘)

作ったプログラム http://github.com/Momijinn/Simple_socket_communication_of_ESP-WROOM-02.git

参考文献