/**
 * A BLE client example that is rich in capabilities.
 * There is a lot new capabilities implemented.
 * author unknown
 * updated by chegewara
 */

#include "BLEDevice.h"
//#include "BLEScan.h"

// The remote service we wish to connect to.
//static BLEUUID serviceUUID("4fafc201-1fb5-459e-8fcc-c5c9c331914b");
// The characteristic of the remote service we are interested in.
//static BLEUUID    charUUID("beb5483e-36e1-4688-b7f5-ea07361b26a8");

static BLEUUID    serviceUUID("6e400001-b5a3-f393-e0a9-e50e24dcca9e");
static BLEUUID    charReadUUID("6e400003-b5a3-f393-e0a9-e50e24dcca9e");
static BLEUUID    charWriteUUID("6e400002-b5a3-f393-e0a9-e50e24dcca9e");


static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLERemoteCharacteristic* pRemoteCharacteristicRead;
static BLERemoteCharacteristic* pRemoteCharacteristicWrite;
static BLEAdvertisedDevice* myDevice;

static void notifyCallback(
  BLERemoteCharacteristic* pBLERemoteCharacteristic,
  uint8_t* pData,
  size_t length,
  bool isNotify) {
    Serial.print("Notify callback for characteristic:");
    Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
    Serial.print("of data length:");
    Serial.println(length);
    Serial.print("data: ");
    Serial.write(pData, length);
    Serial.println();
}

class MyClientCallback : public BLEClientCallbacks {
  void onConnect(BLEClient* pclient) {
  }

  void onDisconnect(BLEClient* pclient) {
    connected = false;
    Serial.println("onDisconnect");
  }
};

bool connectToServer() {
    Serial.print("Forming a connection to ");
    Serial.println(myDevice->getAddress().toString().c_str());
    
    BLEClient*  pClient  = BLEDevice::createClient();
    Serial.println(" - Created client");

    pClient->setClientCallbacks(new MyClientCallback());

    // Connect to the remove BLE Server.
    pClient->connect(myDevice);  // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
    Serial.println(" - Connected to server");
    pClient->setMTU(517); //set client to request maximum MTU from server (default is 23 otherwise)
  
    // Obtain a reference to the service we are after in the remote BLE server.
    BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
    if (pRemoteService == nullptr) {
      Serial.print("Failed to find our service UUID: ");
      Serial.println(serviceUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our service");


    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristicRead = pRemoteService->getCharacteristic(charReadUUID);
    if (pRemoteCharacteristicRead == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charReadUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Obtain a reference to the characteristic in the service of the remote BLE server.
    pRemoteCharacteristicWrite = pRemoteService->getCharacteristic(charWriteUUID);
    if (pRemoteCharacteristicWrite == nullptr) {
      Serial.print("Failed to find our characteristic UUID: ");
      Serial.println(charWriteUUID.toString().c_str());
      pClient->disconnect();
      return false;
    }
    Serial.println(" - Found our characteristic");

    // Read the value of the characteristic.
    if(pRemoteCharacteristicRead->canRead()) {
      //std::string value = pRemoteCharacteristicRead->readValue();
      String value = pRemoteCharacteristicRead->readValue();
      Serial.print("The characteristic value was: ");
      Serial.println(value.c_str());
    }

    if(pRemoteCharacteristicRead->canNotify())
      pRemoteCharacteristicRead->registerForNotify(notifyCallback);

    connected = true;
    return true;
}
/**
 * Scan for BLE servers and find the first one that advertises the service we are looking for.
 */
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
 /**
   * Called for each advertising BLE server.
   */
  void onResult(BLEAdvertisedDevice advertisedDevice) {
    Serial.print("BLE Advertised Device found: ");
    Serial.println(advertisedDevice.toString().c_str());

    // We have found a device, let us now see if it contains the service we are looking for.
    if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {

      BLEDevice::getScan()->stop();
      myDevice = new BLEAdvertisedDevice(advertisedDevice);
      doConnect = true;
      doScan = true;

    } // Found our server
  } // onResult
}; // MyAdvertisedDeviceCallbacks

// 使用工具函数发送16进制数据
void sendHexDataBle(String hexString) {
  uint8_t data[hexString.length()/2];
  // 将16进制字符串转换为字节数组
  for(int i = 0; i < hexString.length(); i += 2) {
    String byteString = hexString.substring(i, i+2);
    data[i/2] = (uint8_t)strtol(byteString.c_str(), NULL, 16);
  }
  pRemoteCharacteristicWrite->writeValue(data, sizeof(data));
  Serial.println("Setting new characteristic value to \"" + hexString + "\"");
}

// 使用工具函数发送字符串数据
void sendStringDataBle(String newValue) {
  //Set the characteristic's value to be the array of bytes that is actually a string.
  pRemoteCharacteristicWrite->writeValue(newValue.c_str(), newValue.length());
  Serial.println("Setting new characteristic value to \"" + newValue + "\"");
}

void setup() {
  Serial.begin(115200);
  Serial.println("Starting Arduino BLE Client application...");
  BLEDevice::init("");

  // Retrieve a Scanner and set the callback we want to use to be informed when we
  // have detected a new device.  Specify that we want active scanning and start the
  // scan to run for 5 seconds.
  BLEScan* pBLEScan = BLEDevice::getScan();
  pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
  pBLEScan->setInterval(1349);
  pBLEScan->setWindow(449);
  pBLEScan->setActiveScan(true);
  pBLEScan->start(5, false);
} // End of setup.


// This is the Arduino main loop function.
void loop() {

  // If the flag "doConnect" is true then we have scanned for and found the desired
  // BLE Server with which we wish to connect.  Now we connect to it.  Once we are 
  // connected we set the connected flag to be true.
  if (doConnect == true) {
    if (connectToServer()) {
      Serial.println("We are now connected to the BLE Server.");
    } else {
      Serial.println("We have failed to connect to the server; there is nothin more we will do.");
    }
    doConnect = false;
  }

  // If we are connected to a peer BLE Server, update the characteristic each time we are reached
  // with the current time since boot.
  if (connected) {
//    String newValue = "VR";//读固件版本号 false
    String newValue = "BV";//电量 false
//    String newValue = "0B0B6300";//温度测量 //无响应数据 true
//    String newValue = "4854";//温湿度测量 //无响应数据 true
//    String newValue = "1F13";//位移测量 //无响应数据 true
//    String newValue = "Time since boot: ";//
//    String newValue = "Time since boot: ";//
//    String newValue = "Time since boot: " + String(millis()/1000);//

    // 方法2: 使用字符串转换
    String hexString = "0B0B6301";//温度测量
//    String hexString = "4854";//温湿度测量
//    String hexString = "1F13";//位移测量
    uint8_t data[hexString.length()/2];
    
    // 将16进制字符串转换为字节数组
    for(int i = 0; i < hexString.length(); i += 2) {
      String byteString = hexString.substring(i, i+2);
      data[i/2] = (uint8_t)strtol(byteString.c_str(), NULL, 16);
    }
    //pRemoteCharacteristicWrite->writeValue(data, sizeof(data));
    sendHexDataBle(hexString);
    delay(2000);
    sendStringDataBle(newValue);

    
  }else if(doScan){
    BLEDevice::getScan()->start(0);  // this is just example to start scan after disconnect, most likely there is better way to do it in arduino
  }
  
  delay(10000); // Delay a second between loops.
} // End of loop
