#include <M5StickCPlus.h>
#include "BluetoothSerial.h"

BluetoothSerial SerialBT;

const char* dname = "BT_Serial_00"; // Slave device name

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

  Serial.begin(115200);
  SerialBT.begin(dname); //Bluetooth device name
  Serial.println("The device started, now you can pair it with bluetooth!");

  uint8_t macBT[6];
  esp_read_mac(macBT, ESP_MAC_BT);
  char mac[20];
  sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X", macBT[0], macBT[1], macBT[2], macBT[3], macBT[4], macBT[5]);
  Serial.println(mac);
  M5.Lcd.println(mac);

}

int line = 0;
void loop() {
  char c;
  if (Serial.available()) {
    SerialBT.write(c = Serial.read());
    Serial.printf("read:%c\n", c);
  }
  if (SerialBT.available()) {
    Serial.write(c = SerialBT.read());
    SerialBT.write(c + 0);
    M5.Lcd.print(c);
    if (c == 0xa) line++;
    if (line > 7) {
      M5.Lcd.fillScreen(YELLOW);  M5.Lcd.setCursor(0, 0, 1);
      line = 0;
    }
  }

  M5.update();
  if (M5.BtnA.wasReleasefor(1000) ) {
    SerialBT.println("[A] was Pressed longer than 1s");
  } else if (M5.BtnA.wasReleased()) {
    SerialBT.println("[A] was Pressed");
  } else if (M5.BtnB.wasReleasefor(1000) ) {
    SerialBT.println("[B] was Pressed longer than 1s");
  } else if (M5.BtnB.wasReleased()) {
    SerialBT.println("[B] was Pressed");
  } else if (M5.Axp.GetBtnPress() == 2) {
    SerialBT.println("[Power] was Pressed");
  }

  delay(20);
}