M5Stack+LAN module(W5500)+HTTP BasicAuth
なかなかぴったりくるライブラリの組み合わせが見つからずリセットやらフリーズに苛まれていましたが、何とかまとまったのでメモ。
defineを切り替えるとWiFiとLANモジュール、通常のGETとBasicAuthの併用を切り替えられます。
#define USE_ETH 1
#define USE_BASICAUTH 1
#include <M5Stack.h>
#include <SPI.h>
#if USE_ETH
#include <Ethernet3.h>
#include <EthernetClient.h>
#else
#include <WiFi.h>
#endif
#include <ArduinoHttpClient.h>
#define SS 33
#define SCK 18
#define MISO 19
#define MOSI 23
#define CS 26
#define RST 13
uint8_t baseMac[6];
#if USE_ETH
IPAddress IP(192, 168, 1, 77);
IPAddress DNS(192, 168, 1, 1);
IPAddress GATEWAY(192, 168, 1, 1);
IPAddress SUBNETM(255, 255, 255, 0);
#else
const char* ssid = "wifi-ssid";
const char* pass = "wifi-password";
#endif
#if USE_BASICAUTH
const char kHostname[] = "httpbin.org";
const char kPath[] = "/basic-auth/user/password";
const char kBasicUser[] = "user";
const char kBasicPass[] = "password";
#else
const char kHostname[] = "httpbin.org";
const char kPath[] = "/ip";
#endif
void setup() {
// put your setup code here, to run once:
M5.begin();
M5.Power.begin(); // Init Power module.
#if USE_ETH
esp_read_mac(baseMac, ESP_MAC_WIFI_STA);
Ethernet.init(2);
// start the Ethernet connection and the server:
Ethernet.setCsPin(CS); // set Pin 3 for CS
Ethernet.setRstPin(RST); // set Pin 4 for RST
Ethernet.begin(baseMac, IP, SUBNETM, GATEWAY, DNS);
//Ethernet.softreset();
#else
WiFi.begin(ssid, pass);
M5.Lcd.printf("Waiting connect to WiFi: %s ", ssid);
while(WiFi.status() != WL_CONNECTED) {
//接続完了まで待つ
delay(1000);
M5.Lcd.print(".");
}
//接続完了したらIPアドレスとMacアドレスを表示する
M5.Lcd.println("\nWiFi connected");
M5.Lcd.print("IP address: ");
M5.Lcd.println(WiFi.localIP());
M5.Lcd.print("MAC address:");
M5.Lcd.println(WiFi.macAddress());
delay(500);
#endif
}
void loop() {
// put your main code here, to run repeatedly:
#if USE_ETH
EthernetClient c;
HttpClient http = HttpClient(c, kHostname, 80);
#else
WiFiClient wifi;
HttpClient http = HttpClient(wifi, kHostname, 80);
#endif
// start connection and send HTTP header
#if USE_BASICAUTH
http.beginRequest();
int err = http.get(kPath);
http.sendBasicAuth(kBasicUser, kBasicPass);
http.endRequest();
#else
int err = http.get(kPath);
#endif
if(err == 0) {
int httpCode = http.responseStatusCode();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server response header has been handled
M5.Lcd.printf("[HTTP] GET... code: %d\n", httpCode);
// file found at server
if(httpCode == 200) {
err = http.skipResponseHeaders();
if (err >= 0)
{
String payload = http.readString();
M5.Lcd.println(payload);
}
}
} else {
M5.Lcd.printf("[HTTP] GET... failed, error: %d\n", httpCode);
}
}
http.stop();
// Wait
delay(10000);
}
LAN使用時のMACアドレスをWiFiモジュールから拝借していますが同時使用しないならまあ…という甘えた思考です。
platformioの設定ファイルは以下のような感じ。
[env:m5stack-core-esp32]
platform = espressif32
board = m5stack-core-esp32
framework = arduino
lib_deps =
m5stack/M5Stack@^0.4.6
sstaub/Ethernet3@^1.5.6
arduino-libraries/ArduinoHttpClient@^0.6.1
お仕事頑張ってください!