ESP-WROOM-02

2020年12月28日 (月)

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(STARWARS編)

2020/12/28:
初版

board3 Ascii STARWARS v2

board3 Ascii STARWARS v2

概要

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(STARWARS編)
本記事は「 Wio-TerminalでWiFiで使う(その2: STARTWARS,WEB_ACCESS) 」 のStarwarsのスケッチを複数ボード対応とwio-terminalのファームウェア・バージョンアップに対応したものである。

wio-terminalのファームウェアのバージョンアップで以下の不具合も解消している。
(描画速度も大幅な改善が見られる)

一部、以下のようなATコマンドのレスポンス・ヘッダーが表示されることがある。 wifi関係のライブラリにバグがあるようだ。 +IPD,4,988,94.142.241.111,23:__|_____|___________|__|____________|_||____ +IPD,4,1460,94.142.241.111,23: +IPD,4,1460,94.142.241.111,23: |(I/ /][][\| {}/ {} \[][][]

wio-terminalのファームウェアのアップデート方法については以下を参照のこと:
wio-terminalのファームウェア・アップデートについて(v2)(linux版)

デモ・スケッチ

src/wifi_starwars.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 ////#define M5ATOM //------------------ #ifdef M5ATOM #include "M5Atom.h" #define ESP32 #endif #ifdef WIO_TERMINAL //#include <AtWiFi.h> #include <rpcWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif const char* ssid = "your_ssid"; const char* passwd = "yours_passwd"; // Use WiFiClient class to create TCP connections WiFiClient client; void setup() { Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(2000); WiFi.begin(ssid, passwd); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.println("Connecting to WiFi.."); } Serial.println("Connected to the WiFi network"); Serial.print("IP Address: "); Serial.println (WiFi.localIP()); // prints out the device's IP address // set url for telnet const char* host = "towel.blinkenlights.nl"; const uint16_t port = 23; Serial.print("Connecting to "); Serial.println(host); while (!client.connect(host, port)) { Serial.println("Connection failed."); Serial.println("Waiting 5 seconds before retrying..."); delay(5000); } } void loop() { while (!client.available()) { delay(1); //delay 1 msec } // no buffering for ASCII Art Animation while (client.available()) { char c = client.read(); Serial.write(c); } /*********** if (client.available() > 0) { String line = client.readString(); // Read from the server response Serial.print(line); } ************/ }

wio-terminalのファームウェアのバージョン・アップにともない
以下のようにヘッダーが変更になっている:

//#include <AtWiFi.h> #include <rpcWiFi.h>

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32 #define M5ATOM

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char passwd[] = "yours_passwd";

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:
(M5Atomの場合、実行時にリセット・ボタンを押す必要があるようだ)

$ picocom /dev/ttyACM0 -b115200 #以下のようなAsciiArtのアニメが実行される: ........... @@@@@ @@@@@ ........... .......... @ @ @ @ .......... ........ @@@ @ @ .......... ....... @@ @ @ ......... ...... @@@@@@@ @@@@@ th ........ ..... ----------------------- ....... .... C E N T U R Y ....... ... ----------------------- ..... .. @@@@@ @@@@@ @ @ @@@@@ ... == @ @ @ @ @ == __||__ @ @@@@ @ @ __||__ | | @ @ @ @ @ | | _________|______|_____ @ @@@@@ @ @ @ _____|______|_________

platformio.ini

platformio.iniは、ボードに合わせて以下を使用する:

wio-terminalの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:seeed_wio_terminal] platform = atmelsam board = seeed_wio_terminal framework = arduino build_flags = -DWIO_TERMINAL upload_protocol = sam-ba monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = https://github.com/Seeed-Studio/Seeed_Arduino_mbedtls/archive/dev.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcUnified/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcBLE/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcWiFi/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FreeRTOS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_SFUD/archive/master.zip # https://github.com/Seeed-Studio/Seeed_Arduino_LCD/archive/master.zip

M5Atomの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 #board = esp32dev board = m5stick-c framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # use M5Atom lib 3113 # use "FastLED" 126

ESP32の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino build_flags = -DESP32 monitor_speed = 115200 lib_ldf_mode = deep+

ESP8266の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:huzzah] platform = espressif8266 #board = huzzah board = esp_wroom_02 framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+

wio-terminalのファームウェアを切り替えたときの注意

古いファームウェアのライブラリを動かした後は、古いライブラリがキャッシュで残っていると ビルド・エラーになるので以下を実行すること:

cd project_directory rm -r .pio/libdeps/seeed_wio_terminal/* rm -r .pio/build/seeed_wio_terminal/*

参考情報

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(STARWARS編)"

| | コメント (0)

2020年12月27日 (日)

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(MQTT編)

2020/12/27:
初版

board3 MQTT v2

board3 MQTT v2

概要

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(MQTT編)

本記事は「 Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(MQTT編) 」 の改版にあたり、wio-terminalのファームウェア・バージョンアップに対応している。

wio-terminalのファームウェアのアップデート方法については以下を参照のこと:
wio-terminalのファームウェア・アップデートについて(v2)(linux版)

デモ・スケッチ

src/MQTT_test.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 ////#define M5ATOM //------------------ // // MQTT program for Wio-Terminal/ESP8266/ESP32 // // Forked from the following code: //-------------------------------------------- // This example uses an Adafruit Huzzah ESP8266 // to connect to shiftr.io. // // You can check on your device after a successful // connection here: https://shiftr.io/try. // // by Joël Gähwiler // https://github.com/256dpi/arduino-mqtt //-------------------------------------------- #ifdef M5ATOM #include "M5Atom.h" #define ESP32 #endif #ifdef WIO_TERMINAL //#include <AtWiFi.h> #include <rpcWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif #include <MQTT.h> const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd"; WiFiClient net; MQTTClient client; unsigned long lastMillis = 0; void connect() { Serial.print("checking wifi..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } Serial.print("\nconnecting..."); while (!client.connect("arduino", "try", "try")) { // for "broker.shiftr.io" //while (!client.connect("arduino", "", "")) { // no username. no passwd (for "mqtt.eclipse.org") Serial.print("."); delay(1000); } Serial.println("\nconnected!"); client.subscribe("topic0"); // client.unsubscribe("/hello"); } void messageReceived(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); } void setup() { Serial.begin(115200); WiFi.begin(ssid, pass); // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino. // You need to set the IP address directly. // uncomment one of them to select MQTT server client.begin("broker.shiftr.io", net); //OK //client.begin("mqtt.eclipse.org", net); //OK //client.begin("test.mosquitto.org", net); //NG? client.onMessage(messageReceived); connect(); } void loop() { char s[100]; // buf for sprintf // dumy sensor values float pascals = 101312; float altm = 42; //m float tempC = 28.7; // deg C client.loop(); delay(10); // <- fixes some issues with WiFi stability if (!client.connected()) { connect(); } // publish a message roughly every second. if (millis() - lastMillis > 1000) { lastMillis = millis(); // publish sensor values sprintf(s,"{ \"press\" : %.2f, \"altm\" : %.1f, \"tempC\" : %.1f}", pascals/100, altm, tempC); client.publish("topic0", &s[0]); } delay(1000); }

wio-terminalのファームウェアのバージョン・アップにともない
以下のようにヘッダーが変更になっている:

//#include <AtWiFi.h> #include <rpcWiFi.h>

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32 #define M5ATOM

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd";

以下は利用するMQTTサーバー(broker)に合わせてコメントアウトする:

<省略> while (!client.connect("arduino", "try", "try")) { // for "broker.shiftr.io" //while (!client.connect("arduino", "", "")) { // no username. no passwd (for "mqtt.eclipse.org") <省略> <省略> client.begin("broker.shiftr.io", net); //OK //client.begin("mqtt.eclipse.org", net); //OK <省略>

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 Terminal ready # 実際のセンサーを接続していないので一定のダミーデータを受信する incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} ... <省略>

対向する送受信プログラム

以下をブラウザ(chromeのみ)で動かす:

MQTT_AT_webTestZero_02.html

<html> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> <body> <script> //var mqtt_url = 'ws://test.mosquitto.org:8081' //var mqtt_url = 'ws://mqtt.eclipse.org/mqtt:443' var mqtt_url = 'wss://try:try@broker.shiftr.io' document.body.innerHTML = ''; var consout = 'MQTT over WebSockets Test'+'('+mqtt_url+')<br>' document.body.innerHTML = consout; //var mqtt = require('mqtt'); var client = mqtt.connect(mqtt_url); // subscribe Topic //client.subscribe('hello'); client.subscribe('topic0'); //client.subscribe('topic0/sample/hello'); //client.subscribe('topic0/sample/#'); // wildcard topic //client.subscribe('topic0/#'); //client.subscribe('#'); client.on('message', function(topic, payload) { console.log([topic, payload].join(': ')); consout += [topic, payload].join(': ')+'<br>' document.body.innerHTML = consout // disconnect //client.end(); }); // publish messages client.publish('topic0', 'hello world of MQTT! #1'); client.publish('topic0', 'hello world of MQTT! #2'); client.publish('topic0', 'hello world of MQTT! #3'); client.publish('topic0', 'hello world of MQTT! #4'); client.publish('topic0', 'hello world of MQTT! #5'); </script> </body> </html>

以下の部分は使用しているbrokerによって変更すること:
(brokerが止まっていることがあるようなので、そのときはbrokerを変えてみる)

//var mqtt_url = 'ws://test.mosquitto.org:8081' //var mqtt_url = 'ws://mqtt.eclipse.org/mqtt:443' var mqtt_url = 'wss://try:try@broker.shiftr.io'

デモプログラムを起動後、上の「MQTT_AT_webTestZero_02.html」をプラウザーで起動すると
以下のweb画面が表示される(例):

MQTT over WebSockets Test(wss://try:try@broker.shiftr.io) topic0: hello world of MQTT! #1 topic0: hello world of MQTT! #2 topic0: hello world of MQTT! #3 topic0: hello world of MQTT! #4 topic0: hello world of MQTT! #5 topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} ...

platformio.ini

platformio.iniは、ボードに合わせて以下を使用する:

wio-terminalの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:seeed_wio_terminal] platform = atmelsam board = seeed_wio_terminal framework = arduino build_flags = -DWIO_TERMINAL upload_protocol = sam-ba monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = https://github.com/Seeed-Studio/Seeed_Arduino_mbedtls/archive/dev.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcUnified/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcBLE/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcWiFi/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FreeRTOS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_SFUD/archive/master.zip # https://github.com/Seeed-Studio/Seeed_Arduino_LCD/archive/master.zip # MQTT lib 617

M5Atomの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 #board = esp32dev board = m5stick-c framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # use M5Atom lib 3113 # use "FastLED" 126 # MQTT lib 617

ESP32の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # MQTT lib 617

ESP8266の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:huzzah] platform = espressif8266 #board = huzzah board = esp_wroom_02 framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # MQTT lib 617

wio-terminalのファームウェアを切り替えたときの注意

古いファームウェアのライブラリを動かした後は、古いライブラリがキャッシュで残っていると ビルド・エラーになるので以下を実行すること:

cd project_directory rm -r .pio/libdeps/seeed_wio_terminal/* rm -r .pio/build/seeed_wio_terminal/*

参考情報

https://docs.shiftr.io/interfaces/mqtt/

The following ports are available on the broker.shiftr.io host: MQTT MQTTS MQTTWS MQTTWSS 1883 8883 80 443

MQTT test server @mosquitto.org

https://test.mosquitto.org/ The server listens on the following ports: 1883 : MQTT, unencrypted 8883 : MQTT, encrypted 8884 : MQTT, encrypted, client certificate required 8080 : MQTT over WebSockets, unencrypted 8081 : MQTT over WebSockets, encrypted websocketで使用するurlは以下になる: 'ws://test.mosquitto.org:8081'

MQTT test server @eclipse.org

http://mqtt.eclipse.org/ This is a public test MQTT broker service. It currently listens on the following ports: 1883 : MQTT over unencrypted TCP 8883 : MQTT over encrypted TCP 80 : MQTT over unencrypted WebSockets (note: URL must be /mqtt ) 443 : MQTT over encrypted WebSockets (note: URL must be /mqtt ) websocketで使用するurlは以下になる: 'ws://mqtt.eclipse.org/mqtt:443'

10 Free Public & Private MQTT Brokers(For Testing & Production)

PlatformIO Core (CLI)

ESP-WROOM-02ボードでMQTTとMPL3115A2(気圧・高度・気温センサ)を動かす(Arduino版)
本記事のスケッチは、この記事のスケッチとほとんど同じであるので参考にできる。

以上

続きを読む "Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(MQTT編)"

| | コメント (0)

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(REST-API編)

2020/12/27+
初版

board3 REST API v2

board3 REST API v2

概要

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(REST-API編)
本記事は「 Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API編)」 の改版にあたり、wio-terminalのファームウェア・バージョンアップに対応している。

wio-terminalのファームウェアのバージョンアップで以下の不具合も解消している。

Wio-Terminalの場合、REST-APIは、起動後の1回しか動作しなかった。(原因不明)

wio-terminalのファームウェアのアップデート方法については以下を参照のこと:
wio-terminalのファームウェア・アップデートについて(v2)(linux版)

デモ・スケッチ

src/REST-API_test.ino

// select board ////#define M5ATOM ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 //------------------ // REST-API server for Wio-Terminal/ESP8266/ESP32 /* * Forked from the following code: * * Simple hello world Json REST response * by Mischianti Renzo <https://www.mischianti.org> * * https://www.mischianti.org/ * */ #ifdef M5ATOM #include "M5Atom.h" #define ESP32 #endif #ifdef WIO_TERMINAL //#include <AtWiFi.h> #include <rpcWiFi.h> #include <WebServer.h> #include <WiFiUdp.h> #include <ArduinoMDNS.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #endif #ifdef ESP32 #include <WiFi.h> #include <WebServer.h> #include <ESPmDNS.h> #endif const char* ssid = "<your-ssid>"; const char* password = "<your-passwd>"; #ifdef WIO_TERMINAL WiFiUDP udp; MDNS mdns(udp); WebServer server(80); #endif #ifdef ESP8266 ESP8266WebServer server(80); #endif #ifdef ESP32 WebServer server(80); #endif // Serving Hello world void getHelloWord() { server.send(200, "text/json", "{\"name\": \"Hello world\"}\r\n"); } void ledOff() { // do something for LED off server.send(200, "text/json", "{\"led\": \"OFF\"}\r\n"); } void ledOn() { // do something for LED on server.send(200, "text/json", "{\"led\": \"ON\"}\r\n"); } // Define routing void restServerRouting() { server.on("/", HTTP_GET, []() { server.send(200, F("text/html"), F("Welcome to the REST Web Server")); }); server.on(F("/helloWorld"), HTTP_GET, getHelloWord); server.on(F("/api/v1/led=0"), HTTP_GET, ledOff); server.on(F("/api/v1/led=1"), HTTP_GET, ledOn); } // Manage not found URL void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void setup(void) { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Activate mDNS this is used to be able to connect to the server // with local DNS hostmane esp8266.local #ifdef WIO_TERMINAL mdns.begin(WiFi.localIP(), "wiot"); Serial.println("MDNS responder started(wiot)"); #endif #ifdef ESP8266 if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started(esp8266)"); } #endif #ifdef ESP32 if (MDNS.begin("esp32")) { Serial.println("MDNS responder started(esp32)"); } #endif // Set server routing restServerRouting(); // Set not found response server.onNotFound(handleNotFound); // Start server server.begin(); Serial.println("HTTP server started"); } void loop(void) { #ifdef WIO_TERMINAL mdns.run(); // This actually runs the mDNS module. YOU HAVE TO CALL THIS PERIODICALLY #endif #ifdef ESP8266 MDNS.update(); #endif #ifdef ESP32 //MDNS.update(); // no need to update on ESP32 #endif server.handleClient(); }

