// =============================================================================
// ESP32 Bluetooth Serial - Slave Device
// =============================================================================

#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-Slave"
#define BAUD_RATE     115200
#define BUTTON_PIN    15
#define LED_PIN       2

// --- Globals -----------------------------------------------------------------
BluetoothSerial SerialBT;
bool wasConnected    = false;
bool lastButtonState = HIGH;

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

  SerialBT.begin(DEVICE_NAME); // slave mode

  Serial.println("==============================================");
  Serial.println("  Slave ready (waiting for master)");
  Serial.println("==============================================");

  // 👉 Print MAC so you can copy it into master
  Serial.print("Slave MAC Address: ");
  Serial.println(SerialBT.getBtAddressString());
}

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

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

  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);
}