WS_Bluetooth.cpp 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. #include "esp_gap_ble_api.h"
  2. #include "BLEUUID.h"
  3. #include "BLEAdvertising.h"
  4. #include "WS_Bluetooth.h"
  5. #include "WS_GPIO.h"
  6. #include <ArduinoJson.h>
  7. #include <MacroDebugger.h>
  8. BLEServer* pServer;
  9. BLEService* pConfigService;
  10. BLECharacteristic* pConfigCharacteristic;
  11. BLEService* pControlService;
  12. BLECharacteristic* pControlCharacteristic;
  13. BLEAdvertising *pAdvertising;
  14. bool requiresrestart = false;
  15. bool isBluetoothConnected = false;
  16. /********************************************************** Bluetooth *********************************************************/
  17. class ServerCallbacks : public BLEServerCallbacks {
  18. void onConnect(BLEServer* pServer) {
  19. DEBUGLN("BLE::Connect()");
  20. //pAdvertising->stop();
  21. isBluetoothConnected = true;
  22. }
  23. void onDisconnect(BLEServer* pServer) {
  24. DEBUGLN("BLE::Disconnect()");
  25. isBluetoothConnected = false;
  26. // BLEDevice::startAdvertising();
  27. // pConfigCharacteristic->notify();
  28. // if (pControlService)
  29. // pControlCharacteristic->notify();
  30. // pAdvertising->start();
  31. UpdateAdvertising();
  32. if (requiresrestart)
  33. Restart();
  34. }
  35. };
  36. class ConfigCharacteristicCallback : public BLECharacteristicCallbacks
  37. {
  38. void onRead(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param)
  39. {
  40. DEBUGLN("Config::Read()");
  41. JsonDocument doc;
  42. doc["warning"] = GetWarningNotice();
  43. doc["contact"] = GetContactInfo();
  44. String json = "";
  45. serializeJson(doc,json);
  46. pCharacteristic->setValue(json);
  47. }
  48. void onWrite(BLECharacteristic* pCharacteristic)
  49. {
  50. String json = pCharacteristic->getValue();
  51. DEBUGLN(json);
  52. JsonDocument doc;
  53. deserializeJson(doc, json);
  54. String name = doc["name"];
  55. String warning = doc["warning"];
  56. String contact = doc["contact"];
  57. String equipmentid = doc["id"];
  58. Configure(name,warning,contact,equipmentid);
  59. pCharacteristic->setValue("");
  60. requiresrestart = true;
  61. }
  62. };
  63. // char json[] = "{ \"Relay00\" : 15000, \"Relay01\" : 0, \"Relay02\" : 0, \"Relay03\" : 0, \"Relay04\" : 0, \"Relay05\" : 0 }"
  64. class ControlCharacteristicCallback : public BLECharacteristicCallbacks
  65. {
  66. void onWrite(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t *param)
  67. {
  68. String json = pCharacteristic->getValue();
  69. JsonDocument doc;
  70. deserializeJson(doc, json);
  71. char name[10];
  72. for (int i=0; i<6; i++)
  73. {
  74. sprintf(name,"Relay%02D",i);
  75. long time = doc[name];
  76. SetRelay(i,time);
  77. }
  78. pCharacteristic->setValue("");
  79. }
  80. // char json[] = "{ \"Relay00\" : true, \"Relay01\" : false, \"Relay02\" : false, \"Relay03\" : false, \"Relay04\" : false, \"Relay05\" : false }"
  81. void onRead(BLECharacteristic* pCharacteristic, esp_ble_gatts_cb_param_t* param)
  82. {
  83. DEBUGLN("Control::Read()");
  84. JsonDocument doc;
  85. char name[10];
  86. for (int i=0; i<6; i++)
  87. {
  88. sprintf(name,"Relay%02d",i);
  89. doc[name] = GetRelay(i);
  90. }
  91. String json;
  92. serializeJson(doc,json);
  93. pCharacteristic->setValue(json);
  94. }
  95. };
  96. bool IsConnected()
  97. {
  98. return isBluetoothConnected;
  99. }
  100. void UpdateAdvertising()
  101. {
  102. DEBUGLN("UpdateAdvertising()");
  103. pAdvertising->stop();
  104. BLEAdvertisementData advData;
  105. advData.addData(UUID32ToAdvertisingData(0xce6c0b18));
  106. if (pControlService)
  107. advData.addData(UUID128ToAdvertisingData(pControlService->getUUID()));
  108. advData.setManufacturerData(DeviceStatus());
  109. pAdvertising->setAdvertisementData(advData);
  110. pAdvertising->start();
  111. }
  112. String DeviceStatus()
  113. {
  114. String result;
  115. uint16_t companyID = 0x02E5; // Espressif's Bluetooth SIG company ID
  116. //uint16_t companyID = 0xFFFF; // Deliberately invalid for identification purposes
  117. result += (char)(companyID & 0xFF); // LSB
  118. result += (char)((companyID >> 8) & 0xFF); // MSB
  119. byte status = 0;
  120. if (RelayStatus(0))
  121. status += 1;
  122. if (RelayStatus(1))
  123. status += 2;
  124. if (RelayStatus(2))
  125. status += 4;
  126. if (RelayStatus(3))
  127. status += 8;
  128. if (RelayStatus(4))
  129. status += 16;
  130. if (RelayStatus(5))
  131. status += 32;
  132. result += (char)status;
  133. return result;
  134. }
  135. String UUID128ToAdvertisingData(BLEUUID uuid128) {
  136. String adField;
  137. // Get raw 16 bytes of the 128-bit UUID
  138. const uint8_t* uuidBytes = uuid128.getNative()->uuid.uuid128;
  139. // First byte: length (16 bytes data + 1 byte type)
  140. adField += (char)(16 + 1);
  141. // Second byte: type = 0x07 (complete list of 128-bit UUIDs)
  142. adField += (char)0x07;
  143. // Append 16 UUID bytes
  144. for (int i=0; i<16; i++) {
  145. adField += (char)(uuidBytes[i] & 0xFF);
  146. }
  147. return adField;
  148. }
  149. String UUID32ToAdvertisingData(uint32_t uuid32) {
  150. String adField;
  151. // 4 bytes of UUID + 1 byte type = 5 bytes total payload length
  152. adField += (char)(4 + 1); // total length
  153. adField += (char)0x05; // 0x05 = Complete List of 32-bit Service Class UUIDs
  154. // Append UUID in little-endian byte order
  155. adField += (char)(uuid32 & 0xFF);
  156. adField += (char)((uuid32 >> 8) & 0xFF);
  157. adField += (char)((uuid32 >> 16) & 0xFF);
  158. adField += (char)((uuid32 >> 24) & 0xFF);
  159. return adField;
  160. }
  161. void Bluetooth_Init()
  162. {
  163. /*************************************************************************
  164. Bluetooth
  165. *************************************************************************/
  166. DEBUGLN("Initialising BLE...");
  167. String devicename = GetDeviceName().substring(0,24);
  168. // Initialise the Device
  169. BLEDevice::init(devicename);
  170. pServer = BLEDevice::createServer();
  171. pServer->setCallbacks(new ServerCallbacks());
  172. pAdvertising = BLEDevice::getAdvertising();
  173. // Set up the Configuration interface (always)
  174. pConfigService = pServer->createService(CONFIG_SERVICE_UUID);
  175. pConfigCharacteristic = pConfigService->createCharacteristic(CONFIG_CHARACTERISTIC_UUID,
  176. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  177. pConfigCharacteristic->setCallbacks(new ConfigCharacteristicCallback());
  178. pConfigService->start();
  179. pAdvertising->addServiceUUID(CONFIG_SERVICE_UUID);
  180. String equipmentid = GetEquipmentId();
  181. if (!equipmentid.isEmpty() && !equipmentid.equalsIgnoreCase("00000000-0000-0000-0000-000000000000"))
  182. {
  183. pControlService = pServer->createService(equipmentid);
  184. pControlCharacteristic = pControlService->createCharacteristic(CONTROL_CHARACTERISTIC_UUID,
  185. BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE);
  186. pControlCharacteristic->setCallbacks(new ControlCharacteristicCallback());
  187. pControlService->start();
  188. pAdvertising->addServiceUUID(equipmentid);
  189. }
  190. //pAdvertising->setScanResponse(true);
  191. pAdvertising->setMinPreferred(0x06);
  192. pAdvertising->setMinPreferred(0x12);
  193. BLEDevice::startAdvertising();
  194. pConfigCharacteristic->notify();
  195. if (pControlCharacteristic)
  196. pControlCharacteristic->notify();
  197. pAdvertising->start();
  198. UpdateAdvertising();
  199. DEBUGLN("BLE Initialisation complete.");
  200. }