過去のコードでは、M5StickCPlusでLINE Notifyに送れなくなっていた。
M5StickCPlusでLINE Notifyに送ろうとしたら送れなくて、シリアルモニターに
Try
Connection failed
と表示されるエラーに遭遇した。
先人の方々の記事を見たら、
以前はclient.setInsecure();は必要なかったが、2022年頃からclient.setInsecure();が必要になっていることがわかった。
従来(2021年頃まで)、以下のコードでLINE Notifyに送ることができた。
/* LINE Notifyに送る */
void send(String message) {
WiFiClientSecure client;
Serial.println("Try");
//LineのAPIサーバに接続
if (!client.connect(host, 443)) {
Serial.println("Connection failed");
return;
}
Serial.println("Connected");
//リクエストを送信
String query = String("message=") + message;
String request = String("") +
"POST /api/notify HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Authorization: Bearer " + token + "\r\n" +
"Content-Length: " + String(query.length()) + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" +
query + "\r\n";
client.print(request);
//受信終了まで待つ
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
break;
}
}
String line = client.readStringUntil('\n');
Serial.println(line);
}
2022年頃からは、上記コードの2行目にclient.setInsecure();を入れた以下のコードで動作する。
/* LINE Notifyに送る */
void send(String message) {
WiFiClientSecure client;
client.setInsecure(); // サーバー証明書の検証を行わずに接続する場合に必要
Serial.println("Try");
//LineのAPIサーバに接続
if (!client.connect(host, 443)) {
Serial.println("Connection failed");
return;
}
Serial.println("Connected");
//リクエストを送信
String query = String("message=") + message;
String request = String("") +
"POST /api/notify HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Authorization: Bearer " + token + "\r\n" +
"Content-Length: " + String(query.length()) + "\r\n" +
"Content-Type: application/x-www-form-urlencoded\r\n\r\n" +
query + "\r\n";
client.print(request);
//受信終了まで待つ
while (client.connected()) {
String line = client.readStringUntil('\n');
Serial.println(line);
if (line == "\r") {
break;
}
}
String line = client.readStringUntil('\n');
Serial.println(line);
}
参考記事
https://twitter.com/ciniml/status/1391016125530460163
https://twitter.com/coppercele/status/1391014047215091719
https://twirepo.com/detail/14663618
おわりに
また動いてガッツポーズ!