M5StickCからサーバにPostでJsonを送り続ける。

M5Stackでもほとんど同じでいける。

とりあえず、センサーの値をサーバに残したい場合とか。 とりあえずとはいえhttpsにはしないとなー。

#include <M5StickCPlus.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "xxxx";
const char* pass = "xxxx";

const int capacity = JSON_OBJECT_SIZE(2);
StaticJsonDocument<capacity> json_request;

char buffer[255];
const char *url = "http://..../";

HTTPClient http;

void setup() {
  M5.begin();
  
  M5.Lcd.setRotation(1);
  M5.Lcd.fillScreen(BLACK);
  M5.Lcd.setTextColor(WHITE);
  M5.Lcd.setCursor(0, 0);
  M5.Lcd.setTextSize(1);

  M5.Lcd.printf("WiFi Connecting.");

  WiFi.begin(ssid, pass);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    M5.Lcd.print(".");
  }
  M5.Lcd.println("OK");

  M5.Lcd.printf("IP: %s", WiFi.localIP().toString().c_str());
  M5.Lcd.println();

  json_request["name"] = "m5stickc-plus";
}

void loop() {
  static int counter = 0;

  json_request["counter"] = ++counter;

  serializeJson(json_request, buffer, sizeof(buffer));

  http.begin(url);
  http.addHeader("Content-Type", "application/json");

  int status_code = http.POST((uint8_t*)buffer, strlen(buffer));

  if (status_code < 0) {
    M5.Lcd.printf("FAILED: %s\n", http.errorToString(status_code).c_str());
    return;
  }

  if (status_code != HTTP_CODE_OK) {
    M5.Lcd.printf("%d\n", status_code);
    return;
  }

  Serial.printf("[%d] ", status_code);

  String payload = http.getString();
  Serial.println(payload);

  delay(1000);
}