ESP32 またはarduino UNO からJSON をPOST送信したいがうまく行かない。curlコマンドでは成功。
JSONのPOST送信。curlコマンドで成功。
私はプログラミング初心者です。MOTU UltraLite AVBというオーディオインターフェイスのパラメータを、外部機器(ESP32またはarduino UNO)からコントロールしたいと考えています。
マニュアルにはAPIで実現出来ると思わしき記載があり、サンプルとして上がっていたcurlコマンドを自らの環境に合わせカスタムしました。
windows10 PCからコマンドプロンプトでcurl送信を行い、無事オーディオインターフェイスの値を書き換える事に成功しました。
MOTU UltraLite AVBマニュアル
MOTU UltraLite AVBマニュアルに掲載されていたcurlコマンドのサンプル
curl --data 'json={"value":"My favorite channel"}' \
<yourdevice.local.>/datastore/ext/obank/2/ch/0/name
☆カスタムを行い、コマンドプロンプト送信で成功したcurlコマンド
curl --data "json={\"value\":\"My favorite channel\"}" http://192.168.0.100/datastore/ext/obank/2/ch/0/name
同じJSONのPOST送信がESP32ではできない。
次はいよいよ同じ内容のJSON『{\"value\":\"My favorite channel\"} 』を同じURI『http://192.168.0.100/datastore/ext/obank/2/ch/0/name 』に、ESP32 またはarduino UNO からPOST送信したいと思いました。件のマニュアルにはESP32やarduinoに関する記載は見当たりませんでした。
ネット検索に頼ったところ『ESP32 HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)』という記事を見つけました。
ESP32 HTTP GET and HTTP POST with Arduino IDE (JSON, URL Encoded, Text)
掲載されていたコードはPOST以外のメソッドもカバーされていました。必要だと思われる箇所を抜き出して、SSIDやpassword等自分の環境に合わせカスタマイズを行いました。ESP32に書き込みコードを走らせてみたのですがうまく行きません。
wifiには接続されました。しかしながらcurlコマンドで成功したオーディオインターフェイスの値がESP32だと書き換わる事がありませんでした。
試したソースコード
#include <WiFi.h>
#include <HTTPClient.h>
const char* ssid = "自分のSSID";
const char* password = "自分のパスワード";
void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}
void loop() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://192.168.0.100/datastore/ext/obank/2/ch/0/name");  //curlコマンドと同じURi『http://192.168.0.100/datastore/ext/obank/2/ch/0/name 』
    http.addHeader("Content-Type", "application/json");
    int httpResponseCode = http.POST("{\"value\":\"My favorite channel\"}");  //curlコマンドと同じ内容のJSON『{\"value\":\"My favorite channel\"} 』
    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error on sending PUT Request: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  } else {
    Serial.println("Error in WiFi connection");
  }
  delay(10000);
}
シリアルモニタの表示
wifiには接続。Error on sending PUT Request: -5 の表示が見られる。
Connected to WiFi network with IP Address: 192.168.0.4
Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.
Error on sending PUT Request: -5
他にそれらしいコードをネット検索で試していますがいずれもうまく行っていません。HTTPやJSONの知識に乏しいプログラミング初心者にはつまづきの要因さえわからず、八方塞がりになったところでこちらの投稿に助けを求めました。
どのようなコードでESP32 またはarduino UNO からJSONのPOST送信が実現できますでしょうか。
皆様お力添え下さい。