wio-terminalのファームウェアのバージョン・アップにともない
以下のようにヘッダーが変更になっている:

//#include <AtWiFi.h> #include <rpcWiFi.h>

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32 #define M5ATOM

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd";

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 # ESP8266の場合 ... Connected to xxxxxxxx IP address: 192.168.0.5 MDNS responder started(esp8266) HTTP server started # M5Atom/ESP32の場合 .. Connected to xxxxxxxx IP address: 192.168.0.15 MDNS responder started(esp32) HTTP server started # Wio-Terminalの場合 .. Connected to xxxxxxxx IP address: 192.168.0.15 MDNS responder started(wiot) HTTP server started

curlによるコマンド実行例:

# ESP8266の場合 $ curl 'http://esp8266.local:80/helloWorld' {"name": "Hello world"} $ curl 'http://esp8266.local:80/api/v1/led=1' {"led": "ON"} $ curl 'http://esp8266.local:80/api/v1/led=0' {"led": "OFF"} # ESP32の場合 $ curl 'http://esp32.local:80/helloWorld' {"name": "Hello world"} $ curl 'http://esp32.local:80/api/v1/led=0' {"led": "OFF"} $ curl 'http://esp32.local:80/api/v1/led=1' {"led": "ON"} # wio-terminalの場合 $ curl 'http://wiot.local:80/helloWorld' {"name": "Hello world"} $ curl 'http://wiot.local:80/api/v1/led=0' {"led": "OFF"} $ curl 'http://wiot.local:80/api/v1/led=1' {"led": "ON"}

mDNSによる名前解決には時間がかかることがあるので その場合、IPアドレスでアクセスすること。
また、M5Atomの場合、プログラム起動後、リセットボタンを押す必要があるようだ。

platformio.ini

platformio.iniは、ボードに合わせて以下を使用する:

wio-terminalの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:seeed_wio_terminal] platform = atmelsam board = seeed_wio_terminal framework = arduino build_flags = -DWIO_TERMINAL upload_protocol = sam-ba monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = https://github.com/Seeed-Studio/Seeed_Arduino_mbedtls/archive/dev.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcUnified/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcBLE/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcWiFi/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FreeRTOS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_SFUD/archive/master.zip # https://github.com/Seeed-Studio/Seeed_Arduino_LCD/archive/master.zip # # mDNS lib "ArduinoMDNS" 2848

M5Atomの場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 #board = esp32dev board = m5stick-c framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # use M5Atom lib 3113 # use "FastLED" 126

ESP32の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino build_flags = -DESP32 monitor_speed = 115200 lib_ldf_mode = deep+

ESP8266の場合:

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:huzzah] platform = espressif8266 #board = huzzah board = esp_wroom_02 framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+

wio-terminalのファームウェアを切り替えたときの注意

古いファームウェアのライブラリを動かした後は、古いライブラリがキャッシュで残っていると ビルド・エラーになるので以下を実行すること:

