#include <M5StickCPlus.h>
#include <WiFi.h>
#include <ArduinoOTA.h>

const char *ssid = "ics-ap";
const char *password = "jikkenics";

void setup()
{
    M5.begin();
    M5.Lcd.setRotation(3);
    M5.Lcd.fillScreen(ORANGE);
    M5.Lcd.setCursor(10, 50, 4);

    WiFi.begin(ssid, password); // 接続開始
    while (WiFi.status() != WL_CONNECTED)
    { // 接続中...
        M5.Beep.tone(2000);
        delay(200);
        M5.Beep.mute();
        delay(300);
        M5.Lcd.print(".");
    }
    // 接続完了！！
    M5.Beep.tone(4000);
    M5.Lcd.fillScreen(CYAN);
    M5.Lcd.setCursor(0, 10, 4);
    M5.Lcd.setTextColor(BLACK, CYAN);
    M5.Lcd.print("  OTA Test\n   Wifi Connected!\n  ");
    String gotip = WiFi.localIP().toString(); // m5デバイスのIPアドレス
    M5.Lcd.println(gotip);

    // MACアドレスを表示
    uint8_t mac[6];
    char macchar[100];
    esp_read_mac(mac, ESP_MAC_WIFI_STA);
    sprintf(macchar, "  %02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    String macstr = macchar;
    M5.Lcd.println(macstr);

    delay(1500);
    M5.Beep.mute();
}

void loop()
{
    ArduinoOTA.handle();
    delay(100);
    M5.update();
    if (M5.Axp.GetBtnPress()) // 電源ボタン押下したら
    {
        // ESP.restart();
        M5.Axp.Write1Byte(0x32, M5.Axp.Read8bit(0x32) | 0x80); //電源OFF
    }
}

void ota_setup() {

  // Port defaults to 3232
//   ArduinoOTA.setPort(3232);

  // Hostname defaults to esp3232-[MAC]
//   ArduinoOTA.setHostname("m5stickc0123");
  
  // No authentication by default
  // ArduinoOTA.setPassword("pass");
  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("4528e6a7bb9341c36c425faf40ef32c3");//pass

  ArduinoOTA
  .onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH)
      type = "sketch";
    else // U_SPIFFS
      type = "filesystem";
  })
  .onEnd([]() {
    M5.Beep.tone(2000);
    delay(150);
    M5.Beep.tone(4000);
    delay(150);
    M5.Beep.tone(8000);
    delay(300);
    M5.Beep.mute();
  })
  .onProgress([](unsigned int progress, unsigned int total) {
    ota_progress(progress, total);
  })
  .onError([](ota_error_t error) {
  });

  ArduinoOTA.begin();
}

int prev_progress = -1;
char buf[30];
void ota_progress(unsigned int progress, unsigned int total) {
  int cur_progress = (progress / (total / 100));
  sprintf(buf, "OTA %d%% done", cur_progress );
  if (prev_progress < cur_progress) {
    M5.Lcd.setCursor(0, 30, 1);
    M5.Lcd.fillScreen(BLACK);
    M5.Lcd.setTextColor(WHITE, BLACK);
    M5.Lcd.println(buf);
    prev_progress = cur_progress;
  }
}
