#include <M5Unified.h>
#include <WiFi.h>

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

void setup() {
  auto cfg = M5.config();
  cfg.serial_baudrate = 115200; // ボーレートを115200に設定
  M5.begin(cfg);
  M5.Display.setRotation(3);
  M5.Display.setFont(&fonts::lgfxJapanGothic_16);
  M5.Display.println("NTP 01");
  M5.Display.setTextScroll(true);

  WiFi.begin(ssid, password); // 接続開始
  while (WiFi.status() != WL_CONNECTED) { // 接続中...
    M5.Display.print(".");
    M5.delay(500);
  }
  char* ntpserver = "ntp.nict.jp" ;
  configTime(9 * 3600, 0, ntpserver) ; //GMTとの時差(秒) が9*3600, サマータイムで進める時間(秒)が0

  M5.Display.fillScreen(CYAN);
  M5.Display.setCursor(0, 40);
  M5.Display.setTextColor(BLACK, CYAN);
  M5.Display.print("  Wifi Connected!\n  ");
  String gotip = WiFi.localIP().toString(); // m5デバイスのIPアドレス
  M5.Display.println(gotip);
  M5.delay(1500);
}

void loop() {
  M5.update();
  char buf[30];

  getLocalC(buf); // bufに、Local(NTP)日時文字列を書き込む
  M5.Display.setTextColor(GREEN,BLACK);
  M5.Display.println(buf);
  Serial.println(buf);

  getRTC(buf); // bufに、日時文字列を書き込む
  M5.Display.setTextColor(CYAN,BLACK);
  M5.Display.println(buf);
  Serial.println(buf);


  if (M5.BtnA.wasPressed()) {
    // NTPからRTCに時刻設定する
    struct tm localTime;
    getLocalTime(&localTime);
    setRTCfromLT(localTime);
    M5.Display.setTextColor(WHITE,RED);
    M5.Display.println("  LocalTimeをRTCに設定！  ");    
  }
  M5.delay(1000);
}

void setRTCfromLT(struct tm lt) {
  m5::rtc_date_t DateStruct;
  DateStruct.year = lt.tm_year + 1900;
  DateStruct.month = lt.tm_mon + 1;
  DateStruct.date = lt.tm_mday;
  DateStruct.weekDay = lt.tm_wday;
  M5.Rtc.setDate(&DateStruct);

  m5::rtc_time_t TimeStruct;
  TimeStruct.hours   = lt.tm_hour;
  TimeStruct.minutes = lt.tm_min;
  TimeStruct.seconds = lt.tm_sec+1;
  M5.Rtc.setTime(&TimeStruct);
}

void getRTC(char* buf) {
  m5::rtc_date_t DateStruct;
  m5::rtc_time_t TimeStruct;
  M5.Rtc.getDate(&DateStruct);
  M5.Rtc.getTime(&TimeStruct);
  sprintf(buf, "RTC %04d/%02d/%02d %02d:%02d:%02d",
          DateStruct.year,  DateStruct.month,   DateStruct.date,
          TimeStruct.hours, TimeStruct.minutes, TimeStruct.seconds
         );
}

void getLocalC(char* buf) {
  struct tm localTime;
  getLocalTime(&localTime);
  sprintf(buf, "LOC %04d/%02d/%02d %02d:%02d:%02d",
          localTime.tm_year + 1900,
          localTime.tm_mon + 1,
          localTime.tm_mday,
          localTime.tm_hour,
          localTime.tm_min,
          localTime.tm_sec
         );  
}