cd project_directory rm -r .pio/libdeps/seeed_wio_terminal/* rm -r .pio/build/seeed_wio_terminal/*

参考情報

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(REST-API編)"

| | コメント (0)

2020年12月26日 (土)

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(OSC編)

2020/12/26+
初版

board3 OSC v2

board3 OSC v2

概要

Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(OSC編)
本記事は「Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(OSC編)」の改版にあたる。wio-terminalのWiFi/BLEファームウェアがバージョンアップしたので、それの対応方法を記載した。これにより、wio-terminalの古いファームウェアで原因不明で動作しなかったOSC受信が動作するようになった。

wio-terminalのファームウェアのアップデート方法については以下を参照のこと:
wio-terminalのファームウェア・アップデートについて(v2)(linux版)

OSCcodecライブラリ

OSC_codecライブラリとしてプロジェクトのsrcディレクトリに以下の2つのファイルを置く:

src/OSCmsgCodec.h

// OSC message Codec Header // 2013/10/28 #ifndef _OSCMSGCODEC_H #define _OSCMSGCODEC_H #include <string.h> int encOSCmsg(char *packet , union OSCarg *msg); // makes packet from OSC message and returns packet size void decOSCmsg(char *packet , union OSCarg *msg); // makes OSC message from packet union OSCarg { // char*, int and float are assumed four bytes char *address; char *typeTag; long int i; // int32 for Arduino(16bits) float f; char *s; struct { long int len; // is "int i" char *p; } blob; char m[4]; // for MIDI char _b[4]; // endian conversion temp variable }; #endif // _OSCMSGCODEC_H

src/OSCmsgCodec.cpp

/* <---------------------------------------------------------------------------------- OSC message Codec(encoder/decoder) version: 1.3 (2014/ 8/31) encoder bufix(enoceder returns byte length) version: 1.2 (2014/ 8/30) decoder bufix version: 1.1 (2013/11/20) support BIG_ENDIAN by #define version: 1.0 (2013/11/10) Copyright (C) 2011,2013,2014 S.Komatsu released under the MIT License: http://mbed.org/license/mit please refer to: http://opensoundcontrol.org/introduction-osc for OSC(Open Sound Control) The followings are supported: Features: Packet Parsing (Client) Packet Construction (Server) Bundle NOT Support Timetag NOT Support Type Support: i: int32 b: blob s: string f: float32 m: MIDI message(port id, status byte, data1, data2) // I don't know the detail Change Log: Bug(string length is not correct in encoding) Fix on 2013/11/10 (v0.9 -> v1.0) >---------------------------------------------------------------------------------- */ #include "OSCmsgCodec.h" //#define BIG_ENDIAN int lenAlign4B(int len) { if ((len % 4) == 0) {return len; } else {return len+4-(len % 4);} } int encOSCmsg(char *packet , union OSCarg *msg){ // *** important notice *** // output buffer must be cleared before call this char *p, *s, *d, *typeTag; char c; p=packet; d=p; s=msg[0].address; // address for(int i=0; i<strlen(msg[0].address); i++) *d++ = *s++; *d=0; // terminator // p += 4*((strlen(msg[0].address)+1)/4+1); p += lenAlign4B(strlen(msg[0].address)+1); // s=msg[1].typeTag; d=p; for(int i=0; i<strlen(msg[1].typeTag); i++) *d++ = *s++; *d=0; // terminator // p += 4*((strlen(msg[1].s)+1)/4+1); p += lenAlign4B(strlen(msg[1].typeTag)+1); // typeTag=msg[1].s+1; // skip ',' for(int n=0; n<strlen(typeTag); n++){ c = typeTag[n]; if (('s'==c)) { s=msg[n+2].s; d=p; for(int i=0; i<strlen(msg[n+2].s); i++) *d++ = *s++; *d=0; // terminater // p += 4*((strlen(msg[n+2].s)+1)/4+1); p += lenAlign4B(strlen(msg[n+2].s)+1); } else if (('i'==c)||('f'==c)) { #ifdef BIG_ENDIAN // no change endian (big to big) p[0]=msg[n+2]._b[0]; p[1]=msg[n+2]._b[1]; p[2]=msg[n+2]._b[2]; p[3]=msg[n+2]._b[3]; #else // change endian (little to big) p[0]=msg[n+2]._b[3]; p[1]=msg[n+2]._b[2]; p[2]=msg[n+2]._b[1]; p[3]=msg[n+2]._b[0]; #endif p +=4; } else if ('b'==c) { // put length of blog #ifdef BIG_ENDIAN // no change endian (big to big) p[0]=msg[n+2]._b[0]; p[1]=msg[n+2]._b[1]; p[2]=msg[n+2]._b[2]; p[3]=msg[n+2]._b[3]; #else // change endian (little to big) p[0]=msg[n+2]._b[3]; p[1]=msg[n+2]._b[2]; p[2]=msg[n+2]._b[1]; p[3]=msg[n+2]._b[0]; #endif p +=4; // get ponter of blog (copy to msg[n].blog.p) s=msg[n+2].blob.p; d=p; for(int i=0; i<msg[n+2].blob.len; i++) *d++ = *s++; p += 4*(msg[n+2].blob.len/4+1); } else if ('m'==c) { // get midi data (copy to msg[n].m[]) p[0]=msg[n+2].m[0]; p[1]=msg[n+2].m[1]; p[2]=msg[n+2].m[2]; p[3]=msg[n+2].m[3]; p +=4; } else { //printf("*** Not Supported TypeTag:%s ****\n",typeTag); } }; //return (p-packet); // return packet size // bugfix 2014/8/31 return sizeof(char)*(p-packet); // return byte length }; void decOSCmsg(char *packet , union OSCarg *msg){ // Caution: the returned result points to packet as blobs or strings (not newly allocatd) char *p, *typeTag; char c; int n; msg[0].address = packet; // address msg[1].typeTag = packet+4*((strlen(msg[0].s)+1)/4+1);//typeTag typeTag=msg[1].s+1; // skip ',' // bugfix 2014/8/30 if (strlen(typeTag)%2 == 0) p= msg[1].s+4*((strlen(msg[1].s)+1)/4); else p= msg[1].s+4*((strlen(msg[1].s)+1)/4+1); for(n=0; n<strlen(typeTag); n++){ c = typeTag[n]; if (('s'==c)) { msg[n+2].s=p; //p += 4*((strlen(msg[n+2].s)+1)/4+1); p += lenAlign4B(strlen(msg[n+2].s)+1); } else if (('i'==c)||('f'==c)) { #ifdef BIG_ENDIAN // no change endian (big to big) msg[n+2]._b[0]=p[0]; msg[n+2]._b[1]=p[1]; msg[n+2]._b[2]=p[2]; msg[n+2]._b[3]=p[3]; #else // change endian (big to little) msg[n+2]._b[3]=p[0]; msg[n+2]._b[2]=p[1]; msg[n+2]._b[1]=p[2]; msg[n+2]._b[0]=p[3]; #endif p +=4; } else if ('b'==c) { // get lenth of blog (copy to msg[n].blog.len) #ifdef BIG_ENDIAN // no change endian (big to big) msg[n+2]._b[0]=p[0]; msg[n+2]._b[1]=p[1]; msg[n+2]._b[2]=p[2]; msg[n+2]._b[3]=p[3]; #else // change endian (big to little) msg[n+2]._b[3]=p[0]; msg[n+2]._b[2]=p[1]; msg[n+2]._b[1]=p[2]; msg[n+2]._b[0]=p[3]; #endif p +=4; // get ponter of blog (copy to msg[n].blog.p) msg[n+2].blob.p=p; //p += 4*(msg[n+2].blob.len/4+1); p += lenAlign4B(msg[n+2].blob.len+1); } else if ('m'==c) { // get midi data (copy to msg[n].m[]) msg[n+2].m[0]=p[0]; msg[n+2].m[1]=p[1]; msg[n+2].m[2]=p[2]; msg[n+2].m[3]=p[3]; p +=4; } else { //printf("*** Not Supported TypeTag:%s ****\n",typeTag); } }; };

デモ・スケッチ

src/main.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 ////#define M5ATOM /* OSC sender/receiver Forked for Wio-Terminal/ESP8266(ESP-WROOM-02)/ESP32 from: This sketch sends random data over UDP on a ESP32 device */ #ifdef M5ATOM #include "M5Atom.h" #define ESP32 #endif #ifdef WIO_TERMINAL //#include <AtWiFi.h> #include <rpcWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif #include <WiFiUdp.h> // WiFi network name and password: const char* ssid = "your-ssid"; const char* passwd = "your-password"; //IP address to send UDP data to: const char* udpAddress = "192.168.0.18"; // target IP const int udpInPort = 8000; // incomming port const int udpOutPort = 9000; // outgoing port //<<<<<<<<<<<<<<<<<<<<< // OSC related #include "OSCmsgCodec.h" #define PACKET_SIZE 512 #define RECBUF_SIZE 256 union OSCarg msg[10], outmsg[10]; char buff[PACKET_SIZE],packet[PACKET_SIZE]; //>>>>>>>>>>>>>>>>>>>> char recbuf[128]; // buffer for incoming packets //The udp library class WiFiUDP udp; void setup() { Serial.begin(115200); Serial.println("OSC test program start..."); Serial.println(""); // delete old config WiFi.disconnect(true); Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, passwd); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" connected"); udp.begin(udpInPort); Serial.printf("Now listening at IP %s, UDP port %d\r\n", WiFi.localIP().toString().c_str(), udpInPort); } void loop() { int packetSize = udp.parsePacket(); if (packetSize>0) { Serial.printf("Received %d bytes from %s, port %d\r\n", packetSize, udp.remoteIP().toString().c_str(), udpInPort); int len = udp.read(recbuf, 128); if (len > 0) { decOSCmsg(recbuf, msg); Serial.printf("incomming OSC msg:\r\n%s %s", msg[0].address, msg[1].typeTag); for(int m=0; m < (strlen(msg[1].typeTag)-1); m++) { if (msg[1].typeTag[m+1]=='f') Serial.printf(" %f",msg[m+2].f); if (msg[1].typeTag[m+1]=='i') Serial.printf(" %d",msg[m+2].i); }; Serial.printf("\r\n"); Serial.printf("-------------------\r\n"); } } else { // test send // fader // send OSC message with random values (to touchOSC) // make OSC message for sending outmsg[0].address="/1/fader5"; outmsg[1].typeTag=",f"; outmsg[2].f= rand()%1000/1000.0; memset(packet,0,sizeof(packet)); // clear send buff for OSC msg int plen=encOSCmsg(packet,outmsg); // send it // Send a packet udp.beginPacket(udpAddress, udpOutPort); udp.write((const uint8_t*)packet, plen); udp.endPacket(); // //Serial.print("."); // indicate sending packet //Wait delay(10); // seems 'must' (for platformio) } }

wio-terminalのファームウェアのバージョン・アップにともない 以下のようにヘッダーが変更になっている:

//#include <AtWiFi.h> #include <rpcWiFi.h>

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32 #define M5ATOM

以下については、自分の環境に合わせて変更すること:

// WiFi network name and password: const char* ssid = "your_ssid"; const char* passwd = "your_passwd"; //IP address to send UDP data to: const char* udpAddress = "192.168.0.18"; // target IP const int udpInPort = 8000; // incomming port const int udpOutPort = 9000; // outgoing port

udpAddressは、対向するOSC受信デバイス(touchOSCなど)のIPを設定する。

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 ........... connected Now listening at IP 192.168.0.11, UDP port 8000

上の例ではTouchOSCから192.168.0.11:8000へOSCパッケットに送る(ようにTouchOSCを設定する)。

または、動作としては、touchOSCのsimpleレイアウトの画面で、最上行の受信アイコンがOSCを受信すると「赤」になり、fader5のfaderが送られてきたOSCの内容に従ってランダムに変化する。

platformio.ini

platformio.iniは、ボードに合わせて以下を使用する:

