#include <M5StickCPlus.h>
#include <WiFi.h>
// #include "time.h"

#define USE_NTP 1   // NTPからRTCに時刻設定するなら1

void setRTCfromLT(struct tm lt) {
  RTC_DateTypeDef 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.SetData(&DateStruct);

  RTC_TimeTypeDef 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) {
  RTC_DateTypeDef DateStruct;
  RTC_TimeTypeDef TimeStruct;
  M5.Rtc.GetData(&DateStruct);
  M5.Rtc.GetTime(&TimeStruct);
  sprintf(buf, "%04d/%02d/%02d %02d:%02d:%02d",
          DateStruct.Year,  DateStruct.Month,   DateStruct.Date,
          TimeStruct.Hours, TimeStruct.Minutes, TimeStruct.Seconds
         );
}

void setup() {
  M5.begin();
  M5.Lcd.setRotation(3);
  Serial.begin(115200);

  if (USE_NTP) {
    const char* ssid = "miura2g";
    const char* password = "jikken2022";
    const char* ntpserver = "192.168.11.11"; // or ntp.nict.jp"; // or 10.64.7.184 for CIT-ap1x
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) { // 接続中...
      Serial.print(".");
    }
    configTime(9 * 3600, 0, ntpserver);

    struct tm localTime;
    while (localTime.tm_year < 80) {
      getLocalTime(&localTime); delay(50);
    }
    setRTCfromLT(localTime);
  }
}

void loop() {
  char buf[30];
  getRTC(buf); // bufに、日時文字列を書き込む
  Serial.println(buf);
  M5.Lcd.fillScreen(BLUE);
  M5.Lcd.setCursor(0, 50, 4);
  M5.Lcd.println(buf);
  delay(1000);
}