// =============================================================================
// ESP32 Bluetooth Serial - Master Device (MAC-based)
// =============================================================================

#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
  #error Bluetooth is not enabled!
#endif
#if !defined(CONFIG_BT_SPP_ENABLED)
  #error Serial Port Profile (SPP) not available.
#endif

// --- Configuration -----------------------------------------------------------
#define DEVICE_NAME       "ESP32-BT-Master"
#define BAUD_RATE         115200
#define BUTTON_PIN        15
#define LED_PIN           2
#define RETRY_INTERVAL_MS 10000

// 👉 PUT YOUR SLAVE MAC HERE
uint8_t slaveAddress[] = {0x24, 0x62, 0xAB, 0xFF, 0x24, 0xC2};

// --- Globals -----------------------------------------------------------------
BluetoothSerial SerialBT;
bool wasConnected    = false;
bool lastButtonState = HIGH;
unsigned long lastConnectAttempt = 0;

// --- Helpers -----------------------------------------------------------------
void attemptConnect() {
  Serial.println("[BT] Connecting using MAC...");
  lastConnectAttempt = millis();
  SerialBT.connect(slaveAddress);
}

// =============================================================================
void setup() {
  Serial.begin(BAUD_RATE);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);

  SerialBT.begin(DEVICE_NAME, true); // master mode

  Serial.println("==============================================");
  Serial.println("  Master ready (MAC mode)");
  Serial.println("==============================================");

  attemptConnect();
}

// =============================================================================
void loop() {
  bool isConnected = SerialBT.connected();

  // --- Connection state changes ---------------------------------------------
  if (isConnected && !wasConnected) {
    wasConnected = true;
    Serial.println("[BT] Connected!");
  } else if (!isConnected && wasConnected) {
    wasConnected = false;
    digitalWrite(LED_PIN, LOW);
    Serial.println("[BT] Disconnected.");
  }

  // --- Retry connection ------------------------------------------------------
  if (!isConnected && millis() - lastConnectAttempt >= RETRY_INTERVAL_MS) {
    attemptConnect();
  }

  if (!isConnected) { delay(20); return; }

  // --- Send button state -----------------------------------------------------
  bool buttonState = digitalRead(BUTTON_PIN);
  if (buttonState != lastButtonState) {
    lastButtonState = buttonState;
    SerialBT.write(buttonState == LOW ? '1' : '0');
    Serial.printf("[BTN] Sent: %c\n", buttonState == LOW ? '1' : '0');
  }

  // --- Receive and control LED ----------------------------------------------
  if (SerialBT.available()) {
    char cmd = SerialBT.read();
    if (cmd == '1' || cmd == '0') {
      digitalWrite(LED_PIN, cmd == '1' ? HIGH : LOW);
      Serial.printf("[LED] Received: %c → LED %s\n",
                    cmd, cmd == '1' ? "ON" : "OFF");
    }
  }

  delay(20);
}