wio-terminalの場合

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:seeed_wio_terminal] platform = atmelsam board = seeed_wio_terminal framework = arduino build_flags = -DWIO_TERMINAL upload_protocol = sam-ba monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = https://github.com/Seeed-Studio/Seeed_Arduino_mbedtls/archive/dev.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcUnified/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcBLE/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_rpcWiFi/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FreeRTOS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_FS/archive/master.zip https://github.com/Seeed-Studio/Seeed_Arduino_SFUD/archive/master.zip # https://github.com/Seeed-Studio/Seeed_Arduino_LCD/archive/master.zip #

M5Atomの場合

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 #board = esp32dev board = m5stick-c framework = arduino monitor_speed = 115200 lib_ldf_mode = deep+ lib_deps = # use M5Atom lib 3113 # use "FastLED" 126

ESP32の場合

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:esp32dev] platform = espressif32 board = esp32dev framework = arduino

ESP8266の場合

; PlatformIO Project Configuration File ; ; Build options: build flags, source filter ; Upload options: custom upload port, speed and extra flags ; Library options: dependencies, extra library storages ; Advanced options: extra scripting ; ; Please visit documentation for the other options and examples ; https://docs.platformio.org/page/projectconf.html [env:huzzah] platform = espressif8266 #board = huzzah board = esp_wroom_02 framework = arduino

wio-terminalのファームウェア切り替えたときの注意

古いファームウェアのライブラリを動かした後は、古いライブラリがキャッシュで残っていると ビルド・エラーになるので以下を実行すること:

cd project_directory rm -r .pio/libdeps/seeed_wio_terminal/* rm -r .pio/build/seeed_wio_terminal/*

参考情報

TouchOSC - Modular touch control surface for OSC & MIDI
TouchOSC - iPhone
TouchOSC - Android

OSCmsgCode lib:
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//raw-file/e62251d890c1/OSCmsgCodec.h
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//raw-file/e62251d890c1/OSCmsgCodec.cpp
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//file/e62251d890c1/main.cpp/

Platform/Wio Terminal Network/Wi-Fi - example sketches

Wio Terminalをはじめよう(ピン配置、データシート、回路図など)

PlatformIO Core (CLI)

old version:
Wio-TerminalでWiFiで使う(その4:OSC)

以上

続きを読む "Wio-Terminal/M5Atom/ESP8622/ESP32ボードを共通のスケッチで動かす(v2)(OSC編)"

| | コメント (0)

2020年8月15日 (土)

XIAOにWiFiモジュールを接続する(STARWARS)

2020/8/16:
接続、スケッチ改版

2020/8/15:
初版

PlatformIO XIAO WiFi-module

PlatformIO XIAO WiFi-module

概要

XIAOに以下のWiFiモジュールを接続する(STARWARS)
本記事は 「XIAOを使ってWiFiモジュール(ESP-WROOM-02)の動作確認をする」の続きになる。
(ホストPCとしてはubuntuを想定している)

ESP-WROOM-02開発ボード(AE-ESP-WROOM02-DEV)
このボードには出荷時にATファームウェアが書き込まれている。(WiFiモジュールとして使用する場合、Arduinoのファームなどを書き込まない)

接続

ESP-WROOM-02開発ボード(AE-ESP-WROOM02-DEV)の場合

AE-ESP-WROOM02-DEV XIAO
1(3V3入力) USB給電の場合、接続しない
2(EN) D8
14(TXD) D7(RX)
13(RXD) D6(TX)
9(GND) GND

USB給電の場合は、オンボードのUSBにホストPCなどを接続して行なう。(USBシリアルとしては使用しない)
XIAOのUSBシリアルして使用するので、XIOAのUSBはホストPCに接続して通信ソフトを起動する。

starwars_test

telnetでASCIIアートの「StarWars」アニメを表示するプログラム:
src/starwars_test.ino

// set your wifi ssid, passwd #define MY_SSID "your_ssid" #define MY_PASSWD "your_passwd" #define esp8266_reset_pin 8 // Connect this pin to CH_PD(chip power-down) on the esp8266, not reset. char res[6000]; // need big buffer for StarWars bool printReply = true; const char Hline[] = "-----\n\r"; char ipAddress [20]; void getReply(int wait) { int tempPos = 0; long int time = millis(); while( (time + wait) > millis()) { while(Serial1.available()>0) { char c = Serial1.read(); //if (tempPos < 500) { res[tempPos] = c; tempPos++; } res[tempPos] = c; tempPos++; } res[tempPos] = 0; } if (printReply) { Serial.println( res ); Serial.println(Hline); } } void setup() { // **** we need chip rest **** pinMode(esp8266_reset_pin, OUTPUT); digitalWrite(esp8266_reset_pin, LOW);//Start with radio off //delay(500); delay(1000); digitalWrite(esp8266_reset_pin, HIGH); // select the radio // **** end of chip rest **** // serials init while (!Serial); while (!Serial1); Serial.begin(115200); //serial port of Arduino Main Serial1.begin(115200); //serial port of ESP8266 delay(3000); //Serial.print("Type a key to start.\r\n"); //while(!Serial.available()) continue; // wait for some input //pinMode(LED_BUILTIN, OUTPUT); //delay(3000); Serial.print("\r\n\r\n\r\n\r\n\r\n"); // no need rest command /********* Serial1.print("AT+RST\r\n"); getReply(2000); ***********/ Serial1.print("AT+GMR\r\n"); getReply(2000); Serial1.print("AT+CWQAP\r\n"); getReply(2000); Serial1.print("AT+CWMODE=1\r\n"); getReply(2000); // set your own wifi Serial1.printf("AT+CWJAP=\"%s\",", MY_SSID); Serial1.printf("\"%s\"\r\n", MY_PASSWD); getReply(10000); Serial1.print("AT+CIFSR\r\n"); getReply(10000); //-- get IP Address -- int len = strlen( res ); bool done=false; bool error = false; int pos = 0; while (!done) { if ( res[pos] == '\"') { done = true;} pos++; if (pos > len) { done = true; error = true;} } if (!error) { int buffpos = 0; done = false; while (!done) { if ( res[pos] == '\"' ) { done = true; } else { ipAddress[buffpos] = res[pos]; buffpos++; pos++; } } ipAddress[buffpos] = 0; } else { strcpy(ipAddress,"ERROR"); } Serial.printf("ipAddress:%s\r\n\r\n",ipAddress); Serial1.print("AT+CIPMUX=1\r\n"); getReply( 1500 ); Serial1.print("AT+CIPSERVER=1,80\r\n"); getReply( 1500 ); // display off printReply = false; // telnet access //Serial.print("AT+CIPSTART=1,\"TCP\",\"towel.blinkenlights.nl\",23\r\n"); //Serial1.print("AT+CIPSTART=1,\"TCP\",\"towel.blinkenlights.nl\",23\r\n"); // do this if DNS fail Serial.print("AT+CIPSTART=1,\"TCP\",\"94.142.241.111\",23\r\n"); Serial1.print("AT+CIPSTART=1,\"TCP\",\"94.142.241.111\",23\r\n"); } //------------------------------------------------------- void get_res(void) { int cpos = 0; for(int cc=0; cc<24000000; cc++) { while (Serial1.available()) { res[cpos] = (char)Serial1.read(); cpos++; }; }; res[cpos] = 0; } void get_res2(void) { int cpos = 0; for(int cc=0; cc<500000; cc++) { while (Serial1.available()) { res[cpos] = (char)Serial1.read(); cpos++; }; }; res[cpos] = 0; } //------------------------------------------------------- void dispatch(void) { // setup string pointer table char *h[20]; for(int i=0; i<20; i++) h[i]=NULL; h[0] = &res[0]; int pi = 1; int cp; int len = (int)strlen(res); // keep length of res[] for (int i=0; i<len; i++) { if ((res[i]=='+') && (res[i+1]=='I') && (res[i+2]=='P') && (res[i+3]=='D') ) { // check +IPD //for (cp = i+3; cp<len; cp++) { for (cp = i+4; cp<len; cp++) { if (res[cp]==':') break; } res[i] = 0; // make string terminator h[pi] = &res[cp+1]; pi++; } }; // display removed IPD header for(int i=0; i<20; i++) { if (h[i] != NULL) Serial.print(h[i]); } } //------------ void loop() { digitalWrite(LED_BUILTIN, HIGH); // debug: for indicate in-loop /** // test loop while(true) { if (Serial1.available()) Serial.write((char)Serial1.read()); if (Serial.available()) Serial1.write((char)Serial.read()); }; **/ while(true) { get_res2(); //getReply(1000); if ((int)strlen(res) != 0) { //usart0_print("\r\nRES:\r\n"); //usart0_println(res); dispatch(); } else { //usart0_print("."); // indicating input wait } } }

以下については、自分の環境に合わせて変更すること:
#define MY_SSID "your_ssid"
#define MY_PASSWD "your_passwd"

書き込み後に「picocom /dev/ttyACM0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 AT+GMR AT version:1.7.4.0(May 11 2020 19:13:04) SDK version:3.0.4(9532ceb) compile time:May 27 2020 10:12:20 Bin version(Wroom 02):1.7.4 OK WIFI GOT IP ----- AT+CWQAP OK WIFI DISCONNECT ----- AT+CWMODE=1 OK ----- AT+CWJAP="YOUR_SSID","YOUR_PASSWD" WIFI CONNECTED WIFI GOT IP OK ----- AT+CIFSR +CIFSR:STAIP,"192.168.0.19" +CIFSR:STAMAC,"84:f3:eb:87:14:72" OK <省略> # STARWARSのASCIIアートのアニメが表示される

実行するとStarWarsのASCIIアートのアニメが表示される。

参考情報

PlatformIO Core (CLI)

ESP8266をTCPサーバとTCPクライアントにするATコマンド実例 (1/4)
esp8266_at_command_examples_en.pdf

ESP8266をWifiモデムとして使う - ATコマンドによるMQTT通信
MQTT_via_ESP01
Arduino WiFi library for ESP8266 modules

espressif/ESP8266_AT - examples
Espressif Documentation

「wio lite RISC-V」による実装例:
Wio_Lite_RISC-VボードでWiFiを動かす(その4:MQTT)
Wio_Lite_RISC-VボードでWiFiを動かす(その3:OSC)
Wio_Lite_RISC-VボードでWiFiを動かす(その2:STARWARS,REST-API)
Wio_Lite_RISC-VボードでWiFiを動かす
開発ツールPlatformIOをcliで使う(Wio_Lite_RISC-V版)

以上

続きを読む "XIAOにWiFiモジュールを接続する(STARWARS)"

| | コメント (0)

2020年8月 3日 (月)

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチでWorld Time APIを使う(WorldTimeAPI編)

2020/8/3:
初版

board3 HTTP/JSON

board3 HTTP/JSON

概要

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチでWorld Time APIを使う(WorldTimeAPI編)
本スケッチは、httpアクセスとJSONライブラリを使用してWorldTimeAPIを利用している。
(ホストPCとしてはubuntuを想定している)

外部ライブラリ(platformioの場合)

以下を実行してライブラリをインストールする:

# JSON lib インストール #pio lib install "ArduinoJson" pio lib install 64

または、platformio.iniに以下を追加する:

lib_deps = # use "ArduinoJson" lib 64

テスト・スケッチ

src/HTTP_JSON.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 //------------------ // // HTTP/JSON access for Wio-Terminal/ESP8266/ESP32 // #ifdef WIO_TERMINAL #include <AtWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif #include <WiFiClientSecure.h> #include <ArduinoJson.h> #define BODY_SIZE 1024 char bodyBuff[BODY_SIZE]; // Allocate the JSON document StaticJsonDocument<400> doc; // change size if error happen const char* ssid = "your_ssid"; const char* passwd = "your_passwd"; // prototype void ConvertUnixTimeToLocalTime(uint64_t unixtime, uint32_t *pyear, uint8_t *pmonth, uint8_t *pday, uint8_t *phour, uint8_t *pminute, uint8_t *psecond); char *weekday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"}; uint32_t year; uint8_t month, day, hour, minu, sec; void setup() { // Initialize serial port Serial.begin(115200); while (!Serial) continue; Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, passwd); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); Serial.println("IP address: "); Serial.println(WiFi.localIP()); } bool Http_Get_access(String host, String url, String argument){ WiFiClient client; client.setTimeout(500); const int httpPort = 80; const char* host2 = host.c_str(); if (!client.connect(host2, httpPort)) { Serial.println("connection failed"); return false; } client.print(String("GET ") + url + "?" + argument + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "User-Agent: ESP8266/1.0\r\n" + "Connection: close\r\n\r\n"); unsigned long timeout = micros(); while (client.available() == 0) { if ( micros() - timeout > 5000000) { Serial.println(">>> Client Timeout !"); client.stop(); return false; } } Serial.println("--- Header ---"); while (1) { String line = client.readStringUntil('\n'); Serial.println(line); if (line == "\r") { break; // end of header } } //Serial.println("--- Body ---"); // for debug int bc = 0; while (client.available()) { bodyBuff[bc] = client.read(); bc++; } bodyBuff[bc] = 0; //Serial.println(bodyBuff); // display body for debug return true; } void loop() { String host = "worldtimeapi.org"; String url = "/api/timezone/Asia/Tokyo"; String argument = ""; Http_Get_access( host, url, argument); Serial.println("accessed BODY:"); Serial.println(bodyBuff); // Deserialize the JSON document DeserializationError errorJson = deserializeJson(doc, bodyBuff); const char* abbreviation = doc["abbreviation"]; const char* client_ip = doc["client_ip"]; const char* datetime = doc["datetime"]; long day_of_week = doc["day_of_week"]; long day_of_year = doc["day_of_year"]; long raw_offset = doc["raw_offset"]; const char* timezone = doc["timezone"]; long unixtime = doc["unixtime"]; const char* utc_datetime = doc["utc_datetime"]; const char* utc_offset = doc["utc_offset"]; long week_number = doc["week_number"]; Serial.println(); Serial.printf("Deserialized:\r\n"); Serial.printf("abbreviation:%s\r\n",abbreviation); Serial.printf("client_ip:%s\r\n",client_ip); Serial.printf("datetime:%s\r\n",datetime); Serial.printf("day_of_week:%d\r\n",day_of_week); Serial.printf("day_of_year:%d\r\n",day_of_year); Serial.printf("raw_offset:%d\r\n",raw_offset); Serial.printf("timezone:%s\r\n",timezone); Serial.printf("unixtime:%d\r\n",unixtime); Serial.printf("utc_datetime:%s\r\n",utc_datetime); Serial.printf("utc_offset:%s\r\n",utc_offset); Serial.printf("week_number:%d\r\n",week_number); Serial.println(); // display current clock from unixtime Serial.printf("Current Time from unixtime:\r\n"); ConvertUnixTimeToLocalTime(unixtime, &year, &month, &day, &hour, &minu, &sec); Serial.printf("%4d/%02d/%02d(%s): %02d:%02d:%02d\r\n", year, month, day, weekday[day_of_week], hour, minu, sec); Serial.println(); // stop Serial.println("Done!"); delay(1000); //while(1){ //} } //<---------------------------------------------------------- // Definition of ConvertUnixTimeToLocalTime function // derived/forked from http://mrkk.ciao.jp/memorandom/unixtime/unixtime.html #define ARRAYSIZE(_arr) (sizeof(_arr) / sizeof(_arr[0])) #define TIME_OFFSET 9*60*60 #define SECONDS_IN_A_DAY (24*60*60) #define EPOCH_DAY (1969*365L + 1969/4 - 1969/100 + 1969/400 + 306) // days from 0000/03/01 to 1970/01/01 #define UNIX_EPOCH_DAY EPOCH_DAY #define YEAR_ONE 365 #define YEAR_FOUR (YEAR_ONE * 4 + 1) // it is YEAR_ONE*4+1 so the maximum reminder of day / YEAR_FOUR is YEAR_ONE * 4 and it occurs only on 2/29 #define YEAR_100 (YEAR_FOUR * 25 - 1) #define YEAR_400 (YEAR_100*4 + 1) // it is YEAR_100*4+1 so the maximum reminder of day / YEAR_400 is YEAR_100 * 4 and it occurs only on 2/29 void ConvertUnixTimeToLocalTime(uint64_t unixtime, uint32_t *pyear, uint8_t *pmonth, uint8_t *pday, uint8_t *phour, uint8_t *pminute, uint8_t *psecond) { uint32_t unixday; uint16_t year = 0; uint8_t leap = 0; uint32_t n; uint8_t month, day, weekday; uint8_t hour, minute, second; static const uint16_t monthday[] = { 0,31,61,92,122,153,184,214,245,275,306,337 }; unixtime += TIME_OFFSET; second = unixtime % 60; minute = (unixtime / 60) % 60; hour = (unixtime / 3600) % 24; unixday = (uint32_t)(unixtime / SECONDS_IN_A_DAY); weekday = (uint8_t)((unixday + 3) % 7); // because the unix epoch day is thursday unixday += UNIX_EPOCH_DAY; // days from 0000/03/01 to 1970/01/01 year += 400 * (unixday / YEAR_400); unixday %= YEAR_400; n = unixday / YEAR_100; year += n * 100; unixday %= YEAR_100; if (n == 4){ leap = 1; } else { year += 4 * (unixday / YEAR_FOUR); unixday %= YEAR_FOUR; n = unixday / YEAR_ONE; year += n; unixday %= YEAR_ONE; if (n == 4) { leap = 1; } } if (leap != 0) { month = 2; day = 29; } else { month = (unixday * 5 + 2) / 153; day = unixday - monthday[month] + 1; // month += 3; if (month > 12) { ++year; month -= 12; } } *psecond = second; *pminute = minute; *phour = hour; *pyear = year; *pmonth = month; *pday = day; } //>----------------------------------------------------------

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32

以下は、自分の環境に応じて変更する:

const char* ssid = "your_ssid"; const char* passwd = "your_passwd";

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 Terminal ready --- Header --- HTTP/1.1 200 OK Connection: close Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: * Access-Control-Expose-Headers: Cache-Control: max-age=0, private, must-revalidate Content-Length: 345 Content-Type: application/json; charset=utf-8 Cross-Origin-Window-Policy: deny Date: Mon, 03 Aug 2020 06:39:09 GMT Server: Cowboy X-Content-Type-Options: nosniff X-Download-Options: noopen X-Frame-Options: SAMEORIGIN X-Permitted-Cross-Domain-Policies: none X-Request-Id: c368a196-c927-43e2-b741-c3ab7ce11336 X-Runtime: 2ms X-Xss-Protection: 1; mode=block Via: 1.1 vegur accessed BODY: {"abbreviation":"JST","client_ip":"218.231.243.62","datetime":"2020-08-03T15:39:10.171382+09:00","day_of_week":1,"day_of_year":216,"dst":false,"dst_from":null,"dst_offset":0,"dst_until":null,"raw_offset":32400,"timezone":"Asia/Tokyo","unixtime":1596436750,"utc_datetime":"2020-08-03T06:39:10.171382+00:00","utc_offset":"+09:00","week_number":32} Deserialized: abbreviation:JST client_ip:218.231.243.62 datetime:2020-08-03T15:39:10.171382+09:00 day_of_week:1 day_of_year:216 raw_offset:32400 timezone:Asia/Tokyo unixtime:1596436750 utc_datetime:2020-08-03T06:39:10.171382+00:00 utc_offset:+09:00 week_number:32 Current Time from unixtime: 2020/08/03(Mon): 15:39:10 Done!

出力には、WorldTimeAPIで取得した時刻が出力される。

参考情報

World Time API
Simple JSON/plain-text API to obtain the current time in, and related data about, a timzone.

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(HTTP-ACCESS編)
ESP8266 Arduino CoreでGETアクセス。HTTP/HTTPS&プロクシを使ったHTTP通信
ESP8266+ArduinoでHTTPS接続

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチでWorld Time APIを使う(WorldTimeAPI編)"

| | コメント (0)

2020年7月25日 (土)

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API2編)

2020/7/25:
初版

board3 REST API 2

board3 REST API 2

概要

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API2編)
Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API編)」で、Wio-Terminalのスケッチが動作しなかったので、その代わりのスケッチを提供する。 (ホストPCとしてはubuntuを想定している)

外部ライブラリ(platformioの場合)

以下を実行してライブラリをインストールする:

# mDNS lib インストール #pio lib install "ArduinoMDNS" pio lib install 2848

デモ・スケッチ

