#include <BLEDevice.h>
#include <BLEUtils.h>
#include <BLEServer.h>

#define ONBOARD_LED  2

#define SERVICE_UUID        "a17881b1-519a-45e5-85c3-ae3acf763e19"
#define CHARACTERISTIC_UUID "05f4798d-3165-455a-931d-e0aceb723423"


bool clientConnected = false;

class MyServerCallbacks: public BLEServerCallbacks {
  void onConnect (BLEServer * pServer) {
    clientConnected = true;
  };
  void onDisconnect (BLEServer * pServer) {
    clientConnected = false;
  }
};


void print_wakeup_reason(){
  esp_sleep_wakeup_cause_t wakeup_reason;

  wakeup_reason = esp_sleep_get_wakeup_cause();

  switch(wakeup_reason)
  {
    case ESP_SLEEP_WAKEUP_EXT0 : Serial.println("Wakeup caused by external signal using RTC_IO"); break;
    case ESP_SLEEP_WAKEUP_EXT1 : Serial.println("Wakeup caused by external signal using RTC_CNTL"); break;
    case ESP_SLEEP_WAKEUP_TIMER : Serial.println("Wakeup caused by timer"); break;
    case ESP_SLEEP_WAKEUP_TOUCHPAD : Serial.println("Wakeup caused by touchpad"); break;
    case ESP_SLEEP_WAKEUP_ULP : Serial.println("Wakeup caused by ULP program"); break;
    default : Serial.printf("Wakeup was not caused by deep sleep: %d\n",wakeup_reason); break;
  }
}
 
void setup() {
  Serial.begin(115200);
  pinMode(ONBOARD_LED,OUTPUT);

  /* Bluetooth */
  Serial.println("Starting BLE");
  BLEDevice::init("LeWe Garage Door Impulse");
  BLEServer *pServer = BLEDevice::createServer();

  pServer->setCallbacks(new MyServerCallbacks());
  
  BLEService *pService = pServer->createService(SERVICE_UUID);
  BLECharacteristic *pCharacteristic = pService->createCharacteristic(CHARACTERISTIC_UUID,BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  pCharacteristic->setValue("Hallo");
  pService->start();
  BLEAdvertising *pAdvertising = BLEDevice::getAdvertising();
  pAdvertising->addServiceUUID(SERVICE_UUID);
  pAdvertising->setScanResponse(true);
//  pAdvertising->setMinPreferred(0x06);  // functions that help with iPhone connections issue
//  pAdvertising->setMinPreferred(0x12);

//  BLEDevice::startAdvertising();
  pAdvertising->start();

  Serial.println("Bluetooth characteristic now active");


  /* Wait 10 seconds for the clients to find us */
  for (int i = 0; i < 10; i++) {
    delay(900);
    digitalWrite(ONBOARD_LED,HIGH);
    delay(100);
    digitalWrite(ONBOARD_LED,LOW);
  }


  /* Enter deep sleep */
/*  print_wakeup_reason();

  // configure wakeup source
  esp_sleep_enable_ext0_wakeup(GPIO_NUM_33,1); //1 = High, 0 = Low

  esp_deep_sleep_start();*/
}
 
void loop() {
  if (clientConnected) {
    Serial.println("Client connected");
  }

  for (int i = 0; i < 10; i++) {
    delay(400);
    digitalWrite(ONBOARD_LED,HIGH);
    delay(100);
    digitalWrite(ONBOARD_LED,LOW);
  }
}