src/REST-API2_test.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 //------------------ // REST-API server2 for Wio-Terminal/ESP8266/ESP32 /* Rest-API server Forked from arduino-esp32 on 04 July, 2018 by Elochukwu Ifediora (fedy0) */ #ifdef WIO_TERMINAL #include <AtWiFi.h> #include <WiFiUdp.h> #include <ArduinoMDNS.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #include <ESP8266mDNS.h> #endif #ifdef ESP32 #include <WiFi.h> #include <ESPmDNS.h> #endif //#define LED 2 // Set the GPIO pin where you connected your test LED // Change to your setting const char* ssid = "your_ssid"; const char* password = "your_passwd"; #ifdef WIO_TERMINAL WiFiUDP udp; MDNS mdns(udp); #endif WiFiServer server(80); void setup() { //set LED of your board //pinMode(LED, OUTPUT); Serial.begin(115200); while(!Serial); // Wait for Serial to be ready delay(1000); Serial.println(); Serial.println("Configuring access point..."); // set your SoftAP if you need //WiFi.softAP(ssid, password); //IPAddress myIP = WiFi.softAPIP(); //or // set for station mode WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } IPAddress myIP = WiFi.localIP(); Serial.println(); Serial.print("AP IP address: "); Serial.println(myIP); server.begin(); Serial.println("Server started"); // Activate mDNS this is used to be able to connect to the server // with local DNS hostmane esp8266.local etc #ifdef WIO_TERMINAL mdns.begin(WiFi.localIP(), "wiot"); Serial.println("MDNS responder started(wiot)"); #endif #ifdef ESP8266 if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started(esp8266)"); } #endif #ifdef ESP32 if (MDNS.begin("esp32")) { Serial.println("MDNS responder started(esp32)"); } #endif } void loop() { WiFiClient client = server.available(); // listen for incoming clients if (client) { // if you get a client, Serial.println("New Client."); // print a message out the serial port String currentLine = ""; // make a String to hold incoming data from the client while (client.connected()) { // loop while the client's connected if (client.available()) { // if there's bytes to read from the client, char c = client.read(); // read a byte, then /////Serial.write(c); // print it out the serial monitor if (c == '\n') { // if the byte is a newline character // if the current line is blank, you got two newline characters in a row. // that's the end of the client HTTP request, so send a response: if (currentLine.length() == 0) { // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK) // and a content-type so the client knows what's coming, then a blank line: ////client.println("HTTP/1.1 200 OK"); ////client.println("Content-type:text/html"); ////client.println(); // the content of the HTTP response follows the header: ////client.print("Click <a href=\"/H\">here</a> to turn ON the LED.<br>"); ////client.print("Click <a href=\"/L\">here</a> to turn OFF the LED.<br>"); // The HTTP response ends with another blank line: client.println(); // break out of the while loop: break; } else { // if you got a newline, then clear currentLine: currentLine = ""; } } else if (c != '\r') { // if you got anything else but a carriage return character, currentLine += c; // add it to the end of the currentLine } // Check to see if the client request was "GET /H" or "GET /L": //if (currentLine.endsWith("GET /H")) { if (currentLine.endsWith("/H")) { //digitalWrite(LED, HIGH); // GET /H turns the LED on Serial.println("****ON****"); currentLine =""; client.println("{ \"LED\" : \"on\" }"); } //if (currentLine.endsWith("GET /L")) { if (currentLine.endsWith("/L")) { //digitalWrite(LED, LOW); // GET /L turns the LED off Serial.println("****OFF****"); currentLine =""; client.println("{ \"LED\" : \"off\" }"); } if (currentLine.endsWith("/api/v1/led=1")) { //digitalWrite(LED, HIGH); Serial.println("led: ON"); currentLine =""; client.println("{ \"LED\" : \"on\" }"); } if (currentLine.endsWith("/api/v1/led=0")) { //digitalWrite(LED, LOW); Serial.println("led: OFF"); currentLine =""; client.println("{ \"LED\" : \"off\" }"); } } } // close the connection: client.stop(); Serial.println("Client Disconnected."); } #ifdef WIO_TERMINAL mdns.run(); // This actually runs the mDNS module. YOU HAVE TO CALL THIS PERIODICALLY #endif #ifdef ESP8266 MDNS.update(); #endif #ifdef ESP32 //MDNS.update(); // no need to update on ESP32 #endif }

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd";

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 # ESP8266の場合 Configuring access point... ............ AP IP address: 192.168.0.5 Server started MDNS responder started(esp8266) # ESP32の場合 Configuring access point... .. AP IP address: 192.168.0.15 Server started MDNS responder started(esp32) # Wio-Terminalの場合 Configuring access point... .............. AP IP address: 192.168.0.29 Server started MDNS responder started(wiot)

curlによるコマンド実行例:

# ESP8266の場合 $ curl 'http://esp8266.local:80/api/v1/led=1' {"LED": "on"} $ curl 'http://esp8266.local:80/api/v1/led=0' {"LED": "off"} # ESP32の場合 $ curl 'http://esp32.local:80/api/v1/led=0' {"LED": "off"} $ curl 'http://esp32.local:80/api/v1/led=1' {"LED": "on"} #Wio-Terminalの場合 $ curl 'http://192.168.0.29:80/api/v1/led=0' { "LED" : "off" } $ curl 'http://192.168.0.29:80/api/v1/led=1' { "LED" : "on" } $ curl 'http://wiot.local:80/api/v1/led=0' curl: (6) Could not resolve host: wiot.local

不具合

mDNSが動作していないので、wiot.localではなく、IPアドレスでアクセスすることになる。(原因不明)

Arduino-IDEのボードマネージャーのURL

以下のURLを設定することで3つのボード(Wio-Terminal/ESP8266/ESP32)が使用可能になる。

https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json http://arduino.esp8266.com/stable/package_esp8266com_index.json https://dl.espressif.com/dl/package_esp32_index.json

参考情報

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API2編)"

| | コメント (0)

2020年7月24日 (金)

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API編)

2020/7/24:
初版

board3 REST API

board3 REST API

概要

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API編)
(ホストPCとしてはubuntuを想定している)

外部ライブラリ(platformioの場合)

以下を実行してライブラリをインストールする:

# mDNS lib インストール #pio lib install "ArduinoMDNS" pio lib install 2848

デモ・スケッチ

src/REST-API_test.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 //------------------ // REST-API server for Wio-Terminal/ESP8266/ESP32 /* * Forked from the following code: * * Simple hello world Json REST response * by Mischianti Renzo <https://www.mischianti.org> * * https://www.mischianti.org/ * */ #ifdef WIO_TERMINAL #include <AtWiFi.h> #include <WebServer.h> #include <WiFiUdp.h> #include <ArduinoMDNS.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <ESP8266mDNS.h> #endif #ifdef ESP32 #include <WiFi.h> #include <WebServer.h> #include <ESPmDNS.h> #endif const char* ssid = "<your_ssid>"; const char* password = "<your_passwd>"; #ifdef WIO_TERMINAL WiFiUDP udp; MDNS mdns(udp); WebServer server(80); #endif #ifdef ESP8266 ESP8266WebServer server(80); #endif #ifdef ESP32 WebServer server(80); #endif // Serving Hello world void getHelloWord() { server.send(200, "text/json", "{\"name\": \"Hello world\"}\r\n"); } void ledOff() { // do something for LED off server.send(200, "text/json", "{\"led\": \"OFF\"}\r\n"); } void ledOn() { // do something for LED on server.send(200, "text/json", "{\"led\": \"ON\"}\r\n"); } // Define routing void restServerRouting() { server.on("/", HTTP_GET, []() { server.send(200, F("text/html"), F("Welcome to the REST Web Server")); }); server.on(F("/helloWorld"), HTTP_GET, getHelloWord); server.on(F("/api/v1/led=0"), HTTP_GET, ledOff); server.on(F("/api/v1/led=1"), HTTP_GET, ledOn); } // Manage not found URL void handleNotFound() { String message = "File Not Found\n\n"; message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; } server.send(404, "text/plain", message); } void setup(void) { Serial.begin(115200); WiFi.mode(WIFI_STA); WiFi.begin(ssid, password); Serial.println(""); // Wait for connection while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.print("Connected to "); Serial.println(ssid); Serial.print("IP address: "); Serial.println(WiFi.localIP()); // Activate mDNS this is used to be able to connect to the server // with local DNS hostmane esp8266.local #ifdef WIO_TERMINAL mdns.begin(WiFi.localIP(), "wiot"); Serial.println("MDNS responder started(wiot)"); #endif #ifdef ESP8266 if (MDNS.begin("esp8266")) { Serial.println("MDNS responder started(esp8266)"); } #endif #ifdef ESP32 if (MDNS.begin("esp32")) { Serial.println("MDNS responder started(esp32)"); } #endif // Set server routing restServerRouting(); // Set not found response server.onNotFound(handleNotFound); // Start server server.begin(); Serial.println("HTTP server started"); } void loop(void) { #ifdef WIO_TERMINAL mdns.run(); // This actually runs the mDNS module. YOU HAVE TO CALL THIS PERIODICALLY #endif #ifdef ESP8266 MDNS.update(); #endif #ifdef ESP32 //MDNS.update(); // no need to update on ESP32 #endif server.handleClient(); }

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd";

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 # ESP8266の場合 ... Connected to xxxxxxxx IP address: 192.168.0.5 MDNS responder started(esp8266) HTTP server started # ESP32の場合 .. Connected to xxxxxxxx IP address: 192.168.0.15 MDNS responder started(esp32) HTTP server started # Wio-Terminalの場合 Terminal ready No ACK, R00 Device reset detected! ESP-AT Lib initialized! .................. Connected to xxxxxxxx IP address: 192.168.0.29 MDNS responder started(wiot) HTTP server started

curlによるコマンド実行例:

# ESP8266の場合 $ curl 'http://esp8266.local:80/helloWorld' {"name": "Hello world"} $ curl 'http://esp8266.local:80/api/v1/led=1' {"led": "ON"} $ curl 'http://esp8266.local:80/api/v1/led=0' {"led": "OFF"} # ESP32の場合 $ curl 'http://esp32.local:80/helloWorld' {"name": "Hello world"} $ curl 'http://esp32.local:80/api/v1/led=0' {"led": "OFF"} $ curl 'http://esp32.local:80/api/v1/led=1' {"led": "ON"}

不具合

Wio-Terminalの場合、REST-APIは、起動後の1回しか動作しなかった。(原因不明) mDNSも動作していないので、wiot.localではなく、IPアドレスでアクセスすることになる。

Arduino-IDEのボードマネージャーのURL

以下のURLを設定することで3つのボード(Wio-Terminal/ESP8266/ESP32)が使用可能になる。

https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json http://arduino.esp8266.com/stable/package_esp8266com_index.json https://dl.espressif.com/dl/package_esp32_index.json

参考情報

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(REST-API編)"

| | コメント (0)

2020年7月22日 (水)

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(OSC編)

2020/7/22:
スケッチ改版

2020/7/21:
初版

board3 OSC

board3 OSC

概要

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(OSC編)
(ホストPCとしてはubuntuを想定している)

OSCcodecライブラリ

OSC_codecライブラリとしてプロジェクトのsrcディレクトリに以下の2つのファイルを置く:

src/OSCmsgCodec.h

// OSC message Codec Header // 2013/10/28 #ifndef _OSCMSGCODEC_H #define _OSCMSGCODEC_H #include <string.h> int encOSCmsg(char *packet , union OSCarg *msg); // makes packet from OSC message and returns packet size void decOSCmsg(char *packet , union OSCarg *msg); // makes OSC message from packet union OSCarg { // char*, int and float are assumed four bytes char *address; char *typeTag; long int i; // int32 for Arduino(16bits) float f; char *s; struct { long int len; // is "int i" char *p; } blob; char m[4]; // for MIDI char _b[4]; // endian conversion temp variable }; #endif // _OSCMSGCODEC_H

src/OSCmsgCodec.cpp

/* <---------------------------------------------------------------------------------- OSC message Codec(encoder/decoder) version: 1.3 (2014/ 8/31) encoder bufix(enoceder returns byte length) version: 1.2 (2014/ 8/30) decoder bufix version: 1.1 (2013/11/20) support BIG_ENDIAN by #define version: 1.0 (2013/11/10) Copyright (C) 2011,2013,2014 S.Komatsu released under the MIT License: http://mbed.org/license/mit please refer to: http://opensoundcontrol.org/introduction-osc for OSC(Open Sound Control) The followings are supported: Features: Packet Parsing (Client) Packet Construction (Server) Bundle NOT Support Timetag NOT Support Type Support: i: int32 b: blob s: string f: float32 m: MIDI message(port id, status byte, data1, data2) // I don't know the detail Change Log: Bug(string length is not correct in encoding) Fix on 2013/11/10 (v0.9 -> v1.0) >---------------------------------------------------------------------------------- */ #include "OSCmsgCodec.h" //#define BIG_ENDIAN int lenAlign4B(int len) { if ((len % 4) == 0) {return len; } else {return len+4-(len % 4);} } int encOSCmsg(char *packet , union OSCarg *msg){ // *** important notice *** // output buffer must be cleared before call this char *p, *s, *d, *typeTag; char c; p=packet; d=p; s=msg[0].address; // address for(int i=0; i<strlen(msg[0].address); i++) *d++ = *s++; *d=0; // terminator // p += 4*((strlen(msg[0].address)+1)/4+1); p += lenAlign4B(strlen(msg[0].address)+1); // s=msg[1].typeTag; d=p; for(int i=0; i<strlen(msg[1].typeTag); i++) *d++ = *s++; *d=0; // terminator // p += 4*((strlen(msg[1].s)+1)/4+1); p += lenAlign4B(strlen(msg[1].typeTag)+1); // typeTag=msg[1].s+1; // skip ',' for(int n=0; n<strlen(typeTag); n++){ c = typeTag[n]; if (('s'==c)) { s=msg[n+2].s; d=p; for(int i=0; i<strlen(msg[n+2].s); i++) *d++ = *s++; *d=0; // terminater // p += 4*((strlen(msg[n+2].s)+1)/4+1); p += lenAlign4B(strlen(msg[n+2].s)+1); } else if (('i'==c)||('f'==c)) { #ifdef BIG_ENDIAN // no change endian (big to big) p[0]=msg[n+2]._b[0]; p[1]=msg[n+2]._b[1]; p[2]=msg[n+2]._b[2]; p[3]=msg[n+2]._b[3]; #else // change endian (little to big) p[0]=msg[n+2]._b[3]; p[1]=msg[n+2]._b[2]; p[2]=msg[n+2]._b[1]; p[3]=msg[n+2]._b[0]; #endif p +=4; } else if ('b'==c) { // put length of blog #ifdef BIG_ENDIAN // no change endian (big to big) p[0]=msg[n+2]._b[0]; p[1]=msg[n+2]._b[1]; p[2]=msg[n+2]._b[2]; p[3]=msg[n+2]._b[3]; #else // change endian (little to big) p[0]=msg[n+2]._b[3]; p[1]=msg[n+2]._b[2]; p[2]=msg[n+2]._b[1]; p[3]=msg[n+2]._b[0]; #endif p +=4; // get ponter of blog (copy to msg[n].blog.p) s=msg[n+2].blob.p; d=p; for(int i=0; i<msg[n+2].blob.len; i++) *d++ = *s++; p += 4*(msg[n+2].blob.len/4+1); } else if ('m'==c) { // get midi data (copy to msg[n].m[]) p[0]=msg[n+2].m[0]; p[1]=msg[n+2].m[1]; p[2]=msg[n+2].m[2]; p[3]=msg[n+2].m[3]; p +=4; } else { //printf("*** Not Supported TypeTag:%s ****\n",typeTag); } }; //return (p-packet); // return packet size // bugfix 2014/8/31 return sizeof(char)*(p-packet); // return byte length }; void decOSCmsg(char *packet , union OSCarg *msg){ // Caution: the returned result points to packet as blobs or strings (not newly allocatd) char *p, *typeTag; char c; int n; msg[0].address = packet; // address msg[1].typeTag = packet+4*((strlen(msg[0].s)+1)/4+1);//typeTag typeTag=msg[1].s+1; // skip ',' // bugfix 2014/8/30 if (strlen(typeTag)%2 == 0) p= msg[1].s+4*((strlen(msg[1].s)+1)/4); else p= msg[1].s+4*((strlen(msg[1].s)+1)/4+1); for(n=0; n<strlen(typeTag); n++){ c = typeTag[n]; if (('s'==c)) { msg[n+2].s=p; //p += 4*((strlen(msg[n+2].s)+1)/4+1); p += lenAlign4B(strlen(msg[n+2].s)+1); } else if (('i'==c)||('f'==c)) { #ifdef BIG_ENDIAN // no change endian (big to big) msg[n+2]._b[0]=p[0]; msg[n+2]._b[1]=p[1]; msg[n+2]._b[2]=p[2]; msg[n+2]._b[3]=p[3]; #else // change endian (big to little) msg[n+2]._b[3]=p[0]; msg[n+2]._b[2]=p[1]; msg[n+2]._b[1]=p[2]; msg[n+2]._b[0]=p[3]; #endif p +=4; } else if ('b'==c) { // get lenth of blog (copy to msg[n].blog.len) #ifdef BIG_ENDIAN // no change endian (big to big) msg[n+2]._b[0]=p[0]; msg[n+2]._b[1]=p[1]; msg[n+2]._b[2]=p[2]; msg[n+2]._b[3]=p[3]; #else // change endian (big to little) msg[n+2]._b[3]=p[0]; msg[n+2]._b[2]=p[1]; msg[n+2]._b[1]=p[2]; msg[n+2]._b[0]=p[3]; #endif p +=4; // get ponter of blog (copy to msg[n].blog.p) msg[n+2].blob.p=p; //p += 4*(msg[n+2].blob.len/4+1); p += lenAlign4B(msg[n+2].blob.len+1); } else if ('m'==c) { // get midi data (copy to msg[n].m[]) msg[n+2].m[0]=p[0]; msg[n+2].m[1]=p[1]; msg[n+2].m[2]=p[2]; msg[n+2].m[3]=p[3]; p +=4; } else { //printf("*** Not Supported TypeTag:%s ****\n",typeTag); } }; };

デモ・スケッチ

src/OSC_test.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 /* OSC sender/receiver Forked for Wio-Terminal/ESP8266(ESP-WROOM-02)/ESP32 from: This sketch sends random data over UDP on a ESP32 device */ #ifdef WIO_TERMINAL #include <AtWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif #include <WiFiUdp.h> // WiFi network name and password: const char* ssid = "your_ssid"; const char* passwd = "your_passwd"; //IP address to send UDP data to: const char* udpAddress = "192.168.0.21"; // target IP const int udpInPort = 8000; // incomming port const int udpOutPort = 9000; // outgoing port //<<<<<<<<<<<<<<<<<<<<< // OSC related #include "OSCmsgCodec.h" #define PACKET_SIZE 512 #define RECBUF_SIZE 256 union OSCarg msg[10], outmsg[10]; char buff[PACKET_SIZE],packet[PACKET_SIZE]; //>>>>>>>>>>>>>>>>>>>> char recbuf[128]; // buffer for incoming packets //The udp library class WiFiUDP udp; void setup() { Serial.begin(115200); Serial.println("OSC test program start..."); Serial.println(""); // delete old config WiFi.disconnect(true); Serial.printf("Connecting to %s ", ssid); WiFi.begin(ssid, passwd); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(" connected"); udp.begin(udpInPort); Serial.printf("Now listening at IP %s, UDP port %d\r\n", WiFi.localIP().toString().c_str(), udpInPort); } void loop() { int packetSize = udp.parsePacket(); if (packetSize>0) { Serial.printf("Received %d bytes from %s, port %d\r\n", packetSize, udp.remoteIP().toString().c_str(), udpInPort); int len = udp.read(recbuf, 128); if (len > 0) { decOSCmsg(recbuf, msg); Serial.printf("incomming OSC msg:\r\n%s %s", msg[0].address, msg[1].typeTag); for(int m=0; m < (strlen(msg[1].typeTag)-1); m++) { if (msg[1].typeTag[m+1]=='f') Serial.printf(" %f",msg[m+2].f); if (msg[1].typeTag[m+1]=='i') Serial.printf(" %d",msg[m+2].i); }; Serial.printf("\r\n"); Serial.printf("-------------------\r\n"); } } else { // test send // fader // send OSC message with random values (to touchOSC) // make OSC message for sending outmsg[0].address="/1/fader5"; outmsg[1].typeTag=",f"; outmsg[2].f= rand()%1000/1000.0; memset(packet,0,sizeof(packet)); // clear send buff for OSC msg int plen=encOSCmsg(packet,outmsg); // send it // Send a packet udp.beginPacket(udpAddress, udpOutPort); udp.write((const uint8_t*)packet, plen); udp.endPacket(); // //Serial.print("."); // indicate sending packet //Wait delay(10); // seems 'must' (for platformio) } }

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32

以下については、自分の環境に合わせて変更すること:

// WiFi network name and password: const char* ssid = "your_ssid"; const char* passwd = "your_passwd"; //IP address to send UDP data to: const char* udpAddress = "192.168.0.15"; // target IP const int udpInPort = 8000; // incomming port const int udpOutPort = 9000; // outgoing port

udpAddressは、対向するOSC受信デバイス(touchOSCなど)のIPを設定する。

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 ........... connected Now listening at IP 192.168.0.11, UDP port 8000

上の例ではTouchOSCから192.168.0.11:8000へOSCパッケットに送る(ようにTouchOSCを設定する)。

または、動作としては、touchOSCのsimpleレイアウトの画面で、最上行の受信アイコンがOSCを受信すると「赤」になり、fader5のfaderが送られてきたOSCの内容に従ってランダムに変化する。

Arduino-IDEのボードマネージャーのURL

以下のURLを設定することで3つのボード(Wio-Terminal/ESP8266/ESP32)が使用可能になる。

https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json http://arduino.esp8266.com/stable/package_esp8266com_index.json https://dl.espressif.com/dl/package_esp32_index.json

問題点

Wio-Terminalでは、OSC受信は、動作しなかった。(原因不明)

参考情報

TouchOSC - Modular touch control surface for OSC & MIDI
TouchOSC - iPhone
TouchOSC - Android

OSCmsgCode lib:
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//raw-file/e62251d890c1/OSCmsgCodec.h
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//raw-file/e62251d890c1/OSCmsgCodec.cpp
https://os.mbed.com/users/xshige/code/Sparkfun_CC3000_WiFi_OSCtranceiver//file/e62251d890c1/main.cpp/

Platform/Wio Terminal Network/Wi-Fi - example sketches

Wio Terminalをはじめよう(ピン配置、データシート、回路図など)

Platform/Wio Terminal/Network/Overview
download url:
https://files.seeedstudio.com/wiki/Wio-Terminal/res/ameba-image-Tool-v2.4.1.zip
https://files.seeedstudio.com/wiki/Wio-Terminal/res/20200601-rtl8720d-images-v2.2.0.0.zip

PlatformIO Core (CLI)

以上

続きを読む "Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(OSC編)"

| | コメント (0)

2020年7月21日 (火)

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(MQTT編)

2020/7/21:
初版

board3 MQTT

board3 MQTT

概要

Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(MQTT編)
(ホストPCとしてはubuntuを想定している)

外部ライブラリ(platformioの場合)

以下を実行してライブラリをインストールする:

# MQTT lib インストール pio lib install 617

外部ライブラリ(Arduino-IDEの場合)

Arduino-IDEでMQTTライブラリをインストールする。 MQTTは同じようなライブラリが見つかるが 「author:Joel Gaehwiler」のものをインストールする。

デモ・スケッチ

src/MQTT_test.ino

// select board ////#define WIO_TERMINAL ////#define ESP8266 ////#define ESP32 //------------------ // // MQTT program for Wio-Terminal/ESP8266/ESP32 // // Forked from the following code: //-------------------------------------------- // This example uses an Adafruit Huzzah ESP8266 // to connect to shiftr.io. // // You can check on your device after a successful // connection here: https://shiftr.io/try. // // by Joël Gähwiler // https://github.com/256dpi/arduino-mqtt //-------------------------------------------- #ifdef WIO_TERMINAL #include <AtWiFi.h> #endif #ifdef ESP8266 #include <ESP8266WiFi.h> #endif #ifdef ESP32 #include <WiFi.h> #endif #include <MQTT.h> const char ssid[] = "your_ssid"; const char pass[] = "your_passwd"; WiFiClient net; MQTTClient client; unsigned long lastMillis = 0; void connect() { Serial.print("checking wifi..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } Serial.print("\nconnecting..."); //while (!client.connect("arduino", "try", "try")) { // for "broker.shiftr.io" while (!client.connect("arduino", "", "")) { // no username. no passwd (for "mqtt.eclipse.org") Serial.print("."); delay(1000); } Serial.println("\nconnected!"); client.subscribe("topic0"); // client.unsubscribe("/hello"); } void messageReceived(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); } void setup() { Serial.begin(115200); WiFi.begin(ssid, pass); // Note: Local domain names (e.g. "Computer.local" on OSX) are not supported by Arduino. // You need to set the IP address directly. // uncomment one of them to select MQTT server //client.begin("broker.shiftr.io", net); //OK client.begin("mqtt.eclipse.org", net); //OK //client.begin("test.mosquitto.org", net); //NG? client.onMessage(messageReceived); connect(); } void loop() { char s[100]; // buf for sprintf // dumy sensor values float pascals = 101312; float altm = 42; //m float tempC = 28.7; // deg C client.loop(); delay(10); // <- fixes some issues with WiFi stability if (!client.connected()) { connect(); } // publish a message roughly every second. if (millis() - lastMillis > 1000) { lastMillis = millis(); // publish sensor values sprintf(s,"{ \"press\" : %.2f, \"altm\" : %.1f, \"tempC\" : %.1f}", pascals/100, altm, tempC); client.publish("topic0", &s[0]); } delay(1000); }

以下の#defineでボードを切り換えているがボードの種類を設定すると、 システムで設定されている定義が有効になるので特にソースを変更する必要はない。

#define WIO_TERMINAL #define ESP8266 #define ESP32

以下については、自分の環境に合わせて変更すること:

const char ssid[] = "yours_ssid"; const char pass[] = "yours_passwd";

以下は利用するMQTTサーバー(broker)に合わせてコメントアウトする:

//client.begin("broker.shiftr.io", net); //OK client.begin("mqtt.eclipse.org", net); //OK

書き込み後に「picocom /dev/ttyACM0 -b115200」または「picocom /dev/ttyUSB0 -b115200」で通信ソフトを起動すると以下のような出力が表示される:

$ picocom /dev/ttyACM0 -b115200 Terminal ready # 実際のセンサーを接続していないので一定のダミーデータを受信する incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} incoming: topic0 - { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} ... <省略>

対向する送受信プログラム

以下をブラウザ(chromeのみ)で動かす:

MQTT_AT_webTestZero.html

<html> <script src="https://unpkg.com/mqtt/dist/mqtt.min.js"></script> <body> <script> //var mqtt_url = 'ws://test.mosquitto.org:8081' var mqtt_url = 'ws://mqtt.eclipse.org/mqtt:443' //var mqtt_url = 'wss://try:try@broker.shiftr.io' document.body.innerHTML = ''; var consout = 'MQTT over WebSockets Test'+'('+mqtt_url+')<br>' document.body.innerHTML = consout; //var mqtt = require('mqtt'); var client = mqtt.connect(mqtt_url); // subscribe Topic //client.subscribe('hello'); client.subscribe('topic0'); //client.subscribe('topic0/sample/hello'); //client.subscribe('topic0/sample/#'); // wildcard topic //client.subscribe('topic0/#'); //client.subscribe('#'); client.on('message', function(topic, payload) { console.log([topic, payload].join(': ')); consout += [topic, payload].join(': ')+'<br>' document.body.innerHTML = consout // disconnect //client.end(); }); // publish messages client.publish('topic0', 'hello world of MQTT! #1'); client.publish('topic0', 'hello world of MQTT! #2'); client.publish('topic0', 'hello world of MQTT! #3'); client.publish('topic0', 'hello world of MQTT! #4'); client.publish('topic0', 'hello world of MQTT! #5'); </script> </body> </html>

デモプログラムを起動後、上の「MQTT_AT_webTestZero.html」をプラウザーで起動すると
以下のweb画面が表示される(例):

MQTT over WebSockets Test(ws://mqtt.eclipse.org/mqtt:443) topic0: hello world of MQTT! #1 topic0: hello world of MQTT! #2 topic0: hello world of MQTT! #3 topic0: hello world of MQTT! #4 topic0: hello world of MQTT! #5 topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} topic0: { "press" : 1013.12, "altm" : 42.0, "tempC" : 28.7} ...

Arduino-IDEのボードマネージャーのURL

以下のURLを設定することで3つのボード(Wio-Terminal/ESP8266/ESP32)が使用可能になる。

https://files.seeedstudio.com/arduino/package_seeeduino_boards_index.json http://arduino.esp8266.com/stable/package_esp8266com_index.json https://dl.espressif.com/dl/package_esp32_index.json

参考情報

https://docs.shiftr.io/interfaces/mqtt/

The following ports are available on the broker.shiftr.io host: MQTT MQTTS MQTTWS MQTTWSS 1883 8883 80 443

MQTT test server @mosquitto.org

https://test.mosquitto.org/ The server listens on the following ports: 1883 : MQTT, unencrypted 8883 : MQTT, encrypted 8884 : MQTT, encrypted, client certificate required 8080 : MQTT over WebSockets, unencrypted 8081 : MQTT over WebSockets, encrypted websocketで使用するurlは以下になる: 'ws://test.mosquitto.org:8081'

MQTT test server @eclipse.org

http://mqtt.eclipse.org/ This is a public test MQTT broker service. It currently listens on the following ports: 1883 : MQTT over unencrypted TCP 8883 : MQTT over encrypted TCP 80 : MQTT over unencrypted WebSockets (note: URL must be /mqtt ) 443 : MQTT over encrypted WebSockets (note: URL must be /mqtt ) websocketで使用するurlは以下になる: 'ws://mqtt.eclipse.org/mqtt:443'

10 Free Public & Private MQTT Brokers(For Testing & Production)

PlatformIO Core (CLI)

ESP-WROOM-02ボードでMQTTとMPL3115A2(気圧・高度・気温センサ)を動かす(Arduino版)
本記事のスケッチは、この記事のスケッチとほとんど同じであるので参考にできる。

以上

続きを読む "Wio-Terminal/ESP8622/ESP32ボードを共通のスケッチで動かす(MQTT編)"

| | コメント (0)