From 2e19b9ff5bff0ece845476bda82c40bdf5fbd747 Mon Sep 17 00:00:00 2001 From: 0xFEEDC0DE64 Date: Thu, 21 Jan 2021 23:11:37 +0100 Subject: [PATCH] Removed bullshit shitty files from shitty arduino developers who write shitty code --- CMakeLists.txt | 98 +- Kconfig.projbuild | 122 - cores/esp32/Arduino.h | 1 - cores/esp32/Esp.cpp | 389 ---- cores/esp32/Esp.h | 120 - .../ArduinoOTA/examples/BasicOTA/BasicOTA.ino | 68 - .../examples/OTAWebUpdater/OTAWebUpdater.ino | 169 -- libraries/ArduinoOTA/keywords.txt | 26 - libraries/ArduinoOTA/library.properties | 9 - libraries/ArduinoOTA/src/ArduinoOTA.cpp | 395 ---- libraries/ArduinoOTA/src/ArduinoOTA.h | 116 - libraries/BLE/README.md | 15 - .../examples/BLE_Beacon_Scanner/.skip.esp32s2 | 0 .../BLE_Beacon_Scanner/BLE_Beacon_Scanner.ino | 153 -- .../BLE_Beacon_Scanner/BLE_Beacon_Scanner.md | 9 - .../BLE_EddystoneTLM_Beacon/.skip.esp32s2 | 0 .../BLE_EddystoneTLM_Beacon.ino | 116 - .../BLE_EddystoneTLM_Beacon.md | 14 - .../BLE_EddystoneURL_Beacon/.skip.esp32s2 | 0 .../BLE_EddystoneURL_Beacon.ino | 192 -- .../BLE_EddystoneURL_Beacon.md | 14 - .../BLE/examples/BLE_client/.skip.esp32s2 | 0 .../BLE/examples/BLE_client/BLE_client.ino | 161 -- .../BLE/examples/BLE_iBeacon/.skip.esp32s2 | 0 .../BLE/examples/BLE_iBeacon/BLE_iBeacon.ino | 104 - .../BLE/examples/BLE_notify/.skip.esp32s2 | 0 .../BLE/examples/BLE_notify/BLE_notify.ino | 110 - libraries/BLE/examples/BLE_scan/.skip.esp32s2 | 0 libraries/BLE/examples/BLE_scan/BLE_scan.ino | 40 - .../BLE/examples/BLE_server/.skip.esp32s2 | 0 .../BLE/examples/BLE_server/BLE_server.ino | 45 - .../BLE_server_multiconnect/.skip.esp32s2 | 0 .../BLE_server_multiconnect.ino | 111 - libraries/BLE/examples/BLE_uart/.skip.esp32s2 | 0 libraries/BLE/examples/BLE_uart/BLE_uart.ino | 125 - .../BLE/examples/BLE_write/.skip.esp32s2 | 0 .../BLE/examples/BLE_write/BLE_write.ino | 65 - libraries/BLE/library.properties | 10 - libraries/BLE/src/BLE2902.cpp | 62 - libraries/BLE/src/BLE2902.h | 34 - libraries/BLE/src/BLE2904.cpp | 74 - libraries/BLE/src/BLE2904.h | 74 - libraries/BLE/src/BLEAddress.cpp | 94 - libraries/BLE/src/BLEAddress.h | 34 - libraries/BLE/src/BLEAdvertisedDevice.cpp | 575 ----- libraries/BLE/src/BLEAdvertisedDevice.h | 128 -- libraries/BLE/src/BLEAdvertising.cpp | 528 ----- libraries/BLE/src/BLEAdvertising.h | 81 - libraries/BLE/src/BLEBeacon.cpp | 83 - libraries/BLE/src/BLEBeacon.h | 43 - libraries/BLE/src/BLECharacteristic.cpp | 803 ------- libraries/BLE/src/BLECharacteristic.h | 154 -- libraries/BLE/src/BLECharacteristicMap.cpp | 134 -- libraries/BLE/src/BLEClient.cpp | 538 ----- libraries/BLE/src/BLEClient.h | 103 - libraries/BLE/src/BLEDescriptor.cpp | 287 --- libraries/BLE/src/BLEDescriptor.h | 77 - libraries/BLE/src/BLEDescriptorMap.cpp | 148 -- libraries/BLE/src/BLEDevice.cpp | 672 ------ libraries/BLE/src/BLEDevice.h | 100 - libraries/BLE/src/BLEEddystoneTLM.cpp | 146 -- libraries/BLE/src/BLEEddystoneTLM.h | 51 - libraries/BLE/src/BLEEddystoneURL.cpp | 148 -- libraries/BLE/src/BLEEddystoneURL.h | 43 - libraries/BLE/src/BLEExceptions.cpp | 9 - libraries/BLE/src/BLEExceptions.h | 31 - libraries/BLE/src/BLEHIDDevice.cpp | 244 -- libraries/BLE/src/BLEHIDDevice.h | 75 - libraries/BLE/src/BLERemoteCharacteristic.cpp | 616 ----- libraries/BLE/src/BLERemoteCharacteristic.h | 87 - libraries/BLE/src/BLERemoteDescriptor.cpp | 204 -- libraries/BLE/src/BLERemoteDescriptor.h | 58 - libraries/BLE/src/BLERemoteService.cpp | 362 --- libraries/BLE/src/BLERemoteService.h | 85 - libraries/BLE/src/BLEScan.cpp | 333 --- libraries/BLE/src/BLEScan.h | 85 - libraries/BLE/src/BLESecurity.cpp | 115 - libraries/BLE/src/BLESecurity.h | 73 - libraries/BLE/src/BLEServer.cpp | 426 ---- libraries/BLE/src/BLEServer.h | 141 -- libraries/BLE/src/BLEService.cpp | 413 ---- libraries/BLE/src/BLEService.h | 97 - libraries/BLE/src/BLEServiceMap.cpp | 137 -- libraries/BLE/src/BLEUUID.cpp | 386 ---- libraries/BLE/src/BLEUUID.h | 39 - libraries/BLE/src/BLEUtils.cpp | 2040 ----------------- libraries/BLE/src/BLEUtils.h | 63 - libraries/BLE/src/BLEValue.cpp | 130 -- libraries/BLE/src/BLEValue.h | 39 - libraries/BLE/src/FreeRTOS.cpp | 306 --- libraries/BLE/src/GeneralUtils.cpp | 541 ----- libraries/BLE/src/GeneralUtils.h | 35 - libraries/BLE/src/HIDKeyboardTypes.h | 402 ---- libraries/BLE/src/HIDTypes.h | 96 - libraries/BLE/src/RTOS.h | 81 - libraries/BluetoothSerial/README.md | 19 - .../examples/SerialToSerialBT/.skip.esp32s2 | 0 .../SerialToSerialBT/SerialToSerialBT.ino | 29 - .../examples/SerialToSerialBTM/.skip.esp32s2 | 0 .../SerialToSerialBTM/SerialToSerialBTM.ino | 56 - .../bt_remove_paired_devices/.skip.esp32s2 | 0 .../bt_remove_paired_devices.ino | 87 - libraries/BluetoothSerial/keywords.txt | 26 - libraries/BluetoothSerial/library.properties | 9 - .../BluetoothSerial/src/BluetoothSerial.cpp | 823 ------- .../BluetoothSerial/src/BluetoothSerial.h | 69 - .../examples/CaptivePortal/CaptivePortal.ino | 52 - libraries/DNSServer/library.properties | 9 - libraries/DNSServer/src/DNSServer.cpp | 210 -- libraries/DNSServer/src/DNSServer.h | 109 - libraries/EEPROM/README.md | 4 - .../examples/eeprom_class/eeprom_class.ino | 77 - .../examples/eeprom_extra/eeprom_extra.ino | 139 -- .../examples/eeprom_write/eeprom_write.ino | 63 - libraries/EEPROM/keywords.txt | 19 - libraries/EEPROM/library.properties | 9 - libraries/EEPROM/src/EEPROM.cpp | 557 ----- libraries/EEPROM/src/EEPROM.h | 122 - .../mDNS-SD_Extended/mDNS-SD_Extended.ino | 80 - .../mDNS_Web_Server/mDNS_Web_Server.ino | 120 - libraries/ESPmDNS/keywords.txt | 25 - libraries/ESPmDNS/library.properties | 9 - libraries/ESPmDNS/src/ESPmDNS.cpp | 345 --- libraries/ESPmDNS/src/ESPmDNS.h | 123 - .../FFat/examples/FFat_Test/FFat_Test.ino | 188 -- .../FFat/examples/FFat_time/FFat_time.ino | 177 -- libraries/FFat/library.properties | 9 - libraries/FFat/src/FFat.cpp | 181 -- libraries/FFat/src/FFat.h | 48 - .../examples/Authorization/Authorization.ino | 83 - .../BasicHttpClient/BasicHttpClient.ino | 101 - .../BasicHttpsClient/BasicHttpsClient.ino | 147 -- .../HTTPClientEnterprise.ino | 97 - .../ReuseConnection/ReuseConnection.ino | 68 - .../StreamHttpClient/StreamHttpClient.ino | 100 - libraries/HTTPClient/library.properties | 9 - libraries/HTTPClient/src/HTTPClient.cpp | 1456 ------------ libraries/HTTPClient/src/HTTPClient.h | 270 --- .../examples/httpUpdate/httpUpdate.ino | 72 - .../httpUpdateSPIFFS/httpUpdateSPIFFS.ino | 75 - .../httpUpdateSecure/httpUpdateSecure.ino | 128 -- libraries/HTTPUpdate/keywords.txt | 42 - libraries/HTTPUpdate/library.properties | 9 - libraries/HTTPUpdate/src/HTTPUpdate.cpp | 417 ---- libraries/HTTPUpdate/src/HTTPUpdate.h | 101 - .../examples/WebUpdater/WebUpdater.ino | 51 - libraries/HTTPUpdateServer/keywords.txt | 20 - libraries/HTTPUpdateServer/library.properties | 9 - .../HTTPUpdateServer/src/HTTPUpdateServer.h | 166 -- .../examples/LITTLEFS_PlatformIO/.gitignore | 4 - .../examples/LITTLEFS_PlatformIO/README.md | 68 - .../LITTLEFS_PlatformIO/data/file1.txt | 1 - .../data/testfolder/test2.txt | 1 - .../include/.placeholder.txt | 0 .../LITTLEFS_PlatformIO/lib/.placeholder.txt | 0 .../LITTLEFS_PlatformIO/littlefsbuilder.py | 2 - .../LITTLEFS_PlatformIO/partitions_custom.csv | 6 - .../LITTLEFS_PlatformIO/platformio.ini | 35 - .../examples/LITTLEFS_PlatformIO/src/main.cpp | 282 --- .../examples/LITTLEFS_test/LITTLEFS_test.ino | 272 --- .../examples/LITTLEFS_time/LITTLEFS_time.ino | 214 -- libraries/LITTLEFS/library.properties | 9 - libraries/LITTLEFS/src/LITTLEFS.cpp | 107 - libraries/LITTLEFS/src/LITTLEFS.h | 38 - .../NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino | 31 - libraries/NetBIOS/keywords.txt | 25 - libraries/NetBIOS/library.properties | 9 - libraries/NetBIOS/src/NetBIOS.cpp | 131 -- libraries/NetBIOS/src/NetBIOS.h | 26 - .../examples/Prefs2Struct/Prefs2Struct.ino | 43 - .../examples/StartCounter/StartCounter.ino | 56 - libraries/Preferences/keywords.txt | 54 - libraries/Preferences/library.properties | 9 - libraries/Preferences/src/Preferences.cpp | 512 ----- libraries/Preferences/src/Preferences.h | 77 - libraries/SD/README.md | 42 - libraries/SD/examples/SD_Test/SD_Test.ino | 221 -- libraries/SD/examples/SD_time/SD_time.ino | 213 -- libraries/SD/library.properties | 9 - libraries/SD/src/SD.cpp | 106 - libraries/SD/src/SD.h | 48 - libraries/SD/src/sd_defines.h | 25 - libraries/SD/src/sd_diskio.cpp | 777 ------- libraries/SD/src/sd_diskio.h | 31 - libraries/SD/src/sd_diskio_crc.c | 103 - .../SD_MMC/examples/SDMMC_Test/.skip.esp32s2 | 0 .../SD_MMC/examples/SDMMC_Test/SDMMC_Test.ino | 218 -- .../SD_MMC/examples/SDMMC_time/.skip.esp32s2 | 0 .../SD_MMC/examples/SDMMC_time/SDMMC_time.ino | 213 -- libraries/SD_MMC/library.properties | 9 - libraries/SD_MMC/src/SD_MMC.cpp | 148 -- libraries/SD_MMC/src/SD_MMC.h | 47 - libraries/SD_MMC/src/sd_defines.h | 25 - .../examples/SimpleBleDevice/.skip.esp32s2 | 0 .../SimpleBleDevice/SimpleBleDevice.ino | 52 - libraries/SimpleBLE/library.properties | 9 - libraries/SimpleBLE/src/SimpleBLE.cpp | 132 -- libraries/SimpleBLE/src/SimpleBLE.h | 65 - .../Ticker/examples/Arguments/Arguments.ino | 27 - libraries/Ticker/examples/Blinker/Blinker.ino | 42 - libraries/Ticker/keywords.txt | 14 - libraries/Ticker/library.properties | 9 - libraries/Ticker/src/Ticker.cpp | 58 - libraries/Ticker/src/Ticker.h | 107 - libraries/USB/examples/USBSerial/.skip.esp32 | 0 .../USB/examples/USBSerial/USBSerial.ino | 74 - libraries/USB/keywords.txt | 24 - libraries/USB/library.properties | 9 - libraries/USB/src/USB_NOT.h | 0 .../AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino | 283 --- .../AWS_S3_OTA_Update/StartCounter.ino.bin | Bin 357280 -> 0 bytes .../HTTPS_OTA_Update/HTTPS_OTA_Update.ino | 98 - .../examples/HTTPS_OTA_Update/Readme.md | 32 - .../Update/examples/SD_Update/SD_Update.ino | 112 - libraries/Update/keywords.txt | 24 - libraries/Update/library.properties | 9 - libraries/Update/src/HttpsOTAUpdate.cpp | 107 - libraries/Update/src/HttpsOTAUpdate.h | 21 - libraries/Update/src/Update.h | 191 -- libraries/Update/src/Updater.cpp | 392 ---- .../AdvancedWebServer/AdvancedWebServer.ino | 146 -- .../examples/FSBrowser/FSBrowser.ino | 303 --- .../examples/FSBrowser/data/edit.htm.gz | Bin 4116 -> 0 bytes .../examples/FSBrowser/data/favicon.ico | Bin 1150 -> 0 bytes .../examples/FSBrowser/data/graphs.js.gz | Bin 1971 -> 0 bytes .../examples/FSBrowser/data/index.htm | 97 - .../examples/HelloServer/HelloServer.ino | 73 - .../HttpAdvancedAuth/HttpAdvancedAuth.ino | 59 - .../examples/HttpBasicAuth/HttpBasicAuth.ino | 41 - .../examples/PathArgServer/PathArgServer.ino | 56 - .../examples/SDWebServer/SDWebServer.ino | 313 --- .../SDWebServer/SdRoot/edit/index.htm | 674 ------ .../examples/SDWebServer/SdRoot/index.htm | 22 - .../examples/SDWebServer/SdRoot/pins.png | Bin 177869 -> 0 bytes .../SimpleAuthentification.ino | 132 -- .../examples/WebUpdate/WebUpdate.ino | 69 - libraries/WebServer/keywords.txt | 38 - libraries/WebServer/library.properties | 9 - libraries/WebServer/src/HTTP_Method.h | 15 - libraries/WebServer/src/Parsing.cpp | 581 ----- libraries/WebServer/src/Uri.h | 29 - libraries/WebServer/src/WebServer.cpp | 704 ------ libraries/WebServer/src/WebServer.h | 211 -- .../WebServer/src/detail/RequestHandler.h | 31 - .../src/detail/RequestHandlersImpl.h | 151 -- libraries/WebServer/src/detail/mimetable.cpp | 35 - libraries/WebServer/src/detail/mimetable.h | 47 - libraries/WebServer/src/uri/UriBraces.h | 66 - libraries/WebServer/src/uri/UriGlob.h | 22 - libraries/WebServer/src/uri/UriRegex.h | 44 - .../WiFi/examples/ETH_LAN8720/.skip.esp32s2 | 0 .../WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino | 81 - .../WiFi/examples/ETH_TLK110/.skip.esp32s2 | 0 .../WiFi/examples/ETH_TLK110/ETH_TLK110.ino | 87 - .../SimpleWiFiServer/SimpleWiFiServer.ino | 116 - libraries/WiFi/examples/WPS/README.md | 104 - libraries/WiFi/examples/WPS/WPS.ino | 115 - .../WiFiAccessPoint/WiFiAccessPoint.ino | 93 - .../WiFiBlueToothSwitch/.skip.esp32s2 | 0 .../WiFiBlueToothSwitch.ino | 128 -- .../WiFi/examples/WiFiClient/WiFiClient.ino | 94 - .../WiFiClientBasic/WiFiClientBasic.ino | 87 - .../examples/WiFiClientEnterprise/README.md | 43 - .../WiFiClientEnterprise.ino | 68 - .../WiFiClientEvents/WiFiClientEvents.ino | 174 -- .../WiFiClientStaticIP/WiFiClientStaticIP.ino | 92 - libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino | 120 - .../WiFi/examples/WiFiMulti/WiFiMulti.ino | 35 - libraries/WiFi/examples/WiFiScan/WiFiScan.ino | 48 - .../WiFiSmartConfig/WiFiSmartConfig.ino | 36 - .../WiFiTelnetToSerial/WiFiTelnetToSerial.ino | 129 -- .../examples/WiFiUDPClient/WiFiUDPClient.ino | 76 - .../WiFi/examples/WiFiUDPClient/udp_server.py | 30 - .../WiFi/examples/WiFiUDPClient/udp_server.rb | 16 - libraries/WiFi/keywords.txt | 68 - libraries/WiFi/library.properties | 9 - libraries/WiFi/src/ETH.cpp | 452 ---- libraries/WiFi/src/ETH.h | 111 - libraries/WiFi/src/WiFi.cpp | 91 - libraries/WiFi/src/WiFi.h | 66 - libraries/WiFi/src/WiFiAP.cpp | 369 --- libraries/WiFi/src/WiFiAP.h | 65 - libraries/WiFi/src/WiFiClient.cpp | 605 ----- libraries/WiFi/src/WiFiClient.h | 108 - libraries/WiFi/src/WiFiGeneric.cpp | 1214 ---------- libraries/WiFi/src/WiFiGeneric.h | 200 -- libraries/WiFi/src/WiFiMulti.cpp | 204 -- libraries/WiFi/src/WiFiMulti.h | 51 - libraries/WiFi/src/WiFiSTA.cpp | 684 ------ libraries/WiFi/src/WiFiSTA.h | 105 - libraries/WiFi/src/WiFiScan.cpp | 308 --- libraries/WiFi/src/WiFiScan.h | 66 - libraries/WiFi/src/WiFiServer.cpp | 139 -- libraries/WiFi/src/WiFiServer.h | 61 - libraries/WiFi/src/WiFiType.h | 51 - libraries/WiFi/src/WiFiUdp.cpp | 281 --- libraries/WiFi/src/WiFiUdp.h | 77 - libraries/WiFiClientSecure/README.md | 68 - .../examples/WiFiClientPSK/WiFiClientPSK.ino | 85 - .../WiFiClientSecure/WiFiClientSecure.ino | 110 - .../WiFiClientSecureEnterprise.ino | 116 - libraries/WiFiClientSecure/keywords.txt | 35 - libraries/WiFiClientSecure/library.properties | 9 - .../WiFiClientSecure/src/WiFiClientSecure.cpp | 334 --- .../WiFiClientSecure/src/WiFiClientSecure.h | 108 - libraries/WiFiClientSecure/src/ssl_client.cpp | 453 ---- libraries/WiFiClientSecure/src/ssl_client.h | 40 - .../WiFiProv/examples/WiFiProv/README.md | 116 - .../WiFiProv/examples/WiFiProv/WiFiProv.ino | 57 - libraries/WiFiProv/library.properties | 8 - libraries/WiFiProv/src/WiFiProv.cpp | 176 -- libraries/WiFiProv/src/WiFiProv.h | 50 - 312 files changed, 2 insertions(+), 42000 deletions(-) delete mode 100644 cores/esp32/Esp.cpp delete mode 100644 cores/esp32/Esp.h delete mode 100644 libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino delete mode 100644 libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino delete mode 100644 libraries/ArduinoOTA/keywords.txt delete mode 100644 libraries/ArduinoOTA/library.properties delete mode 100644 libraries/ArduinoOTA/src/ArduinoOTA.cpp delete mode 100644 libraries/ArduinoOTA/src/ArduinoOTA.h delete mode 100644 libraries/BLE/README.md delete mode 100644 libraries/BLE/examples/BLE_Beacon_Scanner/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.ino delete mode 100644 libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.md delete mode 100644 libraries/BLE/examples/BLE_EddystoneTLM_Beacon/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.ino delete mode 100644 libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.md delete mode 100644 libraries/BLE/examples/BLE_EddystoneURL_Beacon/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.ino delete mode 100644 libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.md delete mode 100644 libraries/BLE/examples/BLE_client/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_client/BLE_client.ino delete mode 100644 libraries/BLE/examples/BLE_iBeacon/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino delete mode 100644 libraries/BLE/examples/BLE_notify/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_notify/BLE_notify.ino delete mode 100644 libraries/BLE/examples/BLE_scan/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_scan/BLE_scan.ino delete mode 100644 libraries/BLE/examples/BLE_server/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_server/BLE_server.ino delete mode 100644 libraries/BLE/examples/BLE_server_multiconnect/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino delete mode 100644 libraries/BLE/examples/BLE_uart/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_uart/BLE_uart.ino delete mode 100644 libraries/BLE/examples/BLE_write/.skip.esp32s2 delete mode 100644 libraries/BLE/examples/BLE_write/BLE_write.ino delete mode 100644 libraries/BLE/library.properties delete mode 100644 libraries/BLE/src/BLE2902.cpp delete mode 100644 libraries/BLE/src/BLE2902.h delete mode 100644 libraries/BLE/src/BLE2904.cpp delete mode 100644 libraries/BLE/src/BLE2904.h delete mode 100644 libraries/BLE/src/BLEAddress.cpp delete mode 100644 libraries/BLE/src/BLEAddress.h delete mode 100644 libraries/BLE/src/BLEAdvertisedDevice.cpp delete mode 100644 libraries/BLE/src/BLEAdvertisedDevice.h delete mode 100644 libraries/BLE/src/BLEAdvertising.cpp delete mode 100644 libraries/BLE/src/BLEAdvertising.h delete mode 100644 libraries/BLE/src/BLEBeacon.cpp delete mode 100644 libraries/BLE/src/BLEBeacon.h delete mode 100644 libraries/BLE/src/BLECharacteristic.cpp delete mode 100644 libraries/BLE/src/BLECharacteristic.h delete mode 100644 libraries/BLE/src/BLECharacteristicMap.cpp delete mode 100644 libraries/BLE/src/BLEClient.cpp delete mode 100644 libraries/BLE/src/BLEClient.h delete mode 100644 libraries/BLE/src/BLEDescriptor.cpp delete mode 100644 libraries/BLE/src/BLEDescriptor.h delete mode 100644 libraries/BLE/src/BLEDescriptorMap.cpp delete mode 100644 libraries/BLE/src/BLEDevice.cpp delete mode 100644 libraries/BLE/src/BLEDevice.h delete mode 100644 libraries/BLE/src/BLEEddystoneTLM.cpp delete mode 100644 libraries/BLE/src/BLEEddystoneTLM.h delete mode 100644 libraries/BLE/src/BLEEddystoneURL.cpp delete mode 100644 libraries/BLE/src/BLEEddystoneURL.h delete mode 100644 libraries/BLE/src/BLEExceptions.cpp delete mode 100644 libraries/BLE/src/BLEExceptions.h delete mode 100644 libraries/BLE/src/BLEHIDDevice.cpp delete mode 100644 libraries/BLE/src/BLEHIDDevice.h delete mode 100644 libraries/BLE/src/BLERemoteCharacteristic.cpp delete mode 100644 libraries/BLE/src/BLERemoteCharacteristic.h delete mode 100644 libraries/BLE/src/BLERemoteDescriptor.cpp delete mode 100644 libraries/BLE/src/BLERemoteDescriptor.h delete mode 100644 libraries/BLE/src/BLERemoteService.cpp delete mode 100644 libraries/BLE/src/BLERemoteService.h delete mode 100644 libraries/BLE/src/BLEScan.cpp delete mode 100644 libraries/BLE/src/BLEScan.h delete mode 100644 libraries/BLE/src/BLESecurity.cpp delete mode 100644 libraries/BLE/src/BLESecurity.h delete mode 100644 libraries/BLE/src/BLEServer.cpp delete mode 100644 libraries/BLE/src/BLEServer.h delete mode 100644 libraries/BLE/src/BLEService.cpp delete mode 100644 libraries/BLE/src/BLEService.h delete mode 100644 libraries/BLE/src/BLEServiceMap.cpp delete mode 100644 libraries/BLE/src/BLEUUID.cpp delete mode 100644 libraries/BLE/src/BLEUUID.h delete mode 100644 libraries/BLE/src/BLEUtils.cpp delete mode 100644 libraries/BLE/src/BLEUtils.h delete mode 100644 libraries/BLE/src/BLEValue.cpp delete mode 100644 libraries/BLE/src/BLEValue.h delete mode 100644 libraries/BLE/src/FreeRTOS.cpp delete mode 100644 libraries/BLE/src/GeneralUtils.cpp delete mode 100644 libraries/BLE/src/GeneralUtils.h delete mode 100644 libraries/BLE/src/HIDKeyboardTypes.h delete mode 100644 libraries/BLE/src/HIDTypes.h delete mode 100644 libraries/BLE/src/RTOS.h delete mode 100644 libraries/BluetoothSerial/README.md delete mode 100644 libraries/BluetoothSerial/examples/SerialToSerialBT/.skip.esp32s2 delete mode 100644 libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino delete mode 100644 libraries/BluetoothSerial/examples/SerialToSerialBTM/.skip.esp32s2 delete mode 100644 libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino delete mode 100644 libraries/BluetoothSerial/examples/bt_remove_paired_devices/.skip.esp32s2 delete mode 100755 libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino delete mode 100644 libraries/BluetoothSerial/keywords.txt delete mode 100644 libraries/BluetoothSerial/library.properties delete mode 100755 libraries/BluetoothSerial/src/BluetoothSerial.cpp delete mode 100755 libraries/BluetoothSerial/src/BluetoothSerial.h delete mode 100644 libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino delete mode 100644 libraries/DNSServer/library.properties delete mode 100644 libraries/DNSServer/src/DNSServer.cpp delete mode 100644 libraries/DNSServer/src/DNSServer.h delete mode 100644 libraries/EEPROM/README.md delete mode 100644 libraries/EEPROM/examples/eeprom_class/eeprom_class.ino delete mode 100644 libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino delete mode 100644 libraries/EEPROM/examples/eeprom_write/eeprom_write.ino delete mode 100644 libraries/EEPROM/keywords.txt delete mode 100644 libraries/EEPROM/library.properties delete mode 100644 libraries/EEPROM/src/EEPROM.cpp delete mode 100644 libraries/EEPROM/src/EEPROM.h delete mode 100644 libraries/ESPmDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino delete mode 100644 libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino delete mode 100644 libraries/ESPmDNS/keywords.txt delete mode 100644 libraries/ESPmDNS/library.properties delete mode 100644 libraries/ESPmDNS/src/ESPmDNS.cpp delete mode 100644 libraries/ESPmDNS/src/ESPmDNS.h delete mode 100644 libraries/FFat/examples/FFat_Test/FFat_Test.ino delete mode 100644 libraries/FFat/examples/FFat_time/FFat_time.ino delete mode 100644 libraries/FFat/library.properties delete mode 100644 libraries/FFat/src/FFat.cpp delete mode 100644 libraries/FFat/src/FFat.h delete mode 100644 libraries/HTTPClient/examples/Authorization/Authorization.ino delete mode 100644 libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino delete mode 100644 libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino delete mode 100644 libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino delete mode 100644 libraries/HTTPClient/examples/ReuseConnection/ReuseConnection.ino delete mode 100644 libraries/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino delete mode 100644 libraries/HTTPClient/library.properties delete mode 100644 libraries/HTTPClient/src/HTTPClient.cpp delete mode 100644 libraries/HTTPClient/src/HTTPClient.h delete mode 100644 libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino delete mode 100644 libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino delete mode 100644 libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino delete mode 100644 libraries/HTTPUpdate/keywords.txt delete mode 100644 libraries/HTTPUpdate/library.properties delete mode 100644 libraries/HTTPUpdate/src/HTTPUpdate.cpp delete mode 100644 libraries/HTTPUpdate/src/HTTPUpdate.h delete mode 100644 libraries/HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino delete mode 100644 libraries/HTTPUpdateServer/keywords.txt delete mode 100644 libraries/HTTPUpdateServer/library.properties delete mode 100644 libraries/HTTPUpdateServer/src/HTTPUpdateServer.h delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/.gitignore delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/README.md delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/file1.txt delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/testfolder/test2.txt delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/include/.placeholder.txt delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/lib/.placeholder.txt delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/littlefsbuilder.py delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/partitions_custom.csv delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/platformio.ini delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/src/main.cpp delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_test/LITTLEFS_test.ino delete mode 100644 libraries/LITTLEFS/examples/LITTLEFS_time/LITTLEFS_time.ino delete mode 100644 libraries/LITTLEFS/library.properties delete mode 100644 libraries/LITTLEFS/src/LITTLEFS.cpp delete mode 100644 libraries/LITTLEFS/src/LITTLEFS.h delete mode 100755 libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino delete mode 100755 libraries/NetBIOS/keywords.txt delete mode 100644 libraries/NetBIOS/library.properties delete mode 100755 libraries/NetBIOS/src/NetBIOS.cpp delete mode 100755 libraries/NetBIOS/src/NetBIOS.h delete mode 100644 libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino delete mode 100644 libraries/Preferences/examples/StartCounter/StartCounter.ino delete mode 100644 libraries/Preferences/keywords.txt delete mode 100644 libraries/Preferences/library.properties delete mode 100644 libraries/Preferences/src/Preferences.cpp delete mode 100644 libraries/Preferences/src/Preferences.h delete mode 100644 libraries/SD/README.md delete mode 100644 libraries/SD/examples/SD_Test/SD_Test.ino delete mode 100644 libraries/SD/examples/SD_time/SD_time.ino delete mode 100644 libraries/SD/library.properties delete mode 100644 libraries/SD/src/SD.cpp delete mode 100644 libraries/SD/src/SD.h delete mode 100644 libraries/SD/src/sd_defines.h delete mode 100644 libraries/SD/src/sd_diskio.cpp delete mode 100644 libraries/SD/src/sd_diskio.h delete mode 100644 libraries/SD/src/sd_diskio_crc.c delete mode 100644 libraries/SD_MMC/examples/SDMMC_Test/.skip.esp32s2 delete mode 100644 libraries/SD_MMC/examples/SDMMC_Test/SDMMC_Test.ino delete mode 100644 libraries/SD_MMC/examples/SDMMC_time/.skip.esp32s2 delete mode 100644 libraries/SD_MMC/examples/SDMMC_time/SDMMC_time.ino delete mode 100644 libraries/SD_MMC/library.properties delete mode 100644 libraries/SD_MMC/src/SD_MMC.cpp delete mode 100644 libraries/SD_MMC/src/SD_MMC.h delete mode 100644 libraries/SD_MMC/src/sd_defines.h delete mode 100644 libraries/SimpleBLE/examples/SimpleBleDevice/.skip.esp32s2 delete mode 100644 libraries/SimpleBLE/examples/SimpleBleDevice/SimpleBleDevice.ino delete mode 100644 libraries/SimpleBLE/library.properties delete mode 100644 libraries/SimpleBLE/src/SimpleBLE.cpp delete mode 100644 libraries/SimpleBLE/src/SimpleBLE.h delete mode 100644 libraries/Ticker/examples/Arguments/Arguments.ino delete mode 100644 libraries/Ticker/examples/Blinker/Blinker.ino delete mode 100644 libraries/Ticker/keywords.txt delete mode 100644 libraries/Ticker/library.properties delete mode 100644 libraries/Ticker/src/Ticker.cpp delete mode 100644 libraries/Ticker/src/Ticker.h delete mode 100644 libraries/USB/examples/USBSerial/.skip.esp32 delete mode 100644 libraries/USB/examples/USBSerial/USBSerial.ino delete mode 100644 libraries/USB/keywords.txt delete mode 100644 libraries/USB/library.properties delete mode 100644 libraries/USB/src/USB_NOT.h delete mode 100644 libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino delete mode 100644 libraries/Update/examples/AWS_S3_OTA_Update/StartCounter.ino.bin delete mode 100644 libraries/Update/examples/HTTPS_OTA_Update/HTTPS_OTA_Update.ino delete mode 100644 libraries/Update/examples/HTTPS_OTA_Update/Readme.md delete mode 100644 libraries/Update/examples/SD_Update/SD_Update.ino delete mode 100644 libraries/Update/keywords.txt delete mode 100644 libraries/Update/library.properties delete mode 100644 libraries/Update/src/HttpsOTAUpdate.cpp delete mode 100644 libraries/Update/src/HttpsOTAUpdate.h delete mode 100644 libraries/Update/src/Update.h delete mode 100644 libraries/Update/src/Updater.cpp delete mode 100644 libraries/WebServer/examples/AdvancedWebServer/AdvancedWebServer.ino delete mode 100644 libraries/WebServer/examples/FSBrowser/FSBrowser.ino delete mode 100644 libraries/WebServer/examples/FSBrowser/data/edit.htm.gz delete mode 100644 libraries/WebServer/examples/FSBrowser/data/favicon.ico delete mode 100644 libraries/WebServer/examples/FSBrowser/data/graphs.js.gz delete mode 100644 libraries/WebServer/examples/FSBrowser/data/index.htm delete mode 100644 libraries/WebServer/examples/HelloServer/HelloServer.ino delete mode 100644 libraries/WebServer/examples/HttpAdvancedAuth/HttpAdvancedAuth.ino delete mode 100644 libraries/WebServer/examples/HttpBasicAuth/HttpBasicAuth.ino delete mode 100644 libraries/WebServer/examples/PathArgServer/PathArgServer.ino delete mode 100644 libraries/WebServer/examples/SDWebServer/SDWebServer.ino delete mode 100644 libraries/WebServer/examples/SDWebServer/SdRoot/edit/index.htm delete mode 100644 libraries/WebServer/examples/SDWebServer/SdRoot/index.htm delete mode 100644 libraries/WebServer/examples/SDWebServer/SdRoot/pins.png delete mode 100644 libraries/WebServer/examples/SimpleAuthentification/SimpleAuthentification.ino delete mode 100644 libraries/WebServer/examples/WebUpdate/WebUpdate.ino delete mode 100644 libraries/WebServer/keywords.txt delete mode 100644 libraries/WebServer/library.properties delete mode 100644 libraries/WebServer/src/HTTP_Method.h delete mode 100644 libraries/WebServer/src/Parsing.cpp delete mode 100644 libraries/WebServer/src/Uri.h delete mode 100644 libraries/WebServer/src/WebServer.cpp delete mode 100644 libraries/WebServer/src/WebServer.h delete mode 100644 libraries/WebServer/src/detail/RequestHandler.h delete mode 100644 libraries/WebServer/src/detail/RequestHandlersImpl.h delete mode 100644 libraries/WebServer/src/detail/mimetable.cpp delete mode 100644 libraries/WebServer/src/detail/mimetable.h delete mode 100644 libraries/WebServer/src/uri/UriBraces.h delete mode 100644 libraries/WebServer/src/uri/UriGlob.h delete mode 100644 libraries/WebServer/src/uri/UriRegex.h delete mode 100644 libraries/WiFi/examples/ETH_LAN8720/.skip.esp32s2 delete mode 100644 libraries/WiFi/examples/ETH_LAN8720/ETH_LAN8720.ino delete mode 100644 libraries/WiFi/examples/ETH_TLK110/.skip.esp32s2 delete mode 100644 libraries/WiFi/examples/ETH_TLK110/ETH_TLK110.ino delete mode 100644 libraries/WiFi/examples/SimpleWiFiServer/SimpleWiFiServer.ino delete mode 100644 libraries/WiFi/examples/WPS/README.md delete mode 100644 libraries/WiFi/examples/WPS/WPS.ino delete mode 100644 libraries/WiFi/examples/WiFiAccessPoint/WiFiAccessPoint.ino delete mode 100644 libraries/WiFi/examples/WiFiBlueToothSwitch/.skip.esp32s2 delete mode 100644 libraries/WiFi/examples/WiFiBlueToothSwitch/WiFiBlueToothSwitch.ino delete mode 100644 libraries/WiFi/examples/WiFiClient/WiFiClient.ino delete mode 100644 libraries/WiFi/examples/WiFiClientBasic/WiFiClientBasic.ino delete mode 100644 libraries/WiFi/examples/WiFiClientEnterprise/README.md delete mode 100644 libraries/WiFi/examples/WiFiClientEnterprise/WiFiClientEnterprise.ino delete mode 100644 libraries/WiFi/examples/WiFiClientEvents/WiFiClientEvents.ino delete mode 100644 libraries/WiFi/examples/WiFiClientStaticIP/WiFiClientStaticIP.ino delete mode 100644 libraries/WiFi/examples/WiFiIPv6/WiFiIPv6.ino delete mode 100644 libraries/WiFi/examples/WiFiMulti/WiFiMulti.ino delete mode 100644 libraries/WiFi/examples/WiFiScan/WiFiScan.ino delete mode 100644 libraries/WiFi/examples/WiFiSmartConfig/WiFiSmartConfig.ino delete mode 100644 libraries/WiFi/examples/WiFiTelnetToSerial/WiFiTelnetToSerial.ino delete mode 100644 libraries/WiFi/examples/WiFiUDPClient/WiFiUDPClient.ino delete mode 100644 libraries/WiFi/examples/WiFiUDPClient/udp_server.py delete mode 100644 libraries/WiFi/examples/WiFiUDPClient/udp_server.rb delete mode 100644 libraries/WiFi/keywords.txt delete mode 100644 libraries/WiFi/library.properties delete mode 100644 libraries/WiFi/src/ETH.cpp delete mode 100644 libraries/WiFi/src/ETH.h delete mode 100644 libraries/WiFi/src/WiFi.cpp delete mode 100644 libraries/WiFi/src/WiFi.h delete mode 100644 libraries/WiFi/src/WiFiAP.cpp delete mode 100644 libraries/WiFi/src/WiFiAP.h delete mode 100644 libraries/WiFi/src/WiFiClient.cpp delete mode 100644 libraries/WiFi/src/WiFiClient.h delete mode 100644 libraries/WiFi/src/WiFiGeneric.cpp delete mode 100644 libraries/WiFi/src/WiFiGeneric.h delete mode 100644 libraries/WiFi/src/WiFiMulti.cpp delete mode 100644 libraries/WiFi/src/WiFiMulti.h delete mode 100644 libraries/WiFi/src/WiFiSTA.cpp delete mode 100644 libraries/WiFi/src/WiFiSTA.h delete mode 100644 libraries/WiFi/src/WiFiScan.cpp delete mode 100644 libraries/WiFi/src/WiFiScan.h delete mode 100644 libraries/WiFi/src/WiFiServer.cpp delete mode 100644 libraries/WiFi/src/WiFiServer.h delete mode 100644 libraries/WiFi/src/WiFiType.h delete mode 100644 libraries/WiFi/src/WiFiUdp.cpp delete mode 100644 libraries/WiFi/src/WiFiUdp.h delete mode 100644 libraries/WiFiClientSecure/README.md delete mode 100644 libraries/WiFiClientSecure/examples/WiFiClientPSK/WiFiClientPSK.ino delete mode 100644 libraries/WiFiClientSecure/examples/WiFiClientSecure/WiFiClientSecure.ino delete mode 100644 libraries/WiFiClientSecure/examples/WiFiClientSecureEnterprise/WiFiClientSecureEnterprise.ino delete mode 100644 libraries/WiFiClientSecure/keywords.txt delete mode 100644 libraries/WiFiClientSecure/library.properties delete mode 100644 libraries/WiFiClientSecure/src/WiFiClientSecure.cpp delete mode 100644 libraries/WiFiClientSecure/src/WiFiClientSecure.h delete mode 100644 libraries/WiFiClientSecure/src/ssl_client.cpp delete mode 100644 libraries/WiFiClientSecure/src/ssl_client.h delete mode 100644 libraries/WiFiProv/examples/WiFiProv/README.md delete mode 100644 libraries/WiFiProv/examples/WiFiProv/WiFiProv.ino delete mode 100644 libraries/WiFiProv/library.properties delete mode 100644 libraries/WiFiProv/src/WiFiProv.cpp delete mode 100644 libraries/WiFiProv/src/WiFiProv.h diff --git a/CMakeLists.txt b/CMakeLists.txt index afd1bc11..a73f7a55 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -19,7 +19,6 @@ set(CORE_SRCS cores/esp32/esp32-hal-touch.c cores/esp32/esp32-hal-uart.c cores/esp32/esp32-hal-rmt.c - cores/esp32/Esp.cpp cores/esp32/FunctionalInterrupt.cpp cores/esp32/HardwareSerial.cpp cores/esp32/IPAddress.cpp @@ -41,120 +40,27 @@ set(CORE_SRCS ) set(LIBRARY_SRCS - libraries/ArduinoOTA/src/ArduinoOTA.cpp libraries/AsyncUDP/src/AsyncUDP.cpp - libraries/BluetoothSerial/src/BluetoothSerial.cpp - libraries/DNSServer/src/DNSServer.cpp - libraries/EEPROM/src/EEPROM.cpp - libraries/ESPmDNS/src/ESPmDNS.cpp - libraries/FFat/src/FFat.cpp libraries/FS/src/FS.cpp libraries/FS/src/vfs_api.cpp - libraries/HTTPClient/src/HTTPClient.cpp - libraries/HTTPUpdate/src/HTTPUpdate.cpp - # Removed due https://github.com/espressif/arduino-esp32/issues/4629 - #libraries/LITTLEFS/src/LITTLEFS.cpp - libraries/NetBIOS/src/NetBIOS.cpp - libraries/Preferences/src/Preferences.cpp - libraries/SD_MMC/src/SD_MMC.cpp - libraries/SD/src/SD.cpp - libraries/SD/src/sd_diskio.cpp - libraries/SD/src/sd_diskio_crc.c - libraries/SimpleBLE/src/SimpleBLE.cpp libraries/SPIFFS/src/SPIFFS.cpp - libraries/SPI/src/SPI.cpp - libraries/Ticker/src/Ticker.cpp - libraries/Update/src/Updater.cpp - libraries/Update/src/HttpsOTAUpdate.cpp - libraries/WebServer/src/WebServer.cpp - libraries/WebServer/src/Parsing.cpp - libraries/WebServer/src/detail/mimetable.cpp - libraries/WiFiClientSecure/src/ssl_client.cpp - libraries/WiFiClientSecure/src/WiFiClientSecure.cpp - libraries/WiFi/src/ETH.cpp - libraries/WiFi/src/WiFiAP.cpp - libraries/WiFi/src/WiFiClient.cpp - libraries/WiFi/src/WiFi.cpp - libraries/WiFi/src/WiFiGeneric.cpp - libraries/WiFi/src/WiFiMulti.cpp - libraries/WiFi/src/WiFiScan.cpp - libraries/WiFi/src/WiFiServer.cpp - libraries/WiFi/src/WiFiSTA.cpp - libraries/WiFi/src/WiFiUdp.cpp - libraries/WiFiProv/src/WiFiProv.cpp libraries/Wire/src/Wire.cpp ) -set(BLE_SRCS - libraries/BLE/src/BLE2902.cpp - libraries/BLE/src/BLE2904.cpp - libraries/BLE/src/BLEAddress.cpp - libraries/BLE/src/BLEAdvertisedDevice.cpp - libraries/BLE/src/BLEAdvertising.cpp - libraries/BLE/src/BLEBeacon.cpp - libraries/BLE/src/BLECharacteristic.cpp - libraries/BLE/src/BLECharacteristicMap.cpp - libraries/BLE/src/BLEClient.cpp - libraries/BLE/src/BLEDescriptor.cpp - libraries/BLE/src/BLEDescriptorMap.cpp - libraries/BLE/src/BLEDevice.cpp - libraries/BLE/src/BLEEddystoneTLM.cpp - libraries/BLE/src/BLEEddystoneURL.cpp - libraries/BLE/src/BLEExceptions.cpp - libraries/BLE/src/BLEHIDDevice.cpp - libraries/BLE/src/BLERemoteCharacteristic.cpp - libraries/BLE/src/BLERemoteDescriptor.cpp - libraries/BLE/src/BLERemoteService.cpp - libraries/BLE/src/BLEScan.cpp - libraries/BLE/src/BLESecurity.cpp - libraries/BLE/src/BLEServer.cpp - libraries/BLE/src/BLEService.cpp - libraries/BLE/src/BLEServiceMap.cpp - libraries/BLE/src/BLEUtils.cpp - libraries/BLE/src/BLEUUID.cpp - libraries/BLE/src/BLEValue.cpp - libraries/BLE/src/FreeRTOS.cpp - libraries/BLE/src/GeneralUtils.cpp - ) - set(includedirs variants/esp32/ cores/esp32/ - libraries/ArduinoOTA/src libraries/AsyncUDP/src - libraries/BLE/src - libraries/BluetoothSerial/src - libraries/DNSServer/src - libraries/EEPROM/src - libraries/ESP32/src - libraries/ESPmDNS/src - libraries/FFat/src libraries/FS/src - libraries/HTTPClient/src - libraries/HTTPUpdate/src - # Removed due https://github.com/espressif/arduino-esp32/issues/4629 - #libraries/LITTLEFS/src - libraries/NetBIOS/src - libraries/Preferences/src - libraries/SD_MMC/src - libraries/SD/src - libraries/SimpleBLE/src libraries/SPIFFS/src - libraries/SPI/src - libraries/Ticker/src - libraries/Update/src - libraries/WebServer/src - libraries/WiFiClientSecure/src - libraries/WiFi/src - libraries/WiFiProv/src libraries/Wire/src ) set(srcs ${CORE_SRCS} ${LIBRARY_SRCS} ${BLE_SRCS}) set(priv_includes cores/esp32/libb64) -set(requires spi_flash mbedtls mdns esp_adc_cal wifi_provisioning esp_https_ota) -set(priv_requires fatfs nvs_flash app_update spiffs bootloader_support openssl bt tinyusb main) +set(requires spi_flash mbedtls esp_adc_cal wifi_provisioning) +set(priv_requires nvs_flash spiffs bootloader_support openssl tinyusb main) idf_component_register(INCLUDE_DIRS ${includedirs} PRIV_INCLUDE_DIRS ${priv_includes} SRCS ${srcs} REQUIRES ${requires} PRIV_REQUIRES ${priv_requires}) diff --git a/Kconfig.projbuild b/Kconfig.projbuild index df1cf496..ca26ee36 100644 --- a/Kconfig.projbuild +++ b/Kconfig.projbuild @@ -184,115 +184,20 @@ config ARDUHAL_PARTITION_SCHEME default "min_spiffs" if ARDUHAL_PARTITION_SCHEME_MIN_SPIFFS -config AUTOCONNECT_WIFI - bool "Autoconnect WiFi on boot" - default "n" - depends on AUTOSTART_ARDUINO - select ARDUINO_SELECTIVE_WiFi - help - If enabled, WiFi will connect to the last used SSID (if station was enabled), - else connection will be started only after calling WiFi.begin(ssid, password) - config ARDUINO_SELECTIVE_COMPILATION bool "Include only specific Arduino libraries" default n -config ARDUINO_SELECTIVE_ArduinoOTA - bool "Enable ArduinoOTA" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - select ARDUINO_SELECTIVE_ESPmDNS - default y - config ARDUINO_SELECTIVE_AsyncUDP bool "Enable AsyncUDP" depends on ARDUINO_SELECTIVE_COMPILATION default y -config ARDUINO_SELECTIVE_AzureIoT - bool "Enable AzureIoT" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_HTTPClient - default y - -config ARDUINO_SELECTIVE_BLE - bool "Enable BLE" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_BluetoothSerial - bool "Enable BluetoothSerial" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_DNSServer - bool "Enable DNSServer" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - default y - -config ARDUINO_SELECTIVE_EEPROM - bool "Enable EEPROM" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_ESP32 - bool "Enable ESP32" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_ESPmDNS - bool "Enable ESPmDNS" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - default y - -config ARDUINO_SELECTIVE_FFat - bool "Enable FFat" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_FS - default y - config ARDUINO_SELECTIVE_FS bool "Enable FS" depends on ARDUINO_SELECTIVE_COMPILATION default y -config ARDUINO_SELECTIVE_HTTPClient - bool "Enable HTTPClient" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - select ARDUINO_SELECTIVE_WiFiClientSecure - default y - -config ARDUINO_SELECTIVE_NetBIOS - bool "Enable NetBIOS" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - default y - -config ARDUINO_SELECTIVE_Preferences - bool "Enable Preferences" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_SD - bool "Enable SD" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_FS - default y - -config ARDUINO_SELECTIVE_SD_MMC - bool "Enable SD_MMC" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_FS - default y - -config ARDUINO_SELECTIVE_SimpleBLE - bool "Enable SimpleBLE" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - config ARDUINO_SELECTIVE_SPI bool "Enable SPI" depends on ARDUINO_SELECTIVE_COMPILATION @@ -304,33 +209,6 @@ config ARDUINO_SELECTIVE_SPIFFS select ARDUINO_SELECTIVE_FS default y -config ARDUINO_SELECTIVE_Ticker - bool "Enable Ticker" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_Update - bool "Enable Update" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_WebServer - bool "Enable WebServer" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - select ARDUINO_SELECTIVE_FS - -config ARDUINO_SELECTIVE_WiFi - bool "Enable WiFi" - depends on ARDUINO_SELECTIVE_COMPILATION - default y - -config ARDUINO_SELECTIVE_WiFiClientSecure - bool "Enable WiFiClientSecure" - depends on ARDUINO_SELECTIVE_COMPILATION - select ARDUINO_SELECTIVE_WiFi - default y - config ARDUINO_SELECTIVE_Wire bool "Enable Wire" depends on ARDUINO_SELECTIVE_COMPILATION diff --git a/cores/esp32/Arduino.h b/cores/esp32/Arduino.h index 570a7442..cf140343 100644 --- a/cores/esp32/Arduino.h +++ b/cores/esp32/Arduino.h @@ -155,7 +155,6 @@ void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val); #include "Server.h" #include "Udp.h" #include "HardwareSerial.h" -#include "Esp.h" using std::abs; using std::isinf; diff --git a/cores/esp32/Esp.cpp b/cores/esp32/Esp.cpp deleted file mode 100644 index 0220c989..00000000 --- a/cores/esp32/Esp.cpp +++ /dev/null @@ -1,389 +0,0 @@ -/* - Esp.cpp - ESP31B-specific APIs - Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#include "Arduino.h" -#include "Esp.h" -#include "esp_sleep.h" -#include "esp_spi_flash.h" -#include -#include -#include -extern "C" { -#include "esp_ota_ops.h" -#include "esp_image_format.h" -} -#include - -#include "esp_system.h" -#ifdef ESP_IDF_VERSION_MAJOR // IDF 4+ -#if CONFIG_IDF_TARGET_ESP32 // ESP32/PICO-D4 -#include "esp32/rom/spi_flash.h" -#include "soc/efuse_reg.h" -#elif CONFIG_IDF_TARGET_ESP32S2 -#include "esp32s2/rom/spi_flash.h" -#else -#error Target CONFIG_IDF_TARGET is not supported -#endif -#else // ESP32 Before IDF 4.0 -#include "rom/spi_flash.h" -#endif - -/** - * User-defined Literals - * usage: - * - * uint32_t = test = 10_MHz; // --> 10000000 - */ - -unsigned long long operator"" _kHz(unsigned long long x) -{ - return x * 1000; -} - -unsigned long long operator"" _MHz(unsigned long long x) -{ - return x * 1000 * 1000; -} - -unsigned long long operator"" _GHz(unsigned long long x) -{ - return x * 1000 * 1000 * 1000; -} - -unsigned long long operator"" _kBit(unsigned long long x) -{ - return x * 1024; -} - -unsigned long long operator"" _MBit(unsigned long long x) -{ - return x * 1024 * 1024; -} - -unsigned long long operator"" _GBit(unsigned long long x) -{ - return x * 1024 * 1024 * 1024; -} - -unsigned long long operator"" _kB(unsigned long long x) -{ - return x * 1024; -} - -unsigned long long operator"" _MB(unsigned long long x) -{ - return x * 1024 * 1024; -} - -unsigned long long operator"" _GB(unsigned long long x) -{ - return x * 1024 * 1024 * 1024; -} - - -EspClass ESP; - -void EspClass::deepSleep(uint32_t time_us) -{ - esp_deep_sleep(time_us); -} - -void EspClass::restart(void) -{ - esp_restart(); -} - -uint32_t EspClass::getHeapSize(void) -{ - multi_heap_info_t info; - heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); - return info.total_free_bytes + info.total_allocated_bytes; -} - -uint32_t EspClass::getFreeHeap(void) -{ - return heap_caps_get_free_size(MALLOC_CAP_INTERNAL); -} - -uint32_t EspClass::getMinFreeHeap(void) -{ - return heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL); -} - -uint32_t EspClass::getMaxAllocHeap(void) -{ - return heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL); -} - -uint32_t EspClass::getPsramSize(void) -{ - if(psramFound()){ - multi_heap_info_t info; - heap_caps_get_info(&info, MALLOC_CAP_SPIRAM); - return info.total_free_bytes + info.total_allocated_bytes; - } - return 0; -} - -uint32_t EspClass::getFreePsram(void) -{ - if(psramFound()){ - return heap_caps_get_free_size(MALLOC_CAP_SPIRAM); - } - return 0; -} - -uint32_t EspClass::getMinFreePsram(void) -{ - if(psramFound()){ - return heap_caps_get_minimum_free_size(MALLOC_CAP_SPIRAM); - } - return 0; -} - -uint32_t EspClass::getMaxAllocPsram(void) -{ - if(psramFound()){ - return heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM); - } - return 0; -} - -static uint32_t sketchSize(sketchSize_t response) { - esp_image_metadata_t data; - const esp_partition_t *running = esp_ota_get_running_partition(); - if (!running) return 0; - const esp_partition_pos_t running_pos = { - .offset = running->address, - .size = running->size, - }; - data.start_addr = running_pos.offset; - esp_image_verify(ESP_IMAGE_VERIFY, &running_pos, &data); - if (response) { - return running_pos.size - data.image_len; - } else { - return data.image_len; - } -} - -uint32_t EspClass::getSketchSize () { - return sketchSize(SKETCH_SIZE_TOTAL); -} - -String EspClass::getSketchMD5() -{ - static String result; - if (result.length()) { - return result; - } - uint32_t lengthLeft = getSketchSize(); - - const esp_partition_t *running = esp_ota_get_running_partition(); - if (!running) { - log_e("Partition could not be found"); - - return String(); - } - const size_t bufSize = SPI_FLASH_SEC_SIZE; - std::unique_ptr buf(new uint8_t[bufSize]); - uint32_t offset = 0; - if(!buf.get()) { - log_e("Not enough memory to allocate buffer"); - - return String(); - } - MD5Builder md5; - md5.begin(); - while( lengthLeft > 0) { - size_t readBytes = (lengthLeft < bufSize) ? lengthLeft : bufSize; - if (!ESP.flashRead(running->address + offset, reinterpret_cast(buf.get()), (readBytes + 3) & ~3)) { - log_e("Could not read buffer from flash"); - - return String(); - } - md5.add(buf.get(), readBytes); - lengthLeft -= readBytes; - offset += readBytes; - } - md5.calculate(); - result = md5.toString(); - return result; -} - -uint32_t EspClass::getFreeSketchSpace () { - const esp_partition_t* _partition = esp_ota_get_next_update_partition(NULL); - if(!_partition){ - return 0; - } - - return _partition->size; -} - -uint8_t EspClass::getChipRevision(void) -{ - esp_chip_info_t chip_info; - esp_chip_info(&chip_info); - return chip_info.revision; -} - -const char * EspClass::getChipModel(void) -{ -#if CONFIG_IDF_TARGET_ESP32 - uint32_t chip_ver = REG_GET_FIELD(EFUSE_BLK0_RDATA3_REG, EFUSE_RD_CHIP_VER_PKG); - uint32_t pkg_ver = chip_ver & 0x7; - switch (pkg_ver) { - case EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ6 : - return "ESP32-D0WDQ6"; - case EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ5 : - return "ESP32-D0WDQ5"; - case EFUSE_RD_CHIP_VER_PKG_ESP32D2WDQ5 : - return "ESP32-D2WDQ5"; - case EFUSE_RD_CHIP_VER_PKG_ESP32PICOD2 : - return "ESP32-PICO-D2"; - case EFUSE_RD_CHIP_VER_PKG_ESP32PICOD4 : - return "ESP32-PICO-D4"; - case EFUSE_RD_CHIP_VER_PKG_ESP32PICOV302 : - return "ESP32-PICO-V3-02"; - default: - return "Unknown"; - } -#elif CONFIG_IDF_TARGET_ESP32S2 - return "ESP32-S2"; -#endif -} - -uint8_t EspClass::getChipCores(void) -{ - esp_chip_info_t chip_info; - esp_chip_info(&chip_info); - return chip_info.cores; -} - -const char * EspClass::getSdkVersion(void) -{ - return esp_get_idf_version(); -} - -uint32_t EspClass::getFlashChipSize(void) -{ - esp_image_header_t fhdr; - if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) { - return 0; - } - return magicFlashChipSize(fhdr.spi_size); -} - -uint32_t EspClass::getFlashChipSpeed(void) -{ - esp_image_header_t fhdr; - if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) { - return 0; - } - return magicFlashChipSpeed(fhdr.spi_speed); -} - -FlashMode_t EspClass::getFlashChipMode(void) -{ - esp_image_header_t fhdr; - if(flashRead(0x1000, (uint32_t*)&fhdr, sizeof(esp_image_header_t)) && fhdr.magic != ESP_IMAGE_HEADER_MAGIC) { - return FM_UNKNOWN; - } - return magicFlashChipMode(fhdr.spi_mode); -} - -uint32_t EspClass::magicFlashChipSize(uint8_t byte) -{ - switch(byte & 0x0F) { - case 0x0: // 8 MBit (1MB) - return (1_MB); - case 0x1: // 16 MBit (2MB) - return (2_MB); - case 0x2: // 32 MBit (4MB) - return (4_MB); - case 0x3: // 64 MBit (8MB) - return (8_MB); - case 0x4: // 128 MBit (16MB) - return (16_MB); - default: // fail? - return 0; - } -} - -uint32_t EspClass::magicFlashChipSpeed(uint8_t byte) -{ - switch(byte & 0x0F) { - case 0x0: // 40 MHz - return (40_MHz); - case 0x1: // 26 MHz - return (26_MHz); - case 0x2: // 20 MHz - return (20_MHz); - case 0xf: // 80 MHz - return (80_MHz); - default: // fail? - return 0; - } -} - -FlashMode_t EspClass::magicFlashChipMode(uint8_t byte) -{ - FlashMode_t mode = (FlashMode_t) byte; - if(mode > FM_SLOW_READ) { - mode = FM_UNKNOWN; - } - return mode; -} - -bool EspClass::flashEraseSector(uint32_t sector) -{ - return spi_flash_erase_sector(sector) == ESP_OK; -} - -// Warning: These functions do not work with encrypted flash -bool EspClass::flashWrite(uint32_t offset, uint32_t *data, size_t size) -{ - return spi_flash_write(offset, (uint32_t*) data, size) == ESP_OK; -} - -bool EspClass::flashRead(uint32_t offset, uint32_t *data, size_t size) -{ - return spi_flash_read(offset, (uint32_t*) data, size) == ESP_OK; -} - -bool EspClass::partitionEraseRange(const esp_partition_t *partition, uint32_t offset, size_t size) -{ - return esp_partition_erase_range(partition, offset, size) == ESP_OK; -} - -bool EspClass::partitionWrite(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size) -{ - return esp_partition_write(partition, offset, data, size) == ESP_OK; -} - -bool EspClass::partitionRead(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size) -{ - return esp_partition_read(partition, offset, data, size) == ESP_OK; -} - -uint64_t EspClass::getEfuseMac(void) -{ - uint64_t _chipmacid = 0LL; - esp_efuse_mac_get_default((uint8_t*) (&_chipmacid)); - return _chipmacid; -} diff --git a/cores/esp32/Esp.h b/cores/esp32/Esp.h deleted file mode 100644 index 34643117..00000000 --- a/cores/esp32/Esp.h +++ /dev/null @@ -1,120 +0,0 @@ -/* - Esp.h - ESP31B-specific APIs - Copyright (c) 2015 Ivan Grokhotkov. All rights reserved. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - */ - -#ifndef ESP_H -#define ESP_H - -#include -#include - -/** - * AVR macros for WDT managment - */ -typedef enum { - WDTO_0MS = 0, //!< WDTO_0MS - WDTO_15MS = 15, //!< WDTO_15MS - WDTO_30MS = 30, //!< WDTO_30MS - WDTO_60MS = 60, //!< WDTO_60MS - WDTO_120MS = 120, //!< WDTO_120MS - WDTO_250MS = 250, //!< WDTO_250MS - WDTO_500MS = 500, //!< WDTO_500MS - WDTO_1S = 1000,//!< WDTO_1S - WDTO_2S = 2000,//!< WDTO_2S - WDTO_4S = 4000,//!< WDTO_4S - WDTO_8S = 8000 //!< WDTO_8S -} WDTO_t; - - -typedef enum { - FM_QIO = 0x00, - FM_QOUT = 0x01, - FM_DIO = 0x02, - FM_DOUT = 0x03, - FM_FAST_READ = 0x04, - FM_SLOW_READ = 0x05, - FM_UNKNOWN = 0xff -} FlashMode_t; - -typedef enum { - SKETCH_SIZE_TOTAL = 0, - SKETCH_SIZE_FREE = 1 -} sketchSize_t; - -class EspClass -{ -public: - EspClass() {} - ~EspClass() {} - void restart(); - - //Internal RAM - uint32_t getHeapSize(); //total heap size - uint32_t getFreeHeap(); //available heap - uint32_t getMinFreeHeap(); //lowest level of free heap since boot - uint32_t getMaxAllocHeap(); //largest block of heap that can be allocated at once - - //SPI RAM - uint32_t getPsramSize(); - uint32_t getFreePsram(); - uint32_t getMinFreePsram(); - uint32_t getMaxAllocPsram(); - - uint8_t getChipRevision(); - const char * getChipModel(); - uint8_t getChipCores(); - uint32_t getCpuFreqMHz(){ return getCpuFrequencyMhz(); } - inline uint32_t getCycleCount() __attribute__((always_inline)); - const char * getSdkVersion(); - - void deepSleep(uint32_t time_us); - - uint32_t getFlashChipSize(); - uint32_t getFlashChipSpeed(); - FlashMode_t getFlashChipMode(); - - uint32_t magicFlashChipSize(uint8_t byte); - uint32_t magicFlashChipSpeed(uint8_t byte); - FlashMode_t magicFlashChipMode(uint8_t byte); - - uint32_t getSketchSize(); - String getSketchMD5(); - uint32_t getFreeSketchSpace(); - - bool flashEraseSector(uint32_t sector); - bool flashWrite(uint32_t offset, uint32_t *data, size_t size); - bool flashRead(uint32_t offset, uint32_t *data, size_t size); - - bool partitionEraseRange(const esp_partition_t *partition, uint32_t offset, size_t size); - bool partitionWrite(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size); - bool partitionRead(const esp_partition_t *partition, uint32_t offset, uint32_t *data, size_t size); - - uint64_t getEfuseMac(); - -}; - -uint32_t ARDUINO_ISR_ATTR EspClass::getCycleCount() -{ - uint32_t ccount; - __asm__ __volatile__("esync; rsr %0,ccount":"=a" (ccount)); - return ccount; -} - -extern EspClass ESP; - -#endif //ESP_H diff --git a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino b/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino deleted file mode 100644 index 83652495..00000000 --- a/libraries/ArduinoOTA/examples/BasicOTA/BasicOTA.ino +++ /dev/null @@ -1,68 +0,0 @@ -#include -#include -#include -#include - -const char* ssid = ".........."; -const char* password = ".........."; - -void setup() { - Serial.begin(115200); - Serial.println("Booting"); - WiFi.mode(WIFI_STA); - WiFi.begin(ssid, password); - while (WiFi.waitForConnectResult() != WL_CONNECTED) { - Serial.println("Connection Failed! Rebooting..."); - delay(5000); - ESP.restart(); - } - - // Port defaults to 3232 - // ArduinoOTA.setPort(3232); - - // Hostname defaults to esp3232-[MAC] - // ArduinoOTA.setHostname("myesp32"); - - // No authentication by default - // ArduinoOTA.setPassword("admin"); - - // Password can be set with it's md5 value as well - // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3 - // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3"); - - ArduinoOTA - .onStart([]() { - String type; - if (ArduinoOTA.getCommand() == U_FLASH) - type = "sketch"; - else // U_SPIFFS - type = "filesystem"; - - // NOTE: if updating SPIFFS this would be the place to unmount SPIFFS using SPIFFS.end() - Serial.println("Start updating " + type); - }) - .onEnd([]() { - Serial.println("\nEnd"); - }) - .onProgress([](unsigned int progress, unsigned int total) { - Serial.printf("Progress: %u%%\r", (progress / (total / 100))); - }) - .onError([](ota_error_t error) { - Serial.printf("Error[%u]: ", error); - if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); - else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); - else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); - else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); - else if (error == OTA_END_ERROR) Serial.println("End Failed"); - }); - - ArduinoOTA.begin(); - - Serial.println("Ready"); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); -} - -void loop() { - ArduinoOTA.handle(); -} \ No newline at end of file diff --git a/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino b/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino deleted file mode 100644 index 4c4adc7f..00000000 --- a/libraries/ArduinoOTA/examples/OTAWebUpdater/OTAWebUpdater.ino +++ /dev/null @@ -1,169 +0,0 @@ -#include -#include -#include -#include -#include - -const char* host = "esp32"; -const char* ssid = "xxx"; -const char* password = "xxxx"; - -WebServer server(80); - -/* - * Login page - */ - -const char* loginIndex = - "
" - "" - "" - "" - "
" - "
" - "" - "" - "" - "" - "" - "
" - "
" - "" - "" - "" - "
" - "
" - "" - "" - "" - "" - "
" - "
ESP32 Login Page
" - "
" - "
Username:
Password:
" -"
" -""; - -/* - * Server Index Page - */ - -const char* serverIndex = -"" -"
" - "" - "" - "
" - "
progress: 0%
" - ""; - -/* - * setup function - */ -void setup(void) { - Serial.begin(115200); - - // Connect to WiFi network - WiFi.begin(ssid, password); - Serial.println(""); - - // Wait for connection - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println(""); - Serial.print("Connected to "); - Serial.println(ssid); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - /*use mdns for host name resolution*/ - if (!MDNS.begin(host)) { //http://esp32.local - Serial.println("Error setting up MDNS responder!"); - while (1) { - delay(1000); - } - } - Serial.println("mDNS responder started"); - /*return index page which is stored in serverIndex */ - server.on("/", HTTP_GET, []() { - server.sendHeader("Connection", "close"); - server.send(200, "text/html", loginIndex); - }); - server.on("/serverIndex", HTTP_GET, []() { - server.sendHeader("Connection", "close"); - server.send(200, "text/html", serverIndex); - }); - /*handling uploading firmware file */ - server.on("/update", HTTP_POST, []() { - server.sendHeader("Connection", "close"); - server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK"); - ESP.restart(); - }, []() { - HTTPUpload& upload = server.upload(); - if (upload.status == UPLOAD_FILE_START) { - Serial.printf("Update: %s\n", upload.filename.c_str()); - if (!Update.begin(UPDATE_SIZE_UNKNOWN)) { //start with max available size - Update.printError(Serial); - } - } else if (upload.status == UPLOAD_FILE_WRITE) { - /* flashing firmware to ESP*/ - if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { - Update.printError(Serial); - } - } else if (upload.status == UPLOAD_FILE_END) { - if (Update.end(true)) { //true to set the size to the current progress - Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); - } else { - Update.printError(Serial); - } - } - }); - server.begin(); -} - -void loop(void) { - server.handleClient(); - delay(1); -} diff --git a/libraries/ArduinoOTA/keywords.txt b/libraries/ArduinoOTA/keywords.txt deleted file mode 100644 index 1c14d9e8..00000000 --- a/libraries/ArduinoOTA/keywords.txt +++ /dev/null @@ -1,26 +0,0 @@ -####################################### -# Syntax Coloring Map For Ultrasound -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ArduinoOTA KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -setup KEYWORD2 -handle KEYWORD2 -onStart KEYWORD2 -onEnd KEYWORD2 -onError KEYWORD2 -onProgress KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/ArduinoOTA/library.properties b/libraries/ArduinoOTA/library.properties deleted file mode 100644 index 22d78c55..00000000 --- a/libraries/ArduinoOTA/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=ArduinoOTA -version=1.0 -author=Ivan Grokhotkov and Hristo Gochkov -maintainer=Hristo Gochkov -sentence=Enables Over The Air upgrades, via wifi and espota.py UDP request/TCP download. -paragraph=With this library you can enable your sketch to be upgraded over network. Includes mdns anounces to get discovered by the arduino IDE. -category=Communication -url= -architectures=esp32 diff --git a/libraries/ArduinoOTA/src/ArduinoOTA.cpp b/libraries/ArduinoOTA/src/ArduinoOTA.cpp deleted file mode 100644 index fe85580f..00000000 --- a/libraries/ArduinoOTA/src/ArduinoOTA.cpp +++ /dev/null @@ -1,395 +0,0 @@ -#ifndef LWIP_OPEN_SRC -#define LWIP_OPEN_SRC -#endif -#include -#include -#include "ArduinoOTA.h" -#include "ESPmDNS.h" -#include "MD5Builder.h" -#include "Update.h" - - -// #define OTA_DEBUG Serial - -ArduinoOTAClass::ArduinoOTAClass() -: _port(0) -, _initialized(false) -, _rebootOnSuccess(true) -, _mdnsEnabled(true) -, _state(OTA_IDLE) -, _size(0) -, _cmd(0) -, _ota_port(0) -, _ota_timeout(1000) -, _start_callback(NULL) -, _end_callback(NULL) -, _error_callback(NULL) -, _progress_callback(NULL) -{ -} - -ArduinoOTAClass::~ArduinoOTAClass(){ - _udp_ota.stop(); -} - -ArduinoOTAClass& ArduinoOTAClass::onStart(THandlerFunction fn) { - _start_callback = fn; - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::onEnd(THandlerFunction fn) { - _end_callback = fn; - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::onProgress(THandlerFunction_Progress fn) { - _progress_callback = fn; - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::onError(THandlerFunction_Error fn) { - _error_callback = fn; - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::setPort(uint16_t port) { - if (!_initialized && !_port && port) { - _port = port; - } - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::setHostname(const char * hostname) { - if (!_initialized && !_hostname.length() && hostname) { - _hostname = hostname; - } - return *this; -} - -String ArduinoOTAClass::getHostname() { - return _hostname; -} - -ArduinoOTAClass& ArduinoOTAClass::setPassword(const char * password) { - if (!_initialized && !_password.length() && password) { - MD5Builder passmd5; - passmd5.begin(); - passmd5.add(password); - passmd5.calculate(); - _password = passmd5.toString(); - } - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::setPasswordHash(const char * password) { - if (!_initialized && !_password.length() && password) { - _password = password; - } - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::setPartitionLabel(const char * partition_label) { - if (!_initialized && !_partition_label.length() && partition_label) { - _partition_label = partition_label; - } - return *this; -} - -String ArduinoOTAClass::getPartitionLabel() { - return _partition_label; -} - -ArduinoOTAClass& ArduinoOTAClass::setRebootOnSuccess(bool reboot){ - _rebootOnSuccess = reboot; - return *this; -} - -ArduinoOTAClass& ArduinoOTAClass::setMdnsEnabled(bool enabled){ - _mdnsEnabled = enabled; - return *this; -} - -void ArduinoOTAClass::begin() { - if (_initialized){ - log_w("already initialized"); - return; - } - - if (!_port) { - _port = 3232; - } - - if(!_udp_ota.begin(_port)){ - log_e("udp bind failed"); - return; - } - - - if (!_hostname.length()) { - char tmp[20]; - uint8_t mac[6]; - WiFi.macAddress(mac); - sprintf(tmp, "esp32-%02x%02x%02x%02x%02x%02x", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - _hostname = tmp; - } - if(_mdnsEnabled){ - MDNS.begin(_hostname.c_str()); - MDNS.enableArduino(_port, (_password.length() > 0)); - } - _initialized = true; - _state = OTA_IDLE; - log_i("OTA server at: %s.local:%u", _hostname.c_str(), _port); -} - -int ArduinoOTAClass::parseInt(){ - char data[INT_BUFFER_SIZE]; - uint8_t index = 0; - char value; - while(_udp_ota.peek() == ' ') _udp_ota.read(); - while(index < INT_BUFFER_SIZE - 1){ - value = _udp_ota.peek(); - if(value < '0' || value > '9'){ - data[index++] = '\0'; - return atoi(data); - } - data[index++] = _udp_ota.read(); - } - return 0; -} - -String ArduinoOTAClass::readStringUntil(char end){ - String res = ""; - int value; - while(true){ - value = _udp_ota.read(); - if(value <= 0 || value == end){ - return res; - } - res += (char)value; - } - return res; -} - -void ArduinoOTAClass::_onRx(){ - if (_state == OTA_IDLE) { - int cmd = parseInt(); - if (cmd != U_FLASH && cmd != U_SPIFFS) - return; - _cmd = cmd; - _ota_port = parseInt(); - _size = parseInt(); - _udp_ota.read(); - _md5 = readStringUntil('\n'); - _md5.trim(); - if(_md5.length() != 32){ - log_e("bad md5 length"); - return; - } - - if (_password.length()){ - MD5Builder nonce_md5; - nonce_md5.begin(); - nonce_md5.add(String(micros())); - nonce_md5.calculate(); - _nonce = nonce_md5.toString(); - - _udp_ota.beginPacket(_udp_ota.remoteIP(), _udp_ota.remotePort()); - _udp_ota.printf("AUTH %s", _nonce.c_str()); - _udp_ota.endPacket(); - _state = OTA_WAITAUTH; - return; - } else { - _udp_ota.beginPacket(_udp_ota.remoteIP(), _udp_ota.remotePort()); - _udp_ota.print("OK"); - _udp_ota.endPacket(); - _ota_ip = _udp_ota.remoteIP(); - _state = OTA_RUNUPDATE; - } - } else if (_state == OTA_WAITAUTH) { - int cmd = parseInt(); - if (cmd != U_AUTH) { - log_e("%d was expected. got %d instead", U_AUTH, cmd); - _state = OTA_IDLE; - return; - } - _udp_ota.read(); - String cnonce = readStringUntil(' '); - String response = readStringUntil('\n'); - if (cnonce.length() != 32 || response.length() != 32) { - log_e("auth param fail"); - _state = OTA_IDLE; - return; - } - - String challenge = _password + ":" + String(_nonce) + ":" + cnonce; - MD5Builder _challengemd5; - _challengemd5.begin(); - _challengemd5.add(challenge); - _challengemd5.calculate(); - String result = _challengemd5.toString(); - - if(result.equals(response)){ - _udp_ota.beginPacket(_udp_ota.remoteIP(), _udp_ota.remotePort()); - _udp_ota.print("OK"); - _udp_ota.endPacket(); - _ota_ip = _udp_ota.remoteIP(); - _state = OTA_RUNUPDATE; - } else { - _udp_ota.beginPacket(_udp_ota.remoteIP(), _udp_ota.remotePort()); - _udp_ota.print("Authentication Failed"); - log_w("Authentication Failed"); - _udp_ota.endPacket(); - if (_error_callback) _error_callback(OTA_AUTH_ERROR); - _state = OTA_IDLE; - } - } -} - -void ArduinoOTAClass::_runUpdate() { - const char *partition_label = _partition_label.length() ? _partition_label.c_str() : NULL; - if (!Update.begin(_size, _cmd, -1, LOW, partition_label)) { - - log_e("Begin ERROR: %s", Update.errorString()); - - if (_error_callback) { - _error_callback(OTA_BEGIN_ERROR); - } - _state = OTA_IDLE; - return; - } - Update.setMD5(_md5.c_str()); - - if (_start_callback) { - _start_callback(); - } - if (_progress_callback) { - _progress_callback(0, _size); - } - - WiFiClient client; - if (!client.connect(_ota_ip, _ota_port)) { - if (_error_callback) { - _error_callback(OTA_CONNECT_ERROR); - } - _state = OTA_IDLE; - } - - uint32_t written = 0, total = 0, tried = 0; - - while (!Update.isFinished() && client.connected()) { - size_t waited = _ota_timeout; - size_t available = client.available(); - while (!available && waited){ - delay(1); - waited -=1 ; - available = client.available(); - } - if (!waited){ - if(written && tried++ < 3){ - log_i("Try[%u]: %u", tried, written); - if(!client.printf("%u", written)){ - log_e("failed to respond"); - _state = OTA_IDLE; - break; - } - continue; - } - log_e("Receive Failed"); - if (_error_callback) { - _error_callback(OTA_RECEIVE_ERROR); - } - _state = OTA_IDLE; - Update.abort(); - return; - } - if(!available){ - log_e("No Data: %u", waited); - _state = OTA_IDLE; - break; - } - tried = 0; - static uint8_t buf[1460]; - if(available > 1460){ - available = 1460; - } - size_t r = client.read(buf, available); - if(r != available){ - log_w("didn't read enough! %u != %u", r, available); - } - - written = Update.write(buf, r); - if (written > 0) { - if(written != r){ - log_w("didn't write enough! %u != %u", written, r); - } - if(!client.printf("%u", written)){ - log_w("failed to respond"); - } - total += written; - if(_progress_callback) { - _progress_callback(total, _size); - } - } else { - log_e("Write ERROR: %s", Update.errorString()); - } - } - - if (Update.end()) { - client.print("OK"); - client.stop(); - delay(10); - if (_end_callback) { - _end_callback(); - } - if(_rebootOnSuccess){ - //let serial/network finish tasks that might be given in _end_callback - delay(100); - ESP.restart(); - } - } else { - if (_error_callback) { - _error_callback(OTA_END_ERROR); - } - Update.printError(client); - client.stop(); - delay(10); - log_e("Update ERROR: %s", Update.errorString()); - _state = OTA_IDLE; - } -} - -void ArduinoOTAClass::end() { - _initialized = false; - _udp_ota.stop(); - if(_mdnsEnabled){ - MDNS.end(); - } - _state = OTA_IDLE; - log_i("OTA server stopped."); -} - -void ArduinoOTAClass::handle() { - if (!_initialized) { - return; - } - if (_state == OTA_RUNUPDATE) { - _runUpdate(); - _state = OTA_IDLE; - } - if(_udp_ota.parsePacket()){ - _onRx(); - } - _udp_ota.flush(); // always flush, even zero length packets must be flushed. -} - -int ArduinoOTAClass::getCommand() { - return _cmd; -} - -void ArduinoOTAClass::setTimeout(int timeoutInMillis) { - _ota_timeout = timeoutInMillis; -} - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_ARDUINOOTA) -ArduinoOTAClass ArduinoOTA; -#endif diff --git a/libraries/ArduinoOTA/src/ArduinoOTA.h b/libraries/ArduinoOTA/src/ArduinoOTA.h deleted file mode 100644 index cd0ba05f..00000000 --- a/libraries/ArduinoOTA/src/ArduinoOTA.h +++ /dev/null @@ -1,116 +0,0 @@ -#ifndef __ARDUINO_OTA_H -#define __ARDUINO_OTA_H - -#include -#include -#include "Update.h" - -#define INT_BUFFER_SIZE 16 - -typedef enum { - OTA_IDLE, - OTA_WAITAUTH, - OTA_RUNUPDATE -} ota_state_t; - -typedef enum { - OTA_AUTH_ERROR, - OTA_BEGIN_ERROR, - OTA_CONNECT_ERROR, - OTA_RECEIVE_ERROR, - OTA_END_ERROR -} ota_error_t; - -class ArduinoOTAClass -{ - public: - typedef std::function THandlerFunction; - typedef std::function THandlerFunction_Error; - typedef std::function THandlerFunction_Progress; - - ArduinoOTAClass(); - ~ArduinoOTAClass(); - - //Sets the service port. Default 3232 - ArduinoOTAClass& setPort(uint16_t port); - - //Sets the device hostname. Default esp32-xxxxxx - ArduinoOTAClass& setHostname(const char *hostname); - String getHostname(); - - //Sets the password that will be required for OTA. Default NULL - ArduinoOTAClass& setPassword(const char *password); - - //Sets the password as above but in the form MD5(password). Default NULL - ArduinoOTAClass& setPasswordHash(const char *password); - - //Sets the partition label to write to when updating SPIFFS. Default NULL - ArduinoOTAClass &setPartitionLabel(const char *partition_label); - String getPartitionLabel(); - - //Sets if the device should be rebooted after successful update. Default true - ArduinoOTAClass& setRebootOnSuccess(bool reboot); - - //Sets if the device should advertise itself to Arduino IDE. Default true - ArduinoOTAClass& setMdnsEnabled(bool enabled); - - //This callback will be called when OTA connection has begun - ArduinoOTAClass& onStart(THandlerFunction fn); - - //This callback will be called when OTA has finished - ArduinoOTAClass& onEnd(THandlerFunction fn); - - //This callback will be called when OTA encountered Error - ArduinoOTAClass& onError(THandlerFunction_Error fn); - - //This callback will be called when OTA is receiving data - ArduinoOTAClass& onProgress(THandlerFunction_Progress fn); - - //Starts the ArduinoOTA service - void begin(); - - //Ends the ArduinoOTA service - void end(); - - //Call this in loop() to run the service - void handle(); - - //Gets update command type after OTA has started. Either U_FLASH or U_SPIFFS - int getCommand(); - - void setTimeout(int timeoutInMillis); - - private: - int _port; - String _password; - String _hostname; - String _partition_label; - String _nonce; - WiFiUDP _udp_ota; - bool _initialized; - bool _rebootOnSuccess; - bool _mdnsEnabled; - ota_state_t _state; - int _size; - int _cmd; - int _ota_port; - int _ota_timeout; - IPAddress _ota_ip; - String _md5; - - THandlerFunction _start_callback; - THandlerFunction _end_callback; - THandlerFunction_Error _error_callback; - THandlerFunction_Progress _progress_callback; - - void _runUpdate(void); - void _onRx(void); - int parseInt(void); - String readStringUntil(char end); -}; - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_ARDUINOOTA) -extern ArduinoOTAClass ArduinoOTA; -#endif - -#endif /* __ARDUINO_OTA_H */ \ No newline at end of file diff --git a/libraries/BLE/README.md b/libraries/BLE/README.md deleted file mode 100644 index e80fbe0c..00000000 --- a/libraries/BLE/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# ESP32 BLE for Arduino -The Arduino IDE provides an excellent library package manager where versions of libraries can be downloaded and installed. This Github project provides the repository for the ESP32 BLE support for Arduino. - -The actual source of the project which is being maintained can be found here: - -https://github.com/nkolban/esp32-snippets - -Issues and questions should be raised here: - -https://github.com/nkolban/esp32-snippets/issues - - -Documentation for using the library can be found here: - -https://github.com/nkolban/esp32-snippets/tree/master/Documentation \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_Beacon_Scanner/.skip.esp32s2 b/libraries/BLE/examples/BLE_Beacon_Scanner/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.ino b/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.ino deleted file mode 100644 index b46baa7c..00000000 --- a/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.ino +++ /dev/null @@ -1,153 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp - Ported to Arduino ESP32 by Evandro Copercini - Changed to a beacon scanner to report iBeacon, EddystoneURL and EddystoneTLM beacons by beegee-tokyo -*/ - -#include - -#include -#include -#include -#include -#include -#include -#include - -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00) >> 8) + (((x)&0xFF) << 8)) - -int scanTime = 5; //In seconds -BLEScan *pBLEScan; - -class MyAdvertisedDeviceCallbacks : public BLEAdvertisedDeviceCallbacks -{ - void onResult(BLEAdvertisedDevice advertisedDevice) - { - if (advertisedDevice.haveName()) - { - Serial.print("Device name: "); - Serial.println(advertisedDevice.getName().c_str()); - Serial.println(""); - } - - if (advertisedDevice.haveServiceUUID()) - { - BLEUUID devUUID = advertisedDevice.getServiceUUID(); - Serial.print("Found ServiceUUID: "); - Serial.println(devUUID.toString().c_str()); - Serial.println(""); - } - else - { - if (advertisedDevice.haveManufacturerData() == true) - { - std::string strManufacturerData = advertisedDevice.getManufacturerData(); - - uint8_t cManufacturerData[100]; - strManufacturerData.copy((char *)cManufacturerData, strManufacturerData.length(), 0); - - if (strManufacturerData.length() == 25 && cManufacturerData[0] == 0x4C && cManufacturerData[1] == 0x00) - { - Serial.println("Found an iBeacon!"); - BLEBeacon oBeacon = BLEBeacon(); - oBeacon.setData(strManufacturerData); - Serial.printf("iBeacon Frame\n"); - Serial.printf("ID: %04X Major: %d Minor: %d UUID: %s Power: %d\n", oBeacon.getManufacturerId(), ENDIAN_CHANGE_U16(oBeacon.getMajor()), ENDIAN_CHANGE_U16(oBeacon.getMinor()), oBeacon.getProximityUUID().toString().c_str(), oBeacon.getSignalPower()); - } - else - { - Serial.println("Found another manufacturers beacon!"); - Serial.printf("strManufacturerData: %d ", strManufacturerData.length()); - for (int i = 0; i < strManufacturerData.length(); i++) - { - Serial.printf("[%X]", cManufacturerData[i]); - } - Serial.printf("\n"); - } - } - return; - } - - uint8_t *payLoad = advertisedDevice.getPayload(); - - BLEUUID checkUrlUUID = (uint16_t)0xfeaa; - - if (advertisedDevice.getServiceUUID().equals(checkUrlUUID)) - { - if (payLoad[11] == 0x10) - { - Serial.println("Found an EddystoneURL beacon!"); - BLEEddystoneURL foundEddyURL = BLEEddystoneURL(); - std::string eddyContent((char *)&payLoad[11]); // incomplete EddystoneURL struct! - - foundEddyURL.setData(eddyContent); - std::string bareURL = foundEddyURL.getURL(); - if (bareURL[0] == 0x00) - { - size_t payLoadLen = advertisedDevice.getPayloadLength(); - Serial.println("DATA-->"); - for (int idx = 0; idx < payLoadLen; idx++) - { - Serial.printf("0x%08X ", payLoad[idx]); - } - Serial.println("\nInvalid Data"); - return; - } - - Serial.printf("Found URL: %s\n", foundEddyURL.getURL().c_str()); - Serial.printf("Decoded URL: %s\n", foundEddyURL.getDecodedURL().c_str()); - Serial.printf("TX power %d\n", foundEddyURL.getPower()); - Serial.println("\n"); - } - else if (payLoad[11] == 0x20) - { - Serial.println("Found an EddystoneTLM beacon!"); - BLEEddystoneTLM foundEddyURL = BLEEddystoneTLM(); - std::string eddyContent((char *)&payLoad[11]); // incomplete EddystoneURL struct! - - eddyContent = "01234567890123"; - - for (int idx = 0; idx < 14; idx++) - { - eddyContent[idx] = payLoad[idx + 11]; - } - - foundEddyURL.setData(eddyContent); - Serial.printf("Reported battery voltage: %dmV\n", foundEddyURL.getVolt()); - Serial.printf("Reported temperature from TLM class: %.2fC\n", (double)foundEddyURL.getTemp()); - int temp = (int)payLoad[16] + (int)(payLoad[15] << 8); - float calcTemp = temp / 256.0f; - Serial.printf("Reported temperature from data: %.2fC\n", calcTemp); - Serial.printf("Reported advertise count: %d\n", foundEddyURL.getCount()); - Serial.printf("Reported time since last reboot: %ds\n", foundEddyURL.getTime()); - Serial.println("\n"); - Serial.print(foundEddyURL.toString().c_str()); - Serial.println("\n"); - } - } - } -}; - -void setup() -{ - Serial.begin(115200); - Serial.println("Scanning..."); - - BLEDevice::init(""); - pBLEScan = BLEDevice::getScan(); //create new scan - pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); - pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster - pBLEScan->setInterval(100); - pBLEScan->setWindow(99); // less or equal setInterval value -} - -void loop() -{ - // put your main code here, to run repeatedly: - BLEScanResults foundDevices = pBLEScan->start(scanTime, false); - Serial.print("Devices found: "); - Serial.println(foundDevices.getCount()); - Serial.println("Scan done!"); - pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory - delay(2000); -} diff --git a/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.md b/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.md deleted file mode 100644 index 558c3e7a..00000000 --- a/libraries/BLE/examples/BLE_Beacon_Scanner/BLE_Beacon_Scanner.md +++ /dev/null @@ -1,9 +0,0 @@ -## BLE Beacon Scanner - -Initiates a BLE device scan. -Checks if the discovered devices are -- an iBeacon -- an Eddystone TLM beacon -- an Eddystone URL beacon - -and sends the decoded beacon information over Serial log \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/.skip.esp32s2 b/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.ino b/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.ino deleted file mode 100644 index 96be28cd..00000000 --- a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.ino +++ /dev/null @@ -1,116 +0,0 @@ -/* - EddystoneTLM beacon by BeeGee based on https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_Eddystone_TLM_deepsleep/ESP32_Eddystone_TLM_deepsleep.ino - EddystoneTLM frame specification https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md -*/ - -/* - Create a BLE server that will send periodic Eddystone URL frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep - -*/ -#include "sys/time.h" - -#include - -#include "BLEDevice.h" -#include "BLEUtils.h" -#include "BLEBeacon.h" -#include "BLEAdvertising.h" -#include "BLEEddystoneURL.h" - -#include "esp_sleep.h" - -#define GPIO_DEEP_SLEEP_DURATION 10 // sleep x seconds and then wake up -RTC_DATA_ATTR static time_t last; // remember last boot in RTC Memory -RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ -BLEAdvertising *pAdvertising; -struct timeval nowTimeStruct; - -time_t lastTenth; - -#define BEACON_UUID "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/) - -// Check -// https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md -// and http://www.hugi.scene.org/online/coding/hugi%2015%20-%20cmtadfix.htm -// for the temperature value. It is a 8.8 fixed-point notation -void setBeacon() -{ - char beacon_data[25]; - uint16_t beconUUID = 0xFEAA; - uint16_t volt = random(2800, 3700); // 3300mV = 3.3V - float tempFloat = random(2000, 3100) / 100.0f; - Serial.printf("Random temperature is %.2fC\n", tempFloat); - int temp = (int)(tempFloat * 256); //(uint16_t)((float)23.00); - Serial.printf("Converted to 8.8 format %0X%0X\n", (temp >> 8), (temp & 0xFF)); - - BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); - BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); - - oScanResponseData.setFlags(0x06); // GENERAL_DISC_MODE 0x02 | BR_EDR_NOT_SUPPORTED 0x04 - oScanResponseData.setCompleteServices(BLEUUID(beconUUID)); - - beacon_data[0] = 0x20; // Eddystone Frame Type (Unencrypted Eddystone-TLM) - beacon_data[1] = 0x00; // TLM version - beacon_data[2] = (volt >> 8); // Battery voltage, 1 mV/bit i.e. 0xCE4 = 3300mV = 3.3V - beacon_data[3] = (volt & 0xFF); // - beacon_data[4] = (temp >> 8); // Beacon temperature - beacon_data[5] = (temp & 0xFF); // - beacon_data[6] = ((bootcount & 0xFF000000) >> 24); // Advertising PDU count - beacon_data[7] = ((bootcount & 0xFF0000) >> 16); // - beacon_data[8] = ((bootcount & 0xFF00) >> 8); // - beacon_data[9] = (bootcount & 0xFF); // - beacon_data[10] = ((lastTenth & 0xFF000000) >> 24); // Time since power-on or reboot as 0.1 second resolution counter - beacon_data[11] = ((lastTenth & 0xFF0000) >> 16); // - beacon_data[12] = ((lastTenth & 0xFF00) >> 8); // - beacon_data[13] = (lastTenth & 0xFF); // - - oScanResponseData.setServiceData(BLEUUID(beconUUID), std::string(beacon_data, 14)); - oAdvertisementData.setName("TLMBeacon"); - pAdvertising->setAdvertisementData(oAdvertisementData); - pAdvertising->setScanResponseData(oScanResponseData); -} - -void setup() -{ - - Serial.begin(115200); - gettimeofday(&nowTimeStruct, NULL); - - Serial.printf("start ESP32 %d\n", bootcount++); - - Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n", nowTimeStruct.tv_sec, nowTimeStruct.tv_sec - last); - - last = nowTimeStruct.tv_sec; - lastTenth = nowTimeStruct.tv_sec * 10; // Time since last reset as 0.1 second resolution counter - - // Create the BLE Device - BLEDevice::init("TLMBeacon"); - - BLEDevice::setPower(ESP_PWR_LVL_N12); - - pAdvertising = BLEDevice::getAdvertising(); - - setBeacon(); - // Start advertising - pAdvertising->start(); - Serial.println("Advertizing started for 10s ..."); - delay(10000); - pAdvertising->stop(); - Serial.printf("enter deep sleep for 10s\n"); - esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION); - Serial.printf("in deep sleep\n"); -} - -void loop() -{ -} diff --git a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.md b/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.md deleted file mode 100644 index 2e34029d..00000000 --- a/libraries/BLE/examples/BLE_EddystoneTLM_Beacon/BLE_EddystoneTLM_Beacon.md +++ /dev/null @@ -1,14 +0,0 @@ -## Eddystone TLM beacon -EddystoneTLM beacon by BeeGee based on -[pcbreflux ESP32 Eddystone TLM deepsleep](https://github.com/pcbreflux/espressif/blob/master/esp32/arduino/sketchbook/ESP32_Eddystone_TLM_deepsleep/ESP32_Eddystone_TLM_deepsleep.ino) - -[EddystoneTLM frame specification](https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md) - - Create a BLE server that will send periodic Eddystone TLM frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep diff --git a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/.skip.esp32s2 b/libraries/BLE/examples/BLE_EddystoneURL_Beacon/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.ino b/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.ino deleted file mode 100644 index 335ea1ff..00000000 --- a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.ino +++ /dev/null @@ -1,192 +0,0 @@ -/* - EddystoneURL beacon by BeeGee - EddystoneURL frame specification https://github.com/google/eddystone/blob/master/eddystone-url/README.md - -*/ - -/* - Create a BLE server that will send periodic Eddystone URL frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep - -*/ -#include "sys/time.h" - -#include - -#include "BLEDevice.h" -#include "BLEUtils.h" -#include "BLEBeacon.h" -#include "BLEAdvertising.h" -#include "BLEEddystoneURL.h" - -#include "esp_sleep.h" - -#define GPIO_DEEP_SLEEP_DURATION 10 // sleep x seconds and then wake up -RTC_DATA_ATTR static time_t last; // remember last boot in RTC Memory -RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ -BLEAdvertising *pAdvertising; -struct timeval now; - -#define BEACON_UUID "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/) - -static const char *eddystone_url_prefix_subs[] = { - "http://www.", - "https://www.", - "http://", - "https://", - "urn:uuid:", - NULL -}; - -static const char *eddystone_url_suffix_subs[] = { - ".com/", - ".org/", - ".edu/", - ".net/", - ".info/", - ".biz/", - ".gov/", - ".com", - ".org", - ".edu", - ".net", - ".info", - ".biz", - ".gov", - NULL -}; - -static int string_begin_with(const char *str, const char *prefix) -{ - int prefix_len = strlen(prefix); - if (strncmp(prefix, str, prefix_len) == 0) - { - return prefix_len; - } - return 0; -} - -void setBeacon() -{ - BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); - BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); - - const char url[] = "https://d.giesecke.tk"; - - int scheme_len, ext_len = 1, i, idx, url_idx; - char *ret_data; - int url_len = strlen(url); - - ret_data = (char *)calloc(1, url_len + 13); - - ret_data[0] = 2; // Len - ret_data[1] = 0x01; // Type Flags - ret_data[2] = 0x06; // GENERAL_DISC_MODE 0x02 | BR_EDR_NOT_SUPPORTED 0x04 - ret_data[3] = 3; // Len - ret_data[4] = 0x03; // Type 16-Bit UUID - ret_data[5] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB - ret_data[6] = 0xFE; // Eddystone UUID 1 MSB - ret_data[7] = 19; // Length of Beacon Data - ret_data[8] = 0x16; // Type Service Data - ret_data[9] = 0xAA; // Eddystone UUID 2 -> 0xFEAA LSB - ret_data[10] = 0xFE; // Eddystone UUID 1 MSB - ret_data[11] = 0x10; // Eddystone Frame Type - ret_data[12] = 0xF4; // Beacons TX power at 0m - - i = 0, idx = 13, url_idx = 0; - - //replace prefix - scheme_len = 0; - while (eddystone_url_prefix_subs[i] != NULL) - { - if ((scheme_len = string_begin_with(url, eddystone_url_prefix_subs[i])) > 0) - { - ret_data[idx] = i; - idx++; - url_idx += scheme_len; - break; - } - i++; - } - while (url_idx < url_len) - { - i = 0; - ret_data[idx] = url[url_idx]; - ext_len = 1; - while (eddystone_url_suffix_subs[i] != NULL) - { - if ((ext_len = string_begin_with(&url[url_idx], eddystone_url_suffix_subs[i])) > 0) - { - ret_data[idx] = i; - break; - } - else - { - ext_len = 1; //inc 1 - } - i++; - } - url_idx += ext_len; - idx++; - } - ret_data[7] = idx - 8; - - Serial.printf("struct size %d url size %d reported len %d\n", - url_len + 13, - url_len, ret_data[7]); - - Serial.printf("URL in data %s\n", &ret_data[13]); - - std::string eddyStoneData(ret_data); - - oAdvertisementData.addData(eddyStoneData); - oScanResponseData.setName("URLBeacon"); - pAdvertising->setAdvertisementData(oAdvertisementData); - pAdvertising->setScanResponseData(oScanResponseData); -} - -void setup() -{ - - Serial.begin(115200); - gettimeofday(&now, NULL); - - Serial.printf("start ESP32 %d\n", bootcount++); - - Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n", now.tv_sec, now.tv_sec - last); - - last = now.tv_sec; - - // Create the BLE Device - BLEDevice::init("URLBeacon"); - - BLEDevice::setPower(ESP_PWR_LVL_N12); - - // Create the BLE Server - // BLEServer *pServer = BLEDevice::createServer(); // <-- no longer required to instantiate BLEServer, less flash and ram usage - - pAdvertising = BLEDevice::getAdvertising(); - - setBeacon(); - // Start advertising - pAdvertising->start(); - Serial.println("Advertizing started..."); - delay(10000); - pAdvertising->stop(); - Serial.printf("enter deep sleep\n"); - esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION); - Serial.printf("in deep sleep\n"); -} - -void loop() -{ -} diff --git a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.md b/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.md deleted file mode 100644 index 2baf1cc5..00000000 --- a/libraries/BLE/examples/BLE_EddystoneURL_Beacon/BLE_EddystoneURL_Beacon.md +++ /dev/null @@ -1,14 +0,0 @@ -## Eddystone URL beacon -EddystoneURL beacon by BeeGee based on -[pcbreflux ESP32 Eddystone URL deepsleep](https://github.com/pcbreflux/espressif/tree/master/esp32/arduino/sketchbook/ESP32_Eddystone_URL_deepsleep) - -[EddystoneURL frame specification](https://github.com/google/eddystone/blob/master/eddystone-url/README.md) - - Create a BLE server that will send periodic Eddystone URL frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep diff --git a/libraries/BLE/examples/BLE_client/.skip.esp32s2 b/libraries/BLE/examples/BLE_client/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_client/BLE_client.ino b/libraries/BLE/examples/BLE_client/BLE_client.ino deleted file mode 100644 index 55d9fa0d..00000000 --- a/libraries/BLE/examples/BLE_client/BLE_client.ino +++ /dev/null @@ -1,161 +0,0 @@ -/** - * 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 boolean doConnect = false; -static boolean connected = false; -static boolean doScan = false; -static BLERemoteCharacteristic* pRemoteCharacteristic; -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.println((char*)pData); -} - -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"); - - // 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. - pRemoteCharacteristic = pRemoteService->getCharacteristic(charUUID); - if (pRemoteCharacteristic == nullptr) { - Serial.print("Failed to find our characteristic UUID: "); - Serial.println(charUUID.toString().c_str()); - pClient->disconnect(); - return false; - } - Serial.println(" - Found our characteristic"); - - // Read the value of the characteristic. - if(pRemoteCharacteristic->canRead()) { - std::string value = pRemoteCharacteristic->readValue(); - Serial.print("The characteristic value was: "); - Serial.println(value.c_str()); - } - - if(pRemoteCharacteristic->canNotify()) - pRemoteCharacteristic->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 - - -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 = "Time since boot: " + String(millis()/1000); - Serial.println("Setting new characteristic value to \"" + newValue + "\""); - - // Set the characteristic's value to be the array of bytes that is actually a string. - pRemoteCharacteristic->writeValue(newValue.c_str(), newValue.length()); - }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(1000); // Delay a second between loops. -} // End of loop diff --git a/libraries/BLE/examples/BLE_iBeacon/.skip.esp32s2 b/libraries/BLE/examples/BLE_iBeacon/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino b/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino deleted file mode 100644 index 324e821e..00000000 --- a/libraries/BLE/examples/BLE_iBeacon/BLE_iBeacon.ino +++ /dev/null @@ -1,104 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp - Ported to Arduino ESP32 by pcbreflux -*/ - - -/* - Create a BLE server that will send periodic iBeacon frames. - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create advertising data - 3. Start advertising. - 4. wait - 5. Stop advertising. - 6. deep sleep - -*/ -#include "sys/time.h" - -#include "BLEDevice.h" -#include "BLEUtils.h" -#include "BLEBeacon.h" -#include "esp_sleep.h" - -#define GPIO_DEEP_SLEEP_DURATION 10 // sleep x seconds and then wake up -RTC_DATA_ATTR static time_t last; // remember last boot in RTC Memory -RTC_DATA_ATTR static uint32_t bootcount; // remember number of boots in RTC Memory - -#ifdef __cplusplus -extern "C" { -#endif - -uint8_t temprature_sens_read(); -//uint8_t g_phyFuns; - -#ifdef __cplusplus -} -#endif - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ -BLEAdvertising *pAdvertising; -struct timeval now; - -#define BEACON_UUID "8ec76ea3-6668-48da-9866-75be8bc86f4d" // UUID 1 128-Bit (may use linux tool uuidgen or random numbers via https://www.uuidgenerator.net/) - -void setBeacon() { - - BLEBeacon oBeacon = BLEBeacon(); - oBeacon.setManufacturerId(0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!) - oBeacon.setProximityUUID(BLEUUID(BEACON_UUID)); - oBeacon.setMajor((bootcount & 0xFFFF0000) >> 16); - oBeacon.setMinor(bootcount&0xFFFF); - BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); - BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); - - oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04 - - std::string strServiceData = ""; - - strServiceData += (char)26; // Len - strServiceData += (char)0xFF; // Type - strServiceData += oBeacon.getData(); - oAdvertisementData.addData(strServiceData); - - pAdvertising->setAdvertisementData(oAdvertisementData); - pAdvertising->setScanResponseData(oScanResponseData); - pAdvertising->setAdvertisementType(ADV_TYPE_NONCONN_IND); - -} - -void setup() { - - - Serial.begin(115200); - gettimeofday(&now, NULL); - - Serial.printf("start ESP32 %d\n",bootcount++); - - Serial.printf("deep sleep (%lds since last reset, %lds since last boot)\n",now.tv_sec,now.tv_sec-last); - - last = now.tv_sec; - - // Create the BLE Device - BLEDevice::init(""); - - // Create the BLE Server - // BLEServer *pServer = BLEDevice::createServer(); // <-- no longer required to instantiate BLEServer, less flash and ram usage - - pAdvertising = BLEDevice::getAdvertising(); - - setBeacon(); - // Start advertising - pAdvertising->start(); - Serial.println("Advertizing started..."); - delay(100); - pAdvertising->stop(); - Serial.printf("enter deep sleep\n"); - esp_deep_sleep(1000000LL * GPIO_DEEP_SLEEP_DURATION); - Serial.printf("in deep sleep\n"); -} - -void loop() { -} diff --git a/libraries/BLE/examples/BLE_notify/.skip.esp32s2 b/libraries/BLE/examples/BLE_notify/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_notify/BLE_notify.ino b/libraries/BLE/examples/BLE_notify/BLE_notify.ino deleted file mode 100644 index 42b9e727..00000000 --- a/libraries/BLE/examples/BLE_notify/BLE_notify.ino +++ /dev/null @@ -1,110 +0,0 @@ -/* - Video: https://www.youtube.com/watch?v=oCMOYS71NIU - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp - Ported to Arduino ESP32 by Evandro Copercini - updated by chegewara - - Create a BLE server that, once we receive a connection, will send periodic notifications. - The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b - And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 - - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create a BLE Service - 3. Create a BLE Characteristic on the Service - 4. Create a BLE Descriptor on the characteristic - 5. Start the service. - 6. Start advertising. - - A connect hander associated with the server starts a background task that performs notification - every couple of seconds. -*/ -#include -#include -#include -#include - -BLEServer* pServer = NULL; -BLECharacteristic* pCharacteristic = NULL; -bool deviceConnected = false; -bool oldDeviceConnected = false; -uint32_t value = 0; - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - - -class MyServerCallbacks: public BLEServerCallbacks { - void onConnect(BLEServer* pServer) { - deviceConnected = true; - }; - - void onDisconnect(BLEServer* pServer) { - deviceConnected = false; - } -}; - - - -void setup() { - Serial.begin(115200); - - // Create the BLE Device - BLEDevice::init("ESP32"); - - // Create the BLE Server - pServer = BLEDevice::createServer(); - pServer->setCallbacks(new MyServerCallbacks()); - - // Create the BLE Service - BLEService *pService = pServer->createService(SERVICE_UUID); - - // Create a BLE Characteristic - pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE | - BLECharacteristic::PROPERTY_NOTIFY | - BLECharacteristic::PROPERTY_INDICATE - ); - - // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - // Create a BLE Descriptor - pCharacteristic->addDescriptor(new BLE2902()); - - // Start the service - pService->start(); - - // Start advertising - BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); - pAdvertising->addServiceUUID(SERVICE_UUID); - pAdvertising->setScanResponse(false); - pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter - BLEDevice::startAdvertising(); - Serial.println("Waiting a client connection to notify..."); -} - -void loop() { - // notify changed value - if (deviceConnected) { - pCharacteristic->setValue((uint8_t*)&value, 4); - pCharacteristic->notify(); - value++; - delay(3); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms - } - // disconnecting - if (!deviceConnected && oldDeviceConnected) { - delay(500); // give the bluetooth stack the chance to get things ready - pServer->startAdvertising(); // restart advertising - Serial.println("start advertising"); - oldDeviceConnected = deviceConnected; - } - // connecting - if (deviceConnected && !oldDeviceConnected) { - // do stuff here on connecting - oldDeviceConnected = deviceConnected; - } -} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_scan/.skip.esp32s2 b/libraries/BLE/examples/BLE_scan/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_scan/BLE_scan.ino b/libraries/BLE/examples/BLE_scan/BLE_scan.ino deleted file mode 100644 index 094f7933..00000000 --- a/libraries/BLE/examples/BLE_scan/BLE_scan.ino +++ /dev/null @@ -1,40 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleScan.cpp - Ported to Arduino ESP32 by Evandro Copercini -*/ - -#include -#include -#include -#include - -int scanTime = 5; //In seconds -BLEScan* pBLEScan; - -class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks { - void onResult(BLEAdvertisedDevice advertisedDevice) { - Serial.printf("Advertised Device: %s \n", advertisedDevice.toString().c_str()); - } -}; - -void setup() { - Serial.begin(115200); - Serial.println("Scanning..."); - - BLEDevice::init(""); - pBLEScan = BLEDevice::getScan(); //create new scan - pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks()); - pBLEScan->setActiveScan(true); //active scan uses more power, but get results faster - pBLEScan->setInterval(100); - pBLEScan->setWindow(99); // less or equal setInterval value -} - -void loop() { - // put your main code here, to run repeatedly: - BLEScanResults foundDevices = pBLEScan->start(scanTime, false); - Serial.print("Devices found: "); - Serial.println(foundDevices.getCount()); - Serial.println("Scan done!"); - pBLEScan->clearResults(); // delete results fromBLEScan buffer to release memory - delay(2000); -} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_server/.skip.esp32s2 b/libraries/BLE/examples/BLE_server/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_server/BLE_server.ino b/libraries/BLE/examples/BLE_server/BLE_server.ino deleted file mode 100644 index 3f9176ac..00000000 --- a/libraries/BLE/examples/BLE_server/BLE_server.ino +++ /dev/null @@ -1,45 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleServer.cpp - Ported to Arduino ESP32 by Evandro Copercini - updates by chegewara -*/ - -#include -#include -#include - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - -void setup() { - Serial.begin(115200); - Serial.println("Starting BLE work!"); - - BLEDevice::init("Long name works now"); - BLEServer *pServer = BLEDevice::createServer(); - BLEService *pService = pServer->createService(SERVICE_UUID); - BLECharacteristic *pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE - ); - - pCharacteristic->setValue("Hello World says Neil"); - pService->start(); - // BLEAdvertising *pAdvertising = pServer->getAdvertising(); // this still is working for backward compatibility - 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(); - Serial.println("Characteristic defined! Now you can read it in your phone!"); -} - -void loop() { - // put your main code here, to run repeatedly: - delay(2000); -} \ No newline at end of file diff --git a/libraries/BLE/examples/BLE_server_multiconnect/.skip.esp32s2 b/libraries/BLE/examples/BLE_server_multiconnect/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino b/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino deleted file mode 100644 index 90704ef1..00000000 --- a/libraries/BLE/examples/BLE_server_multiconnect/BLE_server_multiconnect.ino +++ /dev/null @@ -1,111 +0,0 @@ -/* - Video: https://www.youtube.com/watch?v=oCMOYS71NIU - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp - Ported to Arduino ESP32 by Evandro Copercini - updated by chegewara - - Create a BLE server that, once we receive a connection, will send periodic notifications. - The service advertises itself as: 4fafc201-1fb5-459e-8fcc-c5c9c331914b - And has a characteristic of: beb5483e-36e1-4688-b7f5-ea07361b26a8 - - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create a BLE Service - 3. Create a BLE Characteristic on the Service - 4. Create a BLE Descriptor on the characteristic - 5. Start the service. - 6. Start advertising. - - A connect hander associated with the server starts a background task that performs notification - every couple of seconds. -*/ -#include -#include -#include -#include - -BLEServer* pServer = NULL; -BLECharacteristic* pCharacteristic = NULL; -bool deviceConnected = false; -bool oldDeviceConnected = false; -uint32_t value = 0; - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - - -class MyServerCallbacks: public BLEServerCallbacks { - void onConnect(BLEServer* pServer) { - deviceConnected = true; - BLEDevice::startAdvertising(); - }; - - void onDisconnect(BLEServer* pServer) { - deviceConnected = false; - } -}; - - - -void setup() { - Serial.begin(115200); - - // Create the BLE Device - BLEDevice::init("ESP32"); - - // Create the BLE Server - pServer = BLEDevice::createServer(); - pServer->setCallbacks(new MyServerCallbacks()); - - // Create the BLE Service - BLEService *pService = pServer->createService(SERVICE_UUID); - - // Create a BLE Characteristic - pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE | - BLECharacteristic::PROPERTY_NOTIFY | - BLECharacteristic::PROPERTY_INDICATE - ); - - // https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - // Create a BLE Descriptor - pCharacteristic->addDescriptor(new BLE2902()); - - // Start the service - pService->start(); - - // Start advertising - BLEAdvertising *pAdvertising = BLEDevice::getAdvertising(); - pAdvertising->addServiceUUID(SERVICE_UUID); - pAdvertising->setScanResponse(false); - pAdvertising->setMinPreferred(0x0); // set value to 0x00 to not advertise this parameter - BLEDevice::startAdvertising(); - Serial.println("Waiting a client connection to notify..."); -} - -void loop() { - // notify changed value - if (deviceConnected) { - pCharacteristic->setValue((uint8_t*)&value, 4); - pCharacteristic->notify(); - value++; - delay(10); // bluetooth stack will go into congestion, if too many packets are sent, in 6 hours test i was able to go as low as 3ms - } - // disconnecting - if (!deviceConnected && oldDeviceConnected) { - delay(500); // give the bluetooth stack the chance to get things ready - pServer->startAdvertising(); // restart advertising - Serial.println("start advertising"); - oldDeviceConnected = deviceConnected; - } - // connecting - if (deviceConnected && !oldDeviceConnected) { - // do stuff here on connecting - oldDeviceConnected = deviceConnected; - } -} diff --git a/libraries/BLE/examples/BLE_uart/.skip.esp32s2 b/libraries/BLE/examples/BLE_uart/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_uart/BLE_uart.ino b/libraries/BLE/examples/BLE_uart/BLE_uart.ino deleted file mode 100644 index 35b570b9..00000000 --- a/libraries/BLE/examples/BLE_uart/BLE_uart.ino +++ /dev/null @@ -1,125 +0,0 @@ -/* - Video: https://www.youtube.com/watch?v=oCMOYS71NIU - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleNotify.cpp - Ported to Arduino ESP32 by Evandro Copercini - - Create a BLE server that, once we receive a connection, will send periodic notifications. - The service advertises itself as: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E - Has a characteristic of: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E - used for receiving data with "WRITE" - Has a characteristic of: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E - used to send data with "NOTIFY" - - The design of creating the BLE server is: - 1. Create a BLE Server - 2. Create a BLE Service - 3. Create a BLE Characteristic on the Service - 4. Create a BLE Descriptor on the characteristic - 5. Start the service. - 6. Start advertising. - - In this example rxValue is the data received (only accessible inside that function). - And txValue is the data to be sent, in this example just a byte incremented every second. -*/ -#include -#include -#include -#include - -BLEServer *pServer = NULL; -BLECharacteristic * pTxCharacteristic; -bool deviceConnected = false; -bool oldDeviceConnected = false; -uint8_t txValue = 0; - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "6E400001-B5A3-F393-E0A9-E50E24DCCA9E" // UART service UUID -#define CHARACTERISTIC_UUID_RX "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" -#define CHARACTERISTIC_UUID_TX "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" - - -class MyServerCallbacks: public BLEServerCallbacks { - void onConnect(BLEServer* pServer) { - deviceConnected = true; - }; - - void onDisconnect(BLEServer* pServer) { - deviceConnected = false; - } -}; - -class MyCallbacks: public BLECharacteristicCallbacks { - void onWrite(BLECharacteristic *pCharacteristic) { - std::string rxValue = pCharacteristic->getValue(); - - if (rxValue.length() > 0) { - Serial.println("*********"); - Serial.print("Received Value: "); - for (int i = 0; i < rxValue.length(); i++) - Serial.print(rxValue[i]); - - Serial.println(); - Serial.println("*********"); - } - } -}; - - -void setup() { - Serial.begin(115200); - - // Create the BLE Device - BLEDevice::init("UART Service"); - - // Create the BLE Server - pServer = BLEDevice::createServer(); - pServer->setCallbacks(new MyServerCallbacks()); - - // Create the BLE Service - BLEService *pService = pServer->createService(SERVICE_UUID); - - // Create a BLE Characteristic - pTxCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID_TX, - BLECharacteristic::PROPERTY_NOTIFY - ); - - pTxCharacteristic->addDescriptor(new BLE2902()); - - BLECharacteristic * pRxCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID_RX, - BLECharacteristic::PROPERTY_WRITE - ); - - pRxCharacteristic->setCallbacks(new MyCallbacks()); - - // Start the service - pService->start(); - - // Start advertising - pServer->getAdvertising()->start(); - Serial.println("Waiting a client connection to notify..."); -} - -void loop() { - - if (deviceConnected) { - pTxCharacteristic->setValue(&txValue, 1); - pTxCharacteristic->notify(); - txValue++; - delay(10); // bluetooth stack will go into congestion, if too many packets are sent - } - - // disconnecting - if (!deviceConnected && oldDeviceConnected) { - delay(500); // give the bluetooth stack the chance to get things ready - pServer->startAdvertising(); // restart advertising - Serial.println("start advertising"); - oldDeviceConnected = deviceConnected; - } - // connecting - if (deviceConnected && !oldDeviceConnected) { - // do stuff here on connecting - oldDeviceConnected = deviceConnected; - } -} diff --git a/libraries/BLE/examples/BLE_write/.skip.esp32s2 b/libraries/BLE/examples/BLE_write/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BLE/examples/BLE_write/BLE_write.ino b/libraries/BLE/examples/BLE_write/BLE_write.ino deleted file mode 100644 index 24a0cd23..00000000 --- a/libraries/BLE/examples/BLE_write/BLE_write.ino +++ /dev/null @@ -1,65 +0,0 @@ -/* - Based on Neil Kolban example for IDF: https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLE%20Tests/SampleWrite.cpp - Ported to Arduino ESP32 by Evandro Copercini -*/ - -#include -#include -#include - -// See the following for generating UUIDs: -// https://www.uuidgenerator.net/ - -#define SERVICE_UUID "4fafc201-1fb5-459e-8fcc-c5c9c331914b" -#define CHARACTERISTIC_UUID "beb5483e-36e1-4688-b7f5-ea07361b26a8" - - -class MyCallbacks: public BLECharacteristicCallbacks { - void onWrite(BLECharacteristic *pCharacteristic) { - std::string value = pCharacteristic->getValue(); - - if (value.length() > 0) { - Serial.println("*********"); - Serial.print("New value: "); - for (int i = 0; i < value.length(); i++) - Serial.print(value[i]); - - Serial.println(); - Serial.println("*********"); - } - } -}; - -void setup() { - Serial.begin(115200); - - Serial.println("1- Download and install an BLE scanner app in your phone"); - Serial.println("2- Scan for BLE devices in the app"); - Serial.println("3- Connect to MyESP32"); - Serial.println("4- Go to CUSTOM CHARACTERISTIC in CUSTOM SERVICE and write something"); - Serial.println("5- See the magic =)"); - - BLEDevice::init("MyESP32"); - BLEServer *pServer = BLEDevice::createServer(); - - BLEService *pService = pServer->createService(SERVICE_UUID); - - BLECharacteristic *pCharacteristic = pService->createCharacteristic( - CHARACTERISTIC_UUID, - BLECharacteristic::PROPERTY_READ | - BLECharacteristic::PROPERTY_WRITE - ); - - pCharacteristic->setCallbacks(new MyCallbacks()); - - pCharacteristic->setValue("Hello World"); - pService->start(); - - BLEAdvertising *pAdvertising = pServer->getAdvertising(); - pAdvertising->start(); -} - -void loop() { - // put your main code here, to run repeatedly: - delay(2000); -} \ No newline at end of file diff --git a/libraries/BLE/library.properties b/libraries/BLE/library.properties deleted file mode 100644 index 8c2a019f..00000000 --- a/libraries/BLE/library.properties +++ /dev/null @@ -1,10 +0,0 @@ -name=ESP32 BLE Arduino -version=1.0.1 -author=Neil Kolban -maintainer=Dariusz Krempa -sentence=BLE functions for ESP32 -paragraph=This library provides an implementation Bluetooth Low Energy support for the ESP32 using the Arduino platform. -category=Communication -url=https://github.com/nkolban/ESP32_BLE_Arduino -architectures=esp32 -includes=BLEDevice.h, BLEUtils.h, BLEScan.h, BLEAdvertisedDevice.h diff --git a/libraries/BLE/src/BLE2902.cpp b/libraries/BLE/src/BLE2902.cpp deleted file mode 100644 index 0b695c26..00000000 --- a/libraries/BLE/src/BLE2902.cpp +++ /dev/null @@ -1,62 +0,0 @@ -/* - * BLE2902.cpp - * - * Created on: Jun 25, 2017 - * Author: kolban - */ - -/* - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLE2902.h" - -BLE2902::BLE2902() : BLEDescriptor(BLEUUID((uint16_t) 0x2902)) { - uint8_t data[2] = { 0, 0 }; - setValue(data, 2); -} // BLE2902 - - -/** - * @brief Get the notifications value. - * @return The notifications value. True if notifications are enabled and false if not. - */ -bool BLE2902::getNotifications() { - return (getValue()[0] & (1 << 0)) != 0; -} // getNotifications - - -/** - * @brief Get the indications value. - * @return The indications value. True if indications are enabled and false if not. - */ -bool BLE2902::getIndications() { - return (getValue()[0] & (1 << 1)) != 0; -} // getIndications - - -/** - * @brief Set the indications flag. - * @param [in] flag The indications flag. - */ -void BLE2902::setIndications(bool flag) { - uint8_t *pValue = getValue(); - if (flag) pValue[0] |= 1 << 1; - else pValue[0] &= ~(1 << 1); -} // setIndications - - -/** - * @brief Set the notifications flag. - * @param [in] flag The notifications flag. - */ -void BLE2902::setNotifications(bool flag) { - uint8_t *pValue = getValue(); - if (flag) pValue[0] |= 1 << 0; - else pValue[0] &= ~(1 << 0); -} // setNotifications - -#endif diff --git a/libraries/BLE/src/BLE2902.h b/libraries/BLE/src/BLE2902.h deleted file mode 100644 index b50ed750..00000000 --- a/libraries/BLE/src/BLE2902.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * BLE2902.h - * - * Created on: Jun 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLE2902_H_ -#define COMPONENTS_CPP_UTILS_BLE2902_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLEDescriptor.h" - -/** - * @brief Descriptor for Client Characteristic Configuration. - * - * This is a convenience descriptor for the Client Characteristic Configuration which has a UUID of 0x2902. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.client_characteristic_configuration.xml - */ -class BLE2902: public BLEDescriptor { -public: - BLE2902(); - bool getNotifications(); - bool getIndications(); - void setNotifications(bool flag); - void setIndications(bool flag); - -}; // BLE2902 - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLE2902_H_ */ diff --git a/libraries/BLE/src/BLE2904.cpp b/libraries/BLE/src/BLE2904.cpp deleted file mode 100644 index 23ad3e73..00000000 --- a/libraries/BLE/src/BLE2904.cpp +++ /dev/null @@ -1,74 +0,0 @@ -/* - * BLE2904.cpp - * - * Created on: Dec 23, 2017 - * Author: kolban - */ - -/* - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLE2904.h" - - -BLE2904::BLE2904() : BLEDescriptor(BLEUUID((uint16_t) 0x2904)) { - m_data.m_format = 0; - m_data.m_exponent = 0; - m_data.m_namespace = 1; // 1 = Bluetooth SIG Assigned Numbers - m_data.m_unit = 0; - m_data.m_description = 0; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} // BLE2902 - - -/** - * @brief Set the description. - */ -void BLE2904::setDescription(uint16_t description) { - m_data.m_description = description; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} - - -/** - * @brief Set the exponent. - */ -void BLE2904::setExponent(int8_t exponent) { - m_data.m_exponent = exponent; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} // setExponent - - -/** - * @brief Set the format. - */ -void BLE2904::setFormat(uint8_t format) { - m_data.m_format = format; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} // setFormat - - -/** - * @brief Set the namespace. - */ -void BLE2904::setNamespace(uint8_t namespace_value) { - m_data.m_namespace = namespace_value; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} // setNamespace - - -/** - * @brief Set the units for this value. It should be one of the encoded values defined here: - * https://www.bluetooth.com/specifications/assigned-numbers/units - * @param [in] unit The type of units of this characteristic as defined by assigned numbers. - */ -void BLE2904::setUnit(uint16_t unit) { - m_data.m_unit = unit; - setValue((uint8_t*) &m_data, sizeof(m_data)); -} // setUnit - -#endif diff --git a/libraries/BLE/src/BLE2904.h b/libraries/BLE/src/BLE2904.h deleted file mode 100644 index 4d607525..00000000 --- a/libraries/BLE/src/BLE2904.h +++ /dev/null @@ -1,74 +0,0 @@ -/* - * BLE2904.h - * - * Created on: Dec 23, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLE2904_H_ -#define COMPONENTS_CPP_UTILS_BLE2904_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLEDescriptor.h" - -struct BLE2904_Data { - uint8_t m_format; - int8_t m_exponent; - uint16_t m_unit; // See https://www.bluetooth.com/specifications/assigned-numbers/units - uint8_t m_namespace; - uint16_t m_description; - -} __attribute__((packed)); - -/** - * @brief Descriptor for Characteristic Presentation Format. - * - * This is a convenience descriptor for the Characteristic Presentation Format which has a UUID of 0x2904. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ -class BLE2904: public BLEDescriptor { -public: - BLE2904(); - static const uint8_t FORMAT_BOOLEAN = 1; - static const uint8_t FORMAT_UINT2 = 2; - static const uint8_t FORMAT_UINT4 = 3; - static const uint8_t FORMAT_UINT8 = 4; - static const uint8_t FORMAT_UINT12 = 5; - static const uint8_t FORMAT_UINT16 = 6; - static const uint8_t FORMAT_UINT24 = 7; - static const uint8_t FORMAT_UINT32 = 8; - static const uint8_t FORMAT_UINT48 = 9; - static const uint8_t FORMAT_UINT64 = 10; - static const uint8_t FORMAT_UINT128 = 11; - static const uint8_t FORMAT_SINT8 = 12; - static const uint8_t FORMAT_SINT12 = 13; - static const uint8_t FORMAT_SINT16 = 14; - static const uint8_t FORMAT_SINT24 = 15; - static const uint8_t FORMAT_SINT32 = 16; - static const uint8_t FORMAT_SINT48 = 17; - static const uint8_t FORMAT_SINT64 = 18; - static const uint8_t FORMAT_SINT128 = 19; - static const uint8_t FORMAT_FLOAT32 = 20; - static const uint8_t FORMAT_FLOAT64 = 21; - static const uint8_t FORMAT_SFLOAT16 = 22; - static const uint8_t FORMAT_SFLOAT32 = 23; - static const uint8_t FORMAT_IEEE20601 = 24; - static const uint8_t FORMAT_UTF8 = 25; - static const uint8_t FORMAT_UTF16 = 26; - static const uint8_t FORMAT_OPAQUE = 27; - - void setDescription(uint16_t); - void setExponent(int8_t exponent); - void setFormat(uint8_t format); - void setNamespace(uint8_t namespace_value); - void setUnit(uint16_t unit); - -private: - BLE2904_Data m_data; -}; // BLE2904 - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLE2904_H_ */ diff --git a/libraries/BLE/src/BLEAddress.cpp b/libraries/BLE/src/BLEAddress.cpp deleted file mode 100644 index b9e6e34e..00000000 --- a/libraries/BLE/src/BLEAddress.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* - * BLEAddress.cpp - * - * Created on: Jul 2, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLEAddress.h" -#include -#include -#include -#include -#include -#include -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - - -/** - * @brief Create an address from the native ESP32 representation. - * @param [in] address The native representation. - */ -BLEAddress::BLEAddress(esp_bd_addr_t address) { - memcpy(m_address, address, ESP_BD_ADDR_LEN); -} // BLEAddress - - -/** - * @brief Create an address from a hex string - * - * A hex string is of the format: - * ``` - * 00:00:00:00:00:00 - * ``` - * which is 17 characters in length. - * - * @param [in] stringAddress The hex representation of the address. - */ -BLEAddress::BLEAddress(std::string stringAddress) { - if (stringAddress.length() != 17) return; - - int data[6]; - sscanf(stringAddress.c_str(), "%x:%x:%x:%x:%x:%x", &data[0], &data[1], &data[2], &data[3], &data[4], &data[5]); - m_address[0] = (uint8_t) data[0]; - m_address[1] = (uint8_t) data[1]; - m_address[2] = (uint8_t) data[2]; - m_address[3] = (uint8_t) data[3]; - m_address[4] = (uint8_t) data[4]; - m_address[5] = (uint8_t) data[5]; -} // BLEAddress - - -/** - * @brief Determine if this address equals another. - * @param [in] otherAddress The other address to compare against. - * @return True if the addresses are equal. - */ -bool BLEAddress::equals(BLEAddress otherAddress) { - return memcmp(otherAddress.getNative(), m_address, 6) == 0; -} // equals - - -/** - * @brief Return the native representation of the address. - * @return The native representation of the address. - */ -esp_bd_addr_t *BLEAddress::getNative() { - return &m_address; -} // getNative - - -/** - * @brief Convert a BLE address to a string. - * - * A string representation of an address is in the format: - * - * ``` - * xx:xx:xx:xx:xx:xx - * ``` - * - * @return The string representation of the address. - */ -std::string BLEAddress::toString() { - auto size = 18; - char *res = (char*)malloc(size); - snprintf(res, size, "%02x:%02x:%02x:%02x:%02x:%02x", m_address[0], m_address[1], m_address[2], m_address[3], m_address[4], m_address[5]); - std::string ret(res); - free(res); - return ret; -} // toString -#endif diff --git a/libraries/BLE/src/BLEAddress.h b/libraries/BLE/src/BLEAddress.h deleted file mode 100644 index 81122c36..00000000 --- a/libraries/BLE/src/BLEAddress.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * BLEAddress.h - * - * Created on: Jul 2, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADDRESS_H_ -#define COMPONENTS_CPP_UTILS_BLEADDRESS_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include // ESP32 BLE -#include - - -/** - * @brief A %BLE device address. - * - * Every %BLE device has a unique address which can be used to identify it and form connections. - */ -class BLEAddress { -public: - BLEAddress(esp_bd_addr_t address); - BLEAddress(std::string stringAddress); - bool equals(BLEAddress otherAddress); - esp_bd_addr_t* getNative(); - std::string toString(); - -private: - esp_bd_addr_t m_address; -}; - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADDRESS_H_ */ diff --git a/libraries/BLE/src/BLEAdvertisedDevice.cpp b/libraries/BLE/src/BLEAdvertisedDevice.cpp deleted file mode 100644 index 4a4b23a3..00000000 --- a/libraries/BLE/src/BLEAdvertisedDevice.cpp +++ /dev/null @@ -1,575 +0,0 @@ -/* - * BLEAdvertisedDevice.cpp - * - * During the scanning procedure, we will be finding advertised BLE devices. This class - * models a found device. - * - * - * See also: - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - * - * Created on: Jul 3, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "BLEAdvertisedDevice.h" -#include "BLEUtils.h" -#include "esp32-hal-log.h" - -BLEAdvertisedDevice::BLEAdvertisedDevice() { - m_adFlag = 0; - m_appearance = 0; - m_deviceType = 0; - m_manufacturerData = ""; - m_name = ""; - m_rssi = -9999; - m_serviceData = {}; - m_serviceDataUUIDs = {}; - m_txPower = 0; - m_pScan = nullptr; - - m_haveAppearance = false; - m_haveManufacturerData = false; - m_haveName = false; - m_haveRSSI = false; - m_haveServiceData = false; - m_haveServiceUUID = false; - m_haveTXPower = false; - -} // BLEAdvertisedDevice - - -/** - * @brief Get the address. - * - * Every %BLE device exposes an address that is used to identify it and subsequently connect to it. - * Call this function to obtain the address of the advertised device. - * - * @return The address of the advertised device. - */ -BLEAddress BLEAdvertisedDevice::getAddress() { - return m_address; -} // getAddress - - -/** - * @brief Get the appearance. - * - * A %BLE device can declare its own appearance. The appearance is how it would like to be shown to an end user - * typcially in the form of an icon. - * - * @return The appearance of the advertised device. - */ -uint16_t BLEAdvertisedDevice::getAppearance() { - return m_appearance; -} // getAppearance - - -/** - * @brief Get the manufacturer data. - * @return The manufacturer data of the advertised device. - */ -std::string BLEAdvertisedDevice::getManufacturerData() { - return m_manufacturerData; -} // getManufacturerData - - -/** - * @brief Get the name. - * @return The name of the advertised device. - */ -std::string BLEAdvertisedDevice::getName() { - return m_name; -} // getName - - -/** - * @brief Get the RSSI. - * @return The RSSI of the advertised device. - */ -int BLEAdvertisedDevice::getRSSI() { - return m_rssi; -} // getRSSI - - -/** - * @brief Get the scan object that created this advertisement. - * @return The scan object. - */ -BLEScan* BLEAdvertisedDevice::getScan() { - return m_pScan; -} // getScan - -/** - * @brief Get the number of service data. - * @return Number of service data discovered. - */ -int BLEAdvertisedDevice::getServiceDataCount() { - if (m_haveServiceData) - return m_serviceData.size(); - else - return 0; - -} //getServiceDataCount - -/** - * @brief Get the service data. - * @return The ServiceData of the advertised device. - */ -std::string BLEAdvertisedDevice::getServiceData() { - return m_serviceData[0]; -} //getServiceData - -/** - * @brief Get the service data. - * @return The ServiceData of the advertised device. - */ -std::string BLEAdvertisedDevice::getServiceData(int i) { - return m_serviceData[i]; -} //getServiceData - -/** - * @brief Get the service data UUID. - * @return The service data UUID. - */ -BLEUUID BLEAdvertisedDevice::getServiceDataUUID() { - return m_serviceDataUUIDs[0]; -} // getServiceDataUUID - -/** - * @brief Get the service data UUID. - * @return The service data UUID. - */ -BLEUUID BLEAdvertisedDevice::getServiceDataUUID(int i) { - return m_serviceDataUUIDs[i]; -} // getServiceDataUUID - -/** - * @brief Get the Service UUID. - * @return The Service UUID of the advertised device. - */ -BLEUUID BLEAdvertisedDevice::getServiceUUID() { - return m_serviceUUIDs[0]; -} // getServiceUUID - -/** - * @brief Get the Service UUID. - * @return The Service UUID of the advertised device. - */ -BLEUUID BLEAdvertisedDevice::getServiceUUID(int i) { - return m_serviceUUIDs[i]; -} // getServiceUUID - -/** - * @brief Check advertised serviced for existence required UUID - * @return Return true if service is advertised - */ -bool BLEAdvertisedDevice::isAdvertisingService(BLEUUID uuid){ - for (int i = 0; i < m_serviceUUIDs.size(); i++) { - if (m_serviceUUIDs[i].equals(uuid)) return true; - } - return false; -} - -/** - * @brief Get the TX Power. - * @return The TX Power of the advertised device. - */ -int8_t BLEAdvertisedDevice::getTXPower() { - return m_txPower; -} // getTXPower - - - -/** - * @brief Does this advertisement have an appearance value? - * @return True if there is an appearance value present. - */ -bool BLEAdvertisedDevice::haveAppearance() { - return m_haveAppearance; -} // haveAppearance - - -/** - * @brief Does this advertisement have manufacturer data? - * @return True if there is manufacturer data present. - */ -bool BLEAdvertisedDevice::haveManufacturerData() { - return m_haveManufacturerData; -} // haveManufacturerData - - -/** - * @brief Does this advertisement have a name value? - * @return True if there is a name value present. - */ -bool BLEAdvertisedDevice::haveName() { - return m_haveName; -} // haveName - - -/** - * @brief Does this advertisement have a signal strength value? - * @return True if there is a signal strength value present. - */ -bool BLEAdvertisedDevice::haveRSSI() { - return m_haveRSSI; -} // haveRSSI - - -/** - * @brief Does this advertisement have a service data value? - * @return True if there is a service data value present. - */ -bool BLEAdvertisedDevice::haveServiceData() { - return m_haveServiceData; -} // haveServiceData - - -/** - * @brief Does this advertisement have a service UUID value? - * @return True if there is a service UUID value present. - */ -bool BLEAdvertisedDevice::haveServiceUUID() { - return m_haveServiceUUID; -} // haveServiceUUID - - -/** - * @brief Does this advertisement have a transmission power value? - * @return True if there is a transmission power value present. - */ -bool BLEAdvertisedDevice::haveTXPower() { - return m_haveTXPower; -} // haveTXPower - - -/** - * @brief Parse the advertising pay load. - * - * The pay load is a buffer of bytes that is either 31 bytes long or terminated by - * a 0 length value. Each entry in the buffer has the format: - * [length][type][data...] - * - * The length does not include itself but does include everything after it until the next record. A record - * with a length value of 0 indicates a terminator. - * - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - */ -void BLEAdvertisedDevice::parseAdvertisement(uint8_t* payload, size_t total_len) { - uint8_t length; - uint8_t ad_type; - uint8_t sizeConsumed = 0; - bool finished = false; - m_payload = payload; - m_payloadLength = total_len; - - while(!finished) { - length = *payload; // Retrieve the length of the record. - payload++; // Skip to type - sizeConsumed += 1 + length; // increase the size consumed. - - if (length != 0) { // A length of 0 indicates that we have reached the end. - ad_type = *payload; - payload++; - length--; - - char* pHex = BLEUtils::buildHexData(nullptr, payload, length); - log_d("Type: 0x%.2x (%s), length: %d, data: %s", - ad_type, BLEUtils::advTypeToString(ad_type), length, pHex); - free(pHex); - - switch(ad_type) { - case ESP_BLE_AD_TYPE_NAME_CMPL: { // Adv Data Type: 0x09 - setName(std::string(reinterpret_cast(payload), length)); - break; - } // ESP_BLE_AD_TYPE_NAME_CMPL - - case ESP_BLE_AD_TYPE_TX_PWR: { // Adv Data Type: 0x0A - setTXPower(*payload); - break; - } // ESP_BLE_AD_TYPE_TX_PWR - - case ESP_BLE_AD_TYPE_APPEARANCE: { // Adv Data Type: 0x19 - setAppearance(*reinterpret_cast(payload)); - break; - } // ESP_BLE_AD_TYPE_APPEARANCE - - case ESP_BLE_AD_TYPE_FLAG: { // Adv Data Type: 0x01 - setAdFlag(*payload); - break; - } // ESP_BLE_AD_TYPE_FLAG - - case ESP_BLE_AD_TYPE_16SRV_CMPL: - case ESP_BLE_AD_TYPE_16SRV_PART: { // Adv Data Type: 0x02 - for (int var = 0; var < length/2; ++var) { - setServiceUUID(BLEUUID(*reinterpret_cast(payload + var * 2))); - } - break; - } // ESP_BLE_AD_TYPE_16SRV_PART - - case ESP_BLE_AD_TYPE_32SRV_CMPL: - case ESP_BLE_AD_TYPE_32SRV_PART: { // Adv Data Type: 0x04 - for (int var = 0; var < length/4; ++var) { - setServiceUUID(BLEUUID(*reinterpret_cast(payload + var * 4))); - } - break; - } // ESP_BLE_AD_TYPE_32SRV_PART - - case ESP_BLE_AD_TYPE_128SRV_CMPL: { // Adv Data Type: 0x07 - setServiceUUID(BLEUUID(payload, 16, false)); - break; - } // ESP_BLE_AD_TYPE_128SRV_CMPL - - case ESP_BLE_AD_TYPE_128SRV_PART: { // Adv Data Type: 0x06 - setServiceUUID(BLEUUID(payload, 16, false)); - break; - } // ESP_BLE_AD_TYPE_128SRV_PART - - // See CSS Part A 1.4 Manufacturer Specific Data - case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: { - setManufacturerData(std::string(reinterpret_cast(payload), length)); - break; - } // ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE - - case ESP_BLE_AD_TYPE_SERVICE_DATA: { // Adv Data Type: 0x16 (Service Data) - 2 byte UUID - if (length < 2) { - log_e("Length too small for ESP_BLE_AD_TYPE_SERVICE_DATA"); - break; - } - uint16_t uuid = *(uint16_t*)payload; - setServiceDataUUID(BLEUUID(uuid)); - if (length > 2) { - setServiceData(std::string(reinterpret_cast(payload + 2), length - 2)); - } - break; - } //ESP_BLE_AD_TYPE_SERVICE_DATA - - case ESP_BLE_AD_TYPE_32SERVICE_DATA: { // Adv Data Type: 0x20 (Service Data) - 4 byte UUID - if (length < 4) { - log_e("Length too small for ESP_BLE_AD_TYPE_32SERVICE_DATA"); - break; - } - uint32_t uuid = *(uint32_t*) payload; - setServiceDataUUID(BLEUUID(uuid)); - if (length > 4) { - setServiceData(std::string(reinterpret_cast(payload + 4), length - 4)); - } - break; - } //ESP_BLE_AD_TYPE_32SERVICE_DATA - - case ESP_BLE_AD_TYPE_128SERVICE_DATA: { // Adv Data Type: 0x21 (Service Data) - 16 byte UUID - if (length < 16) { - log_e("Length too small for ESP_BLE_AD_TYPE_128SERVICE_DATA"); - break; - } - - setServiceDataUUID(BLEUUID(payload, (size_t)16, false)); - if (length > 16) { - setServiceData(std::string(reinterpret_cast(payload + 16), length - 16)); - } - break; - } //ESP_BLE_AD_TYPE_32SERVICE_DATA - - default: { - log_d("Unhandled type: adType: %d - 0x%.2x", ad_type, ad_type); - break; - } - } // switch - payload += length; - } // Length <> 0 - - - if (sizeConsumed >= total_len) - finished = true; - - } // !finished -} // parseAdvertisement - -/** - * @brief Parse the advertising payload. - * @param [in] payload The payload of the advertised device. - * @param [in] total_len The length of payload - */ -void BLEAdvertisedDevice::setPayload(uint8_t* payload, size_t total_len) { - m_payload = payload; - m_payloadLength = total_len; -} // setPayload - -/** - * @brief Set the address of the advertised device. - * @param [in] address The address of the advertised device. - */ -void BLEAdvertisedDevice::setAddress(BLEAddress address) { - m_address = address; -} // setAddress - - -/** - * @brief Set the adFlag for this device. - * @param [in] The discovered adFlag. - */ -void BLEAdvertisedDevice::setAdFlag(uint8_t adFlag) { - m_adFlag = adFlag; -} // setAdFlag - - -/** - * @brief Set the appearance for this device. - * @param [in] The discovered appearance. - */ -void BLEAdvertisedDevice::setAppearance(uint16_t appearance) { - m_appearance = appearance; - m_haveAppearance = true; - log_d("- appearance: %d", m_appearance); -} // setAppearance - - -/** - * @brief Set the manufacturer data for this device. - * @param [in] The discovered manufacturer data. - */ -void BLEAdvertisedDevice::setManufacturerData(std::string manufacturerData) { - m_manufacturerData = manufacturerData; - m_haveManufacturerData = true; - char* pHex = BLEUtils::buildHexData(nullptr, (uint8_t*) m_manufacturerData.data(), (uint8_t) m_manufacturerData.length()); - log_d("- manufacturer data: %s", pHex); - free(pHex); -} // setManufacturerData - - -/** - * @brief Set the name for this device. - * @param [in] name The discovered name. - */ -void BLEAdvertisedDevice::setName(std::string name) { - m_name = name; - m_haveName = true; - log_d("- setName(): name: %s", m_name.c_str()); -} // setName - - -/** - * @brief Set the RSSI for this device. - * @param [in] rssi The discovered RSSI. - */ -void BLEAdvertisedDevice::setRSSI(int rssi) { - m_rssi = rssi; - m_haveRSSI = true; - log_d("- setRSSI(): rssi: %d", m_rssi); -} // setRSSI - - -/** - * @brief Set the Scan that created this advertised device. - * @param pScan The Scan that created this advertised device. - */ -void BLEAdvertisedDevice::setScan(BLEScan* pScan) { - m_pScan = pScan; -} // setScan - - -/** - * @brief Set the Service UUID for this device. - * @param [in] serviceUUID The discovered serviceUUID - */ -void BLEAdvertisedDevice::setServiceUUID(const char* serviceUUID) { - return setServiceUUID(BLEUUID(serviceUUID)); -} // setServiceUUID - - -/** - * @brief Set the Service UUID for this device. - * @param [in] serviceUUID The discovered serviceUUID - */ -void BLEAdvertisedDevice::setServiceUUID(BLEUUID serviceUUID) { - m_serviceUUIDs.push_back(serviceUUID); - m_haveServiceUUID = true; - log_d("- addServiceUUID(): serviceUUID: %s", serviceUUID.toString().c_str()); -} // setServiceUUID - - -/** - * @brief Set the ServiceData value. - * @param [in] data ServiceData value. - */ -void BLEAdvertisedDevice::setServiceData(std::string serviceData) { - m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceData.push_back(serviceData); // Save the service data that we received. -} //setServiceData - - -/** - * @brief Set the ServiceDataUUID value. - * @param [in] data ServiceDataUUID value. - */ -void BLEAdvertisedDevice::setServiceDataUUID(BLEUUID uuid) { - m_haveServiceData = true; // Set the flag that indicates we have service data. - m_serviceDataUUIDs.push_back(uuid); - log_d("- addServiceDataUUID(): serviceDataUUID: %s", uuid.toString().c_str()); -} // setServiceDataUUID - - -/** - * @brief Set the power level for this device. - * @param [in] txPower The discovered power level. - */ -void BLEAdvertisedDevice::setTXPower(int8_t txPower) { - m_txPower = txPower; - m_haveTXPower = true; - log_d("- txPower: %d", m_txPower); -} // setTXPower - - -/** - * @brief Create a string representation of this device. - * @return A string representation of this device. - */ -std::string BLEAdvertisedDevice::toString() { - std::string res = "Name: " + getName() + ", Address: " + getAddress().toString(); - if (haveAppearance()) { - char val[6]; - snprintf(val, sizeof(val), "%d", getAppearance()); - res += ", appearance: "; - res += val; - } - if (haveManufacturerData()) { - char *pHex = BLEUtils::buildHexData(nullptr, (uint8_t*)getManufacturerData().data(), getManufacturerData().length()); - res += ", manufacturer data: "; - res += pHex; - free(pHex); - } - if (haveServiceUUID()) { - for (int i=0; i < m_serviceUUIDs.size(); i++) { - res += ", serviceUUID: " + getServiceUUID(i).toString(); - } - } - if (haveTXPower()) { - char val[6]; - snprintf(val, sizeof(val), "%d", getTXPower()); - res += ", txPower: "; - res += val; - } - return res; -} // toString - -uint8_t* BLEAdvertisedDevice::getPayload() { - return m_payload; -} - -esp_ble_addr_type_t BLEAdvertisedDevice::getAddressType() { - return m_addressType; -} - -void BLEAdvertisedDevice::setAddressType(esp_ble_addr_type_t type) { - m_addressType = type; -} - -size_t BLEAdvertisedDevice::getPayloadLength() { - return m_payloadLength; -} - -#endif /* CONFIG_BLUEDROID_ENABLED */ - diff --git a/libraries/BLE/src/BLEAdvertisedDevice.h b/libraries/BLE/src/BLEAdvertisedDevice.h deleted file mode 100644 index d92cc539..00000000 --- a/libraries/BLE/src/BLEAdvertisedDevice.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * BLEAdvertisedDevice.h - * - * Created on: Jul 3, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ -#define COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include - -#include - -#include "BLEAddress.h" -#include "BLEScan.h" -#include "BLEUUID.h" - - -class BLEScan; -/** - * @brief A representation of a %BLE advertised device found by a scan. - * - * When we perform a %BLE scan, the result will be a set of devices that are advertising. This - * class provides a model of a detected device. - */ -class BLEAdvertisedDevice { -public: - BLEAdvertisedDevice(); - - BLEAddress getAddress(); - uint16_t getAppearance(); - std::string getManufacturerData(); - std::string getName(); - int getRSSI(); - BLEScan* getScan(); - std::string getServiceData(); - std::string getServiceData(int i); - BLEUUID getServiceDataUUID(); - BLEUUID getServiceDataUUID(int i); - BLEUUID getServiceUUID(); - BLEUUID getServiceUUID(int i); - int getServiceDataCount(); - int8_t getTXPower(); - uint8_t* getPayload(); - size_t getPayloadLength(); - esp_ble_addr_type_t getAddressType(); - void setAddressType(esp_ble_addr_type_t type); - - - bool isAdvertisingService(BLEUUID uuid); - bool haveAppearance(); - bool haveManufacturerData(); - bool haveName(); - bool haveRSSI(); - bool haveServiceData(); - bool haveServiceUUID(); - bool haveTXPower(); - - std::string toString(); - -private: - friend class BLEScan; - - void parseAdvertisement(uint8_t* payload, size_t total_len=62); - void setPayload(uint8_t* payload, size_t total_len=62); - void setAddress(BLEAddress address); - void setAdFlag(uint8_t adFlag); - void setAdvertizementResult(uint8_t* payload); - void setAppearance(uint16_t appearance); - void setManufacturerData(std::string manufacturerData); - void setName(std::string name); - void setRSSI(int rssi); - void setScan(BLEScan* pScan); - void setServiceData(std::string data); - void setServiceDataUUID(BLEUUID uuid); - void setServiceUUID(const char* serviceUUID); - void setServiceUUID(BLEUUID serviceUUID); - void setTXPower(int8_t txPower); - - bool m_haveAppearance; - bool m_haveManufacturerData; - bool m_haveName; - bool m_haveRSSI; - bool m_haveServiceData; - bool m_haveServiceUUID; - bool m_haveTXPower; - - - BLEAddress m_address = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); - uint8_t m_adFlag; - uint16_t m_appearance; - int m_deviceType; - std::string m_manufacturerData; - std::string m_name; - BLEScan* m_pScan; - int m_rssi; - std::vector m_serviceUUIDs; - int8_t m_txPower; - std::vector m_serviceData; - std::vector m_serviceDataUUIDs; - uint8_t* m_payload; - size_t m_payloadLength = 0; - esp_ble_addr_type_t m_addressType; -}; - -/** - * @brief A callback handler for callbacks associated device scanning. - * - * When we are performing a scan as a %BLE client, we may wish to know when a new device that is advertising - * has been found. This class can be sub-classed and registered such that when a scan is performed and - * a new advertised device has been found, we will be called back to be notified. - */ -class BLEAdvertisedDeviceCallbacks { -public: - virtual ~BLEAdvertisedDeviceCallbacks() {} - /** - * @brief Called when a new scan result is detected. - * - * As we are scanning, we will find new devices. When found, this call back is invoked with a reference to the - * device that was found. During any individual scan, a device will only be detected one time. - */ - virtual void onResult(BLEAdvertisedDevice advertisedDevice) = 0; -}; - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISEDDEVICE_H_ */ diff --git a/libraries/BLE/src/BLEAdvertising.cpp b/libraries/BLE/src/BLEAdvertising.cpp deleted file mode 100644 index 7eb56681..00000000 --- a/libraries/BLE/src/BLEAdvertising.cpp +++ /dev/null @@ -1,528 +0,0 @@ -/* - * BLEAdvertising.cpp - * - * This class encapsulates advertising a BLE Server. - * Created on: Jun 21, 2017 - * Author: kolban - * - * The ESP-IDF provides a framework for BLE advertising. It has determined that there are a common set - * of properties that are advertised and has built a data structure that can be populated by the programmer. - * This means that the programmer doesn't have to "mess with" the low level construction of a low level - * BLE advertising frame. Many of the fields are determined for us while others we can set before starting - * to advertise. - * - * Should we wish to construct our own payload, we can use the BLEAdvertisementData class and call the setters - * upon it. Once it is populated, we can then associate it with the advertising and what ever the programmer - * set in the data will be advertised. - * - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include "BLEAdvertising.h" -#include -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -/** - * @brief Construct a default advertising object. - * - */ -BLEAdvertising::BLEAdvertising() -: m_scanRespData{} -{ - m_advData.set_scan_rsp = false; - m_advData.include_name = true; - m_advData.include_txpower = true; - m_advData.min_interval = 0x20; - m_advData.max_interval = 0x40; - m_advData.appearance = 0x00; - m_advData.manufacturer_len = 0; - m_advData.p_manufacturer_data = nullptr; - m_advData.service_data_len = 0; - m_advData.p_service_data = nullptr; - m_advData.service_uuid_len = 0; - m_advData.p_service_uuid = nullptr; - m_advData.flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT); - - m_advParams.adv_int_min = 0x20; - m_advParams.adv_int_max = 0x40; - m_advParams.adv_type = ADV_TYPE_IND; - m_advParams.own_addr_type = BLE_ADDR_TYPE_PUBLIC; - m_advParams.channel_map = ADV_CHNL_ALL; - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - m_advParams.peer_addr_type = BLE_ADDR_TYPE_PUBLIC; - - m_customAdvData = false; // No custom advertising data - m_customScanResponseData = false; // No custom scan response data -} // BLEAdvertising - - -/** - * @brief Add a service uuid to exposed list of services. - * @param [in] serviceUUID The UUID of the service to expose. - */ -void BLEAdvertising::addServiceUUID(BLEUUID serviceUUID) { - m_serviceUUIDs.push_back(serviceUUID); -} // addServiceUUID - - -/** - * @brief Add a service uuid to exposed list of services. - * @param [in] serviceUUID The string representation of the service to expose. - */ -void BLEAdvertising::addServiceUUID(const char* serviceUUID) { - addServiceUUID(BLEUUID(serviceUUID)); -} // addServiceUUID - - -/** - * @brief Set the device appearance in the advertising data. - * The appearance attribute is of type 0x19. The codes for distinct appearances can be found here: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml. - * @param [in] appearance The appearance of the device in the advertising data. - * @return N/A. - */ -void BLEAdvertising::setAppearance(uint16_t appearance) { - m_advData.appearance = appearance; -} // setAppearance - -void BLEAdvertising::setAdvertisementType(esp_ble_adv_type_t adv_type){ - m_advParams.adv_type = adv_type; -} // setAdvertisementType - -void BLEAdvertising::setMinInterval(uint16_t mininterval) { - m_advParams.adv_int_min = mininterval; -} // setMinInterval - -void BLEAdvertising::setMaxInterval(uint16_t maxinterval) { - m_advParams.adv_int_max = maxinterval; -} // setMaxInterval - -void BLEAdvertising::setMinPreferred(uint16_t mininterval) { - m_advData.min_interval = mininterval; -} // - -void BLEAdvertising::setMaxPreferred(uint16_t maxinterval) { - m_advData.max_interval = maxinterval; -} // - -void BLEAdvertising::setScanResponse(bool set) { - m_scanResp = set; -} - -/** - * @brief Set the filtering for the scan filter. - * @param [in] scanRequestWhitelistOnly If true, only allow scan requests from those on the white list. - * @param [in] connectWhitelistOnly If true, only allow connections from those on the white list. - */ -void BLEAdvertising::setScanFilter(bool scanRequestWhitelistOnly, bool connectWhitelistOnly) { - log_v(">> setScanFilter: scanRequestWhitelistOnly: %d, connectWhitelistOnly: %d", scanRequestWhitelistOnly, connectWhitelistOnly); - if (!scanRequestWhitelistOnly && !connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY; - log_v("<< setScanFilter"); - return; - } - if (scanRequestWhitelistOnly && !connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_ANY; - log_v("<< setScanFilter"); - return; - } - if (!scanRequestWhitelistOnly && connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_WLST; - log_v("<< setScanFilter"); - return; - } - if (scanRequestWhitelistOnly && connectWhitelistOnly) { - m_advParams.adv_filter_policy = ADV_FILTER_ALLOW_SCAN_WLST_CON_WLST; - log_v("<< setScanFilter"); - return; - } -} // setScanFilter - - -/** - * @brief Set the advertisement data that is to be published in a regular advertisement. - * @param [in] advertisementData The data to be advertised. - */ -void BLEAdvertising::setAdvertisementData(BLEAdvertisementData& advertisementData) { - log_v(">> setAdvertisementData"); - esp_err_t errRc = ::esp_ble_gap_config_adv_data_raw( - (uint8_t*)advertisementData.getPayload().data(), - advertisementData.getPayload().length()); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_config_adv_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); - } - m_customAdvData = true; // Set the flag that indicates we are using custom advertising data. - log_v("<< setAdvertisementData"); -} // setAdvertisementData - - -/** - * @brief Set the advertisement data that is to be published in a scan response. - * @param [in] advertisementData The data to be advertised. - */ -void BLEAdvertising::setScanResponseData(BLEAdvertisementData& advertisementData) { - log_v(">> setScanResponseData"); - esp_err_t errRc = ::esp_ble_gap_config_scan_rsp_data_raw( - (uint8_t*)advertisementData.getPayload().data(), - advertisementData.getPayload().length()); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_config_scan_rsp_data_raw: %d %s", errRc, GeneralUtils::errorToString(errRc)); - } - m_customScanResponseData = true; // Set the flag that indicates we are using custom scan response data. - log_v("<< setScanResponseData"); -} // setScanResponseData - -/** - * @brief Start advertising. - * Start advertising. - * @return N/A. - */ -void BLEAdvertising::start() { - log_v(">> start: customAdvData: %d, customScanResponseData: %d", m_customAdvData, m_customScanResponseData); - - // We have a vector of service UUIDs that we wish to advertise. In order to use the - // ESP-IDF framework, these must be supplied in a contiguous array of their 128bit (16 byte) - // representations. If we have 1 or more services to advertise then we allocate enough - // storage to host them and then copy them in one at a time into the contiguous storage. - int numServices = m_serviceUUIDs.size(); - if (numServices > 0) { - m_advData.service_uuid_len = 16 * numServices; - m_advData.p_service_uuid = new uint8_t[m_advData.service_uuid_len]; - uint8_t* p = m_advData.p_service_uuid; - for (int i = 0; i < numServices; i++) { - log_d("- advertising service: %s", m_serviceUUIDs[i].toString().c_str()); - BLEUUID serviceUUID128 = m_serviceUUIDs[i].to128(); - memcpy(p, serviceUUID128.getNative()->uuid.uuid128, 16); - p += 16; - } - } else { - m_advData.service_uuid_len = 0; - log_d("- no services advertised"); - } - - esp_err_t errRc; - - if (!m_customAdvData) { - // Set the configuration for advertising. - m_advData.set_scan_rsp = false; - m_advData.include_name = !m_scanResp; - m_advData.include_txpower = !m_scanResp; - errRc = ::esp_ble_gap_config_adv_data(&m_advData); - if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_config_adv_data: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - if (!m_customScanResponseData && m_scanResp) { - // Set the configuration for scan response. - memcpy(&m_scanRespData, &m_advData, sizeof(esp_ble_adv_data_t)); // Copy the content of m_advData. - m_scanRespData.set_scan_rsp = true; // Define this struct as scan response data - m_scanRespData.include_name = true; // Caution: This may lead to a crash if the device name has more than 29 characters - m_scanRespData.include_txpower = true; - m_scanRespData.appearance = 0; // If defined the 'Appearance' attribute is already included in the advertising data - m_scanRespData.flag = 0; // 'Flags' attribute should no be included in the scan response - - errRc = ::esp_ble_gap_config_adv_data(&m_scanRespData); - if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_config_adv_data (Scan response): rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - // If we had services to advertise then we previously allocated some storage for them. - // Here we release that storage. - if (m_advData.service_uuid_len > 0) { - delete[] m_advData.p_service_uuid; - m_advData.p_service_uuid = nullptr; - } - - // Start advertising. - errRc = ::esp_ble_gap_start_advertising(&m_advParams); - if (errRc != ESP_OK) { - log_e("<< esp_ble_gap_start_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - log_v("<< start"); -} // start - - -/** - * @brief Stop advertising. - * Stop advertising. - * @return N/A. - */ -void BLEAdvertising::stop() { - log_v(">> stop"); - esp_err_t errRc = ::esp_ble_gap_stop_advertising(); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_stop_advertising: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - log_v("<< stop"); -} // stop - -/** - * @brief Set BLE address. - * @param [in] Bluetooth address. - * @param [in] Bluetooth address type. - * Set BLE address. - */ - -void BLEAdvertising::setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type) -{ - log_v(">> setPrivateAddress"); - - m_advParams.own_addr_type = type; - esp_err_t errRc = esp_ble_gap_set_rand_addr((uint8_t*)addr); - if (errRc != ESP_OK) - { - log_e("esp_ble_gap_set_rand_addr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - log_v("<< setPrivateAddress"); -} // setPrivateAddress - -/** - * @brief Add data to the payload to be advertised. - * @param [in] data The data to be added to the payload. - */ -void BLEAdvertisementData::addData(std::string data) { - if ((m_payload.length() + data.length()) > ESP_BLE_ADV_DATA_LEN_MAX) { - return; - } - m_payload.append(data); -} // addData - - -/** - * @brief Set the appearance. - * @param [in] appearance The appearance code value. - * - * See also: - * https://www.bluetooth.com/specifications/gatt/viewer?attributeXmlFile=org.bluetooth.characteristic.gap.appearance.xml - */ -void BLEAdvertisementData::setAppearance(uint16_t appearance) { - char cdata[2]; - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_APPEARANCE; // 0x19 - addData(std::string(cdata, 2) + std::string((char*) &appearance, 2)); -} // setAppearance - - -/** - * @brief Set the complete services. - * @param [in] uuid The single service to advertise. - */ -void BLEAdvertisementData::setCompleteServices(BLEUUID uuid) { - char cdata[2]; - switch (uuid.bitSize()) { - case 16: { - // [Len] [0x02] [LL] [HH] - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_16SRV_CMPL; // 0x03 - addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid16, 2)); - break; - } - - case 32: { - // [Len] [0x04] [LL] [LL] [HH] [HH] - cdata[0] = 5; - cdata[1] = ESP_BLE_AD_TYPE_32SRV_CMPL; // 0x05 - addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid32, 4)); - break; - } - - case 128: { - // [Len] [0x04] [0] [1] ... [15] - cdata[0] = 17; - cdata[1] = ESP_BLE_AD_TYPE_128SRV_CMPL; // 0x07 - addData(std::string(cdata, 2) + std::string((char*) uuid.getNative()->uuid.uuid128, 16)); - break; - } - - default: - return; - } -} // setCompleteServices - - -/** - * @brief Set the advertisement flags. - * @param [in] The flags to be set in the advertisement. - * - * * ESP_BLE_ADV_FLAG_LIMIT_DISC - * * ESP_BLE_ADV_FLAG_GEN_DISC - * * ESP_BLE_ADV_FLAG_BREDR_NOT_SPT - * * ESP_BLE_ADV_FLAG_DMT_CONTROLLER_SPT - * * ESP_BLE_ADV_FLAG_DMT_HOST_SPT - * * ESP_BLE_ADV_FLAG_NON_LIMIT_DISC - */ -void BLEAdvertisementData::setFlags(uint8_t flag) { - char cdata[3]; - cdata[0] = 2; - cdata[1] = ESP_BLE_AD_TYPE_FLAG; // 0x01 - cdata[2] = flag; - addData(std::string(cdata, 3)); -} // setFlag - - - -/** - * @brief Set manufacturer specific data. - * @param [in] data Manufacturer data. - */ -void BLEAdvertisementData::setManufacturerData(std::string data) { - log_d("BLEAdvertisementData", ">> setManufacturerData"); - char cdata[2]; - cdata[0] = data.length() + 1; - cdata[1] = ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE; // 0xff - addData(std::string(cdata, 2) + data); - log_d("BLEAdvertisementData", "<< setManufacturerData"); -} // setManufacturerData - - -/** - * @brief Set the name. - * @param [in] The complete name of the device. - */ -void BLEAdvertisementData::setName(std::string name) { - log_d("BLEAdvertisementData", ">> setName: %s", name.c_str()); - char cdata[2]; - cdata[0] = name.length() + 1; - cdata[1] = ESP_BLE_AD_TYPE_NAME_CMPL; // 0x09 - addData(std::string(cdata, 2) + name); - log_d("BLEAdvertisementData", "<< setName"); -} // setName - - -/** - * @brief Set the partial services. - * @param [in] uuid The single service to advertise. - */ -void BLEAdvertisementData::setPartialServices(BLEUUID uuid) { - char cdata[2]; - switch (uuid.bitSize()) { - case 16: { - // [Len] [0x02] [LL] [HH] - cdata[0] = 3; - cdata[1] = ESP_BLE_AD_TYPE_16SRV_PART; // 0x02 - addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid16, 2)); - break; - } - - case 32: { - // [Len] [0x04] [LL] [LL] [HH] [HH] - cdata[0] = 5; - cdata[1] = ESP_BLE_AD_TYPE_32SRV_PART; // 0x04 - addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid32, 4)); - break; - } - - case 128: { - // [Len] [0x04] [0] [1] ... [15] - cdata[0] = 17; - cdata[1] = ESP_BLE_AD_TYPE_128SRV_PART; // 0x06 - addData(std::string(cdata, 2) + std::string((char *) &uuid.getNative()->uuid.uuid128, 16)); - break; - } - - default: - return; - } -} // setPartialServices - - -/** - * @brief Set the service data (UUID + data) - * @param [in] uuid The UUID to set with the service data. Size of UUID will be used. - * @param [in] data The data to be associated with the service data advert. - */ -void BLEAdvertisementData::setServiceData(BLEUUID uuid, std::string data) { - char cdata[2]; - switch (uuid.bitSize()) { - case 16: { - // [Len] [0x16] [UUID16] data - cdata[0] = data.length() + 3; - cdata[1] = ESP_BLE_AD_TYPE_SERVICE_DATA; // 0x16 - addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid16, 2) + data); - break; - } - - case 32: { - // [Len] [0x20] [UUID32] data - cdata[0] = data.length() + 5; - cdata[1] = ESP_BLE_AD_TYPE_32SERVICE_DATA; // 0x20 - addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid32, 4) + data); - break; - } - - case 128: { - // [Len] [0x21] [UUID128] data - cdata[0] = data.length() + 17; - cdata[1] = ESP_BLE_AD_TYPE_128SERVICE_DATA; // 0x21 - addData(std::string(cdata, 2) + std::string((char*) &uuid.getNative()->uuid.uuid128, 16) + data); - break; - } - - default: - return; - } -} // setServiceData - - -/** - * @brief Set the short name. - * @param [in] The short name of the device. - */ -void BLEAdvertisementData::setShortName(std::string name) { - log_d("BLEAdvertisementData", ">> setShortName: %s", name.c_str()); - char cdata[2]; - cdata[0] = name.length() + 1; - cdata[1] = ESP_BLE_AD_TYPE_NAME_SHORT; // 0x08 - addData(std::string(cdata, 2) + name); - log_d("BLEAdvertisementData", "<< setShortName"); -} // setShortName - - -/** - * @brief Retrieve the payload that is to be advertised. - * @return The payload that is to be advertised. - */ -std::string BLEAdvertisementData::getPayload() { - return m_payload; -} // getPayload - -void BLEAdvertising::handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param) { - - log_d("handleGAPEvent [event no: %d]", (int)event); - - switch(event) { - case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { - // m_semaphoreSetAdv.give(); - break; - } - case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { - // m_semaphoreSetAdv.give(); - break; - } - case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { - // m_semaphoreSetAdv.give(); - break; - } - case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { - log_i("STOP advertising"); - //start(); - break; - } - default: - break; - } -} - - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEAdvertising.h b/libraries/BLE/src/BLEAdvertising.h deleted file mode 100644 index 7a64952a..00000000 --- a/libraries/BLE/src/BLEAdvertising.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * BLEAdvertising.h - * - * Created on: Jun 21, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ -#define COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "BLEUUID.h" -#include -#include "RTOS.h" - -/** - * @brief Advertisement data set by the programmer to be published by the %BLE server. - */ -class BLEAdvertisementData { - // Only a subset of the possible BLE architected advertisement fields are currently exposed. Others will - // be exposed on demand/request or as time permits. - // -public: - void setAppearance(uint16_t appearance); - void setCompleteServices(BLEUUID uuid); - void setFlags(uint8_t); - void setManufacturerData(std::string data); - void setName(std::string name); - void setPartialServices(BLEUUID uuid); - void setServiceData(BLEUUID uuid, std::string data); - void setShortName(std::string name); - void addData(std::string data); // Add data to the payload. - std::string getPayload(); // Retrieve the current advert payload. - -private: - friend class BLEAdvertising; - std::string m_payload; // The payload of the advertisement. -}; // BLEAdvertisementData - - -/** - * @brief Perform and manage %BLE advertising. - * - * A %BLE server will want to perform advertising in order to make itself known to %BLE clients. - */ -class BLEAdvertising { -public: - BLEAdvertising(); - void addServiceUUID(BLEUUID serviceUUID); - void addServiceUUID(const char* serviceUUID); - void start(); - void stop(); - void setAppearance(uint16_t appearance); - void setAdvertisementType(esp_ble_adv_type_t adv_type); - void setMaxInterval(uint16_t maxinterval); - void setMinInterval(uint16_t mininterval); - void setAdvertisementData(BLEAdvertisementData& advertisementData); - void setScanFilter(bool scanRequertWhitelistOnly, bool connectWhitelistOnly); - void setScanResponseData(BLEAdvertisementData& advertisementData); - void setPrivateAddress(esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); - void setDeviceAddress(esp_bd_addr_t addr, esp_ble_addr_type_t type = BLE_ADDR_TYPE_RANDOM); - - void handleGAPEvent(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param); - void setMinPreferred(uint16_t); - void setMaxPreferred(uint16_t); - void setScanResponse(bool); - -private: - esp_ble_adv_data_t m_advData; - esp_ble_adv_data_t m_scanRespData; // Used for configuration of scan response data when m_scanResp is true - esp_ble_adv_params_t m_advParams; - std::vector m_serviceUUIDs; - bool m_customAdvData = false; // Are we using custom advertising data? - bool m_customScanResponseData = false; // Are we using custom scan response data? - FreeRTOS::Semaphore m_semaphoreSetAdv = FreeRTOS::Semaphore("startAdvert"); - bool m_scanResp = true; - -}; -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEADVERTISING_H_ */ diff --git a/libraries/BLE/src/BLEBeacon.cpp b/libraries/BLE/src/BLEBeacon.cpp deleted file mode 100644 index 9f3519b8..00000000 --- a/libraries/BLE/src/BLEBeacon.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* - * BLEBeacon.cpp - * - * Created on: Jan 4, 2018 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "BLEBeacon.h" -#include "esp32-hal-log.h" - -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) - - -BLEBeacon::BLEBeacon() { - m_beaconData.manufacturerId = 0x4c00; - m_beaconData.subType = 0x02; - m_beaconData.subTypeLength = 0x15; - m_beaconData.major = 0; - m_beaconData.minor = 0; - m_beaconData.signalPower = 0; - memset(m_beaconData.proximityUUID, 0, sizeof(m_beaconData.proximityUUID)); -} // BLEBeacon - -std::string BLEBeacon::getData() { - return std::string((char*) &m_beaconData, sizeof(m_beaconData)); -} // getData - -uint16_t BLEBeacon::getMajor() { - return m_beaconData.major; -} - -uint16_t BLEBeacon::getManufacturerId() { - return m_beaconData.manufacturerId; -} - -uint16_t BLEBeacon::getMinor() { - return m_beaconData.minor; -} - -BLEUUID BLEBeacon::getProximityUUID() { - return BLEUUID(m_beaconData.proximityUUID, 16, false); -} - -int8_t BLEBeacon::getSignalPower() { - return m_beaconData.signalPower; -} - -/** - * Set the raw data for the beacon record. - */ -void BLEBeacon::setData(std::string data) { - if (data.length() != sizeof(m_beaconData)) { - log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_beaconData)); - return; - } - memcpy(&m_beaconData, data.data(), sizeof(m_beaconData)); -} // setData - -void BLEBeacon::setMajor(uint16_t major) { - m_beaconData.major = ENDIAN_CHANGE_U16(major); -} // setMajor - -void BLEBeacon::setManufacturerId(uint16_t manufacturerId) { - m_beaconData.manufacturerId = ENDIAN_CHANGE_U16(manufacturerId); -} // setManufacturerId - -void BLEBeacon::setMinor(uint16_t minor) { - m_beaconData.minor = ENDIAN_CHANGE_U16(minor); -} // setMinior - -void BLEBeacon::setProximityUUID(BLEUUID uuid) { - uuid = uuid.to128(); - memcpy(m_beaconData.proximityUUID, uuid.getNative()->uuid.uuid128, 16); -} // setProximityUUID - -void BLEBeacon::setSignalPower(int8_t signalPower) { - m_beaconData.signalPower = signalPower; -} // setSignalPower - - -#endif diff --git a/libraries/BLE/src/BLEBeacon.h b/libraries/BLE/src/BLEBeacon.h deleted file mode 100644 index 277bd670..00000000 --- a/libraries/BLE/src/BLEBeacon.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * BLEBeacon2.h - * - * Created on: Jan 4, 2018 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEBEACON_H_ -#define COMPONENTS_CPP_UTILS_BLEBEACON_H_ -#include "BLEUUID.h" -/** - * @brief Representation of a beacon. - * See: - * * https://en.wikipedia.org/wiki/IBeacon - */ -class BLEBeacon { -private: - struct { - uint16_t manufacturerId; - uint8_t subType; - uint8_t subTypeLength; - uint8_t proximityUUID[16]; - uint16_t major; - uint16_t minor; - int8_t signalPower; - } __attribute__((packed)) m_beaconData; -public: - BLEBeacon(); - std::string getData(); - uint16_t getMajor(); - uint16_t getMinor(); - uint16_t getManufacturerId(); - BLEUUID getProximityUUID(); - int8_t getSignalPower(); - void setData(std::string data); - void setMajor(uint16_t major); - void setMinor(uint16_t minor); - void setManufacturerId(uint16_t manufacturerId); - void setProximityUUID(BLEUUID uuid); - void setSignalPower(int8_t signalPower); -}; // BLEBeacon - -#endif /* COMPONENTS_CPP_UTILS_BLEBEACON_H_ */ diff --git a/libraries/BLE/src/BLECharacteristic.cpp b/libraries/BLE/src/BLECharacteristic.cpp deleted file mode 100644 index a93c4637..00000000 --- a/libraries/BLE/src/BLECharacteristic.cpp +++ /dev/null @@ -1,803 +0,0 @@ -/* - * BLECharacteristic.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include -#include -#include "sdkconfig.h" -#include -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLEDevice.h" -#include "BLEUtils.h" -#include "BLE2902.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -#define NULL_HANDLE (0xffff) - -static BLECharacteristicCallbacks defaultCallback; //null-object-pattern - -/** - * @brief Construct a characteristic - * @param [in] uuid - UUID (const char*) for the characteristic. - * @param [in] properties - Properties for the characteristic. - */ -BLECharacteristic::BLECharacteristic(const char* uuid, uint32_t properties) : BLECharacteristic(BLEUUID(uuid), properties) { -} - -/** - * @brief Construct a characteristic - * @param [in] uuid - UUID for the characteristic. - * @param [in] properties - Properties for the characteristic. - */ -BLECharacteristic::BLECharacteristic(BLEUUID uuid, uint32_t properties) { - m_bleUUID = uuid; - m_handle = NULL_HANDLE; - m_properties = (esp_gatt_char_prop_t)0; - m_pCallbacks = &defaultCallback; - - setBroadcastProperty((properties & PROPERTY_BROADCAST) != 0); - setReadProperty((properties & PROPERTY_READ) != 0); - setWriteProperty((properties & PROPERTY_WRITE) != 0); - setNotifyProperty((properties & PROPERTY_NOTIFY) != 0); - setIndicateProperty((properties & PROPERTY_INDICATE) != 0); - setWriteNoResponseProperty((properties & PROPERTY_WRITE_NR) != 0); -} // BLECharacteristic - -/** - * @brief Destructor. - */ -BLECharacteristic::~BLECharacteristic() { - //free(m_value.attr_value); // Release the storage for the value. -} // ~BLECharacteristic - - -/** - * @brief Associate a descriptor with this characteristic. - * @param [in] pDescriptor - * @return N/A. - */ -void BLECharacteristic::addDescriptor(BLEDescriptor* pDescriptor) { - log_v(">> addDescriptor(): Adding %s to %s", pDescriptor->toString().c_str(), toString().c_str()); - m_descriptorMap.setByUUID(pDescriptor->getUUID(), pDescriptor); - log_v("<< addDescriptor()"); -} // addDescriptor - - -/** - * @brief Register a new characteristic with the ESP runtime. - * @param [in] pService The service with which to associate this characteristic. - */ -void BLECharacteristic::executeCreate(BLEService* pService) { - log_v(">> executeCreate()"); - - if (m_handle != NULL_HANDLE) { - log_e("Characteristic already has a handle."); - return; - } - - m_pService = pService; // Save the service to which this characteristic belongs. - - log_d("Registering characteristic (esp_ble_gatts_add_char): uuid: %s, service: %s", - getUUID().toString().c_str(), - m_pService->toString().c_str()); - - esp_attr_control_t control; - control.auto_rsp = ESP_GATT_RSP_BY_APP; - - m_semaphoreCreateEvt.take("executeCreate"); - esp_err_t errRc = ::esp_ble_gatts_add_char( - m_pService->getHandle(), - getUUID().getNative(), - static_cast(m_permissions), - getProperties(), - nullptr, - &control); // Whether to auto respond or not. - - if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_add_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - m_semaphoreCreateEvt.wait("executeCreate"); - - BLEDescriptor* pDescriptor = m_descriptorMap.getFirst(); - while (pDescriptor != nullptr) { - pDescriptor->executeCreate(this); - pDescriptor = m_descriptorMap.getNext(); - } // End while - - log_v("<< executeCreate"); -} // executeCreate - - -/** - * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. - * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. - * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. - */ -BLEDescriptor* BLECharacteristic::getDescriptorByUUID(const char* descriptorUUID) { - return m_descriptorMap.getByUUID(BLEUUID(descriptorUUID)); -} // getDescriptorByUUID - - -/** - * @brief Return the BLE Descriptor for the given UUID if associated with this characteristic. - * @param [in] descriptorUUID The UUID of the descriptor that we wish to retrieve. - * @return The BLE Descriptor. If no such descriptor is associated with the characteristic, nullptr is returned. - */ -BLEDescriptor* BLECharacteristic::getDescriptorByUUID(BLEUUID descriptorUUID) { - return m_descriptorMap.getByUUID(descriptorUUID); -} // getDescriptorByUUID - - -/** - * @brief Get the handle of the characteristic. - * @return The handle of the characteristic. - */ -uint16_t BLECharacteristic::getHandle() { - return m_handle; -} // getHandle - -void BLECharacteristic::setAccessPermissions(esp_gatt_perm_t perm) { - m_permissions = perm; -} - -esp_gatt_char_prop_t BLECharacteristic::getProperties() { - return m_properties; -} // getProperties - - -/** - * @brief Get the service associated with this characteristic. - */ -BLEService* BLECharacteristic::getService() { - return m_pService; -} // getService - - -/** - * @brief Get the UUID of the characteristic. - * @return The UUID of the characteristic. - */ -BLEUUID BLECharacteristic::getUUID() { - return m_bleUUID; -} // getUUID - - -/** - * @brief Retrieve the current value of the characteristic. - * @return A pointer to storage containing the current characteristic value. - */ -std::string BLECharacteristic::getValue() { - return m_value.getValue(); -} // getValue - -/** - * @brief Retrieve the current raw data of the characteristic. - * @return A pointer to storage containing the current characteristic data. - */ -uint8_t* BLECharacteristic::getData() { - return m_value.getData(); -} // getData - - -/** - * Handle a GATT server event. - */ -void BLECharacteristic::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - log_v(">> handleGATTServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); - - switch(event) { - // Events handled: - // - // ESP_GATTS_ADD_CHAR_EVT - // ESP_GATTS_CONF_EVT - // ESP_GATTS_CONNECT_EVT - // ESP_GATTS_DISCONNECT_EVT - // ESP_GATTS_EXEC_WRITE_EVT - // ESP_GATTS_READ_EVT - // ESP_GATTS_WRITE_EVT - - // - // ESP_GATTS_EXEC_WRITE_EVT - // When we receive this event it is an indication that a previous write long needs to be committed. - // - // exec_write: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint8_t exec_write_flag - Either ESP_GATT_PREP_WRITE_EXEC or ESP_GATT_PREP_WRITE_CANCEL - // - case ESP_GATTS_EXEC_WRITE_EVT: { - if(m_writeEvt){ - m_writeEvt = false; - if (param->exec_write.exec_write_flag == ESP_GATT_PREP_WRITE_EXEC) { - m_value.commit(); - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } else { - m_value.cancel(); - } - // ??? - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, ESP_GATT_OK, nullptr); - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } - break; - } // ESP_GATTS_EXEC_WRITE_EVT - - - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - case ESP_GATTS_ADD_CHAR_EVT: { - if (getHandle() == param->add_char.attr_handle) { - // we have created characteristic, now we can create descriptors - // BLEDescriptor* pDescriptor = m_descriptorMap.getFirst(); - // while (pDescriptor != nullptr) { - // pDescriptor->executeCreate(this); - // pDescriptor = m_descriptorMap.getNext(); - // } // End while - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t *value - // - case ESP_GATTS_WRITE_EVT: { -// We check if this write request is for us by comparing the handles in the event. If it is for us -// we save the new value. Next we look at the need_rsp flag which indicates whether or not we need -// to send a response. If we do, then we formulate a response and send it. - if (param->write.handle == m_handle) { - if (param->write.is_prep) { - m_value.addPart(param->write.value, param->write.len); - m_writeEvt = true; - } else { - setValue(param->write.value, param->write.len); - } - - log_d(" - Response to write event: New value: handle: %.2x, uuid: %s", - getHandle(), getUUID().toString().c_str()); - - char* pHexData = BLEUtils::buildHexData(nullptr, param->write.value, param->write.len); - log_d(" - Data: length: %d, data: %s", param->write.len, pHexData); - free(pHexData); - - if (param->write.need_rsp) { - esp_gatt_rsp_t rsp; - - rsp.attr_value.len = param->write.len; - rsp.attr_value.handle = m_handle; - rsp.attr_value.offset = param->write.offset; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - memcpy(rsp.attr_value.value, param->write.value, param->write.len); - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, - param->write.conn_id, - param->write.trans_id, ESP_GATT_OK, &rsp); - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // Response needed - - if (param->write.is_prep != true) { - m_pCallbacks->onWrite(this); // Invoke the onWrite callback handler. - } - } // Match on handles. - break; - } // ESP_GATTS_WRITE_EVT - - - // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - if (param->read.handle == m_handle) { - - - -// Here's an interesting thing. The read request has the option of saying whether we need a response -// or not. What would it "mean" to receive a read request and NOT send a response back? That feels like -// a very strange read. -// -// We have to handle the case where the data we wish to send back to the client is greater than the maximum -// packet size of 22 bytes. In this case, we become responsible for chunking the data into units of 22 bytes. -// The apparent algorithm is as follows: -// -// If the is_long flag is set then this is a follow on from an original read and we will already have sent at least 22 bytes. -// If the is_long flag is not set then we need to check how much data we are going to send. If we are sending LESS than -// 22 bytes, then we "just" send it and thats the end of the story. -// If we are sending 22 bytes exactly, we just send it BUT we will get a follow on request. -// If we are sending more than 22 bytes, we send the first 22 bytes and we will get a follow on request. -// Because of follow on request processing, we need to maintain an offset of how much data we have already sent -// so that when a follow on request arrives, we know where to start in the data to send the next sequence. -// Note that the indication that the client will send a follow on request is that we sent exactly 22 bytes as a response. -// If our payload is divisible by 22 then the last response will be a response of 0 bytes in length. -// -// The following code has deliberately not been factored to make it fewer statements because this would cloud the -// the logic flow comprehension. -// - - // get mtu for peer device that we are sending read request to - uint16_t maxOffset = getService()->getServer()->getPeerMTU(param->read.conn_id) - 1; - log_d("mtu value: %d", maxOffset); - if (param->read.need_rsp) { - log_d("Sending a response (esp_ble_gatts_send_response)"); - esp_gatt_rsp_t rsp; - - if (param->read.is_long) { - std::string value = m_value.getValue(); - - if (value.length() - m_value.getReadOffset() < maxOffset) { - // This is the last in the chain - rsp.attr_value.len = value.length() - m_value.getReadOffset(); - rsp.attr_value.offset = m_value.getReadOffset(); - memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); - m_value.setReadOffset(0); - } else { - // There will be more to come. - rsp.attr_value.len = maxOffset; - rsp.attr_value.offset = m_value.getReadOffset(); - memcpy(rsp.attr_value.value, value.data() + rsp.attr_value.offset, rsp.attr_value.len); - m_value.setReadOffset(rsp.attr_value.offset + maxOffset); - } - } else { // read.is_long == false - - // If is.long is false then this is the first (or only) request to read data, so invoke the callback - // Invoke the read callback. - m_pCallbacks->onRead(this); - - std::string value = m_value.getValue(); - - if (value.length() + 1 > maxOffset) { - // Too big for a single shot entry. - m_value.setReadOffset(maxOffset); - rsp.attr_value.len = maxOffset; - rsp.attr_value.offset = 0; - memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); - } else { - // Will fit in a single packet with no callbacks required. - rsp.attr_value.len = value.length(); - rsp.attr_value.offset = 0; - memcpy(rsp.attr_value.value, value.data(), rsp.attr_value.len); - } - } - rsp.attr_value.handle = param->read.handle; - rsp.attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE; - - char *pHexData = BLEUtils::buildHexData(nullptr, rsp.attr_value.value, rsp.attr_value.len); - log_d(" - Data: length=%d, data=%s, offset=%d", rsp.attr_value.len, pHexData, rsp.attr_value.offset); - free(pHexData); - - esp_err_t errRc = ::esp_ble_gatts_send_response( - gatts_if, param->read.conn_id, - param->read.trans_id, - ESP_GATT_OK, - &rsp); - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_send_response: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - } // Response needed - } // Handle matches this characteristic. - break; - } // ESP_GATTS_READ_EVT - - - // ESP_GATTS_CONF_EVT - // - // conf: - // - esp_gatt_status_t status – The status code. - // - uint16_t conn_id – The connection used. - // - case ESP_GATTS_CONF_EVT: { - // log_d("m_handle = %d, conf->handle = %d", m_handle, param->conf.handle); - if(param->conf.conn_id == getService()->getServer()->getConnId()) // && param->conf.handle == m_handle) // bug in esp-idf and not implemented in arduino yet - m_semaphoreConfEvt.give(param->conf.status); - break; - } - - case ESP_GATTS_CONNECT_EVT: { - break; - } - - case ESP_GATTS_DISCONNECT_EVT: { - m_semaphoreConfEvt.give(); - break; - } - - default: { - break; - } // default - - } // switch event - - // Give each of the descriptors associated with this characteristic the opportunity to handle the - // event. - - m_descriptorMap.handleGATTServerEvent(event, gatts_if, param); - log_v("<< handleGATTServerEvent"); -} // handleGATTServerEvent - - -/** - * @brief Send an indication. - * An indication is a transmission of up to the first 20 bytes of the characteristic value. An indication - * will block waiting a positive confirmation from the client. - * @return N/A - */ -void BLECharacteristic::indicate() { - - log_v(">> indicate: length: %d", m_value.getValue().length()); - notify(false); - log_v("<< indicate"); -} // indicate - - -/** - * @brief Send a notify. - * A notification is a transmission of up to the first 20 bytes of the characteristic value. An notification - * will not block; it is a fire and forget. - * @return N/A. - */ -void BLECharacteristic::notify(bool is_notification) { - log_v(">> notify: length: %d", m_value.getValue().length()); - - assert(getService() != nullptr); - assert(getService()->getServer() != nullptr); - - m_pCallbacks->onNotify(this); // Invoke the notify callback. - - GeneralUtils::hexDump((uint8_t*)m_value.getValue().data(), m_value.getValue().length()); - - if (getService()->getServer()->getConnectedCount() == 0) { - log_v("<< notify: No connected clients."); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NO_CLIENT, 0); - return; - } - - // Test to see if we have a 0x2902 descriptor. If we do, then check to see if notification is enabled - // and, if not, prevent the notification. - - BLE2902 *p2902 = (BLE2902*)getDescriptorByUUID((uint16_t)0x2902); - if(is_notification) { - if (p2902 != nullptr && !p2902->getNotifications()) { - log_v("<< notifications disabled; ignoring"); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_NOTIFY_DISABLED, 0); // Invoke the notify callback. - return; - } - } - else{ - if (p2902 != nullptr && !p2902->getIndications()) { - log_v("<< indications disabled; ignoring"); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_DISABLED, 0); // Invoke the notify callback. - return; - } - } - for (auto &myPair : getService()->getServer()->getPeerDevices(false)) { - uint16_t _mtu = (myPair.second.mtu); - if (m_value.getValue().length() > _mtu - 3) { - log_w("- Truncating to %d bytes (maximum notify size)", _mtu - 3); - } - - size_t length = m_value.getValue().length(); - if(!is_notification) // is indication - m_semaphoreConfEvt.take("indicate"); - esp_err_t errRc = ::esp_ble_gatts_send_indicate( - getService()->getServer()->getGattsIf(), - myPair.first, - getHandle(), length, (uint8_t*)m_value.getValue().data(), !is_notification); // The need_confirm = false makes this a notify. - if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_send_ %s: rc=%d %s",is_notification?"notify":"indicate", errRc, GeneralUtils::errorToString(errRc)); - m_semaphoreConfEvt.give(); - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_GATT, errRc); // Invoke the notify callback. - return; - } - if(!is_notification){ // is indication - if(!m_semaphoreConfEvt.timedWait("indicate", indicationTimeout)){ - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_TIMEOUT, 0); // Invoke the notify callback. - } else { - auto code = (esp_gatt_status_t) m_semaphoreConfEvt.value(); - if(code == ESP_GATT_OK) { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_INDICATE, code); // Invoke the notify callback. - } else { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::ERROR_INDICATE_FAILURE, code); - } - } - } else { - m_pCallbacks->onStatus(this, BLECharacteristicCallbacks::Status::SUCCESS_NOTIFY, 0); // Invoke the notify callback. - } - } - log_v("<< notify"); -} // Notify - - -/** - * @brief Set the permission to broadcast. - * A characteristics has properties associated with it which define what it is capable of doing. - * One of these is the broadcast flag. - * @param [in] value The flag value of the property. - * @return N/A - */ -void BLECharacteristic::setBroadcastProperty(bool value) { - //log_d("setBroadcastProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_BROADCAST); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_BROADCAST); - } -} // setBroadcastProperty - - -/** - * @brief Set the callback handlers for this characteristic. - * @param [in] pCallbacks An instance of a callbacks structure used to define any callbacks for the characteristic. - */ -void BLECharacteristic::setCallbacks(BLECharacteristicCallbacks* pCallbacks) { - log_v(">> setCallbacks: 0x%x", (uint32_t)pCallbacks); - if (pCallbacks != nullptr){ - m_pCallbacks = pCallbacks; - } else { - m_pCallbacks = &defaultCallback; - } - log_v("<< setCallbacks"); -} // setCallbacks - - -/** - * @brief Set the BLE handle associated with this characteristic. - * A user program will request that a characteristic be created against a service. When the characteristic has been - * registered, the service will be given a "handle" that it knows the characteristic as. This handle is unique to the - * server/service but it is told to the service, not the characteristic associated with the service. This internally - * exposed function can be invoked by the service against this model of the characteristic to allow the characteristic - * to learn its own handle. Once the characteristic knows its own handle, it will be able to see incoming GATT events - * that will be propagated down to it which contain a handle value and now know that the event is destined for it. - * @param [in] handle The handle associated with this characteristic. - */ -void BLECharacteristic::setHandle(uint16_t handle) { - log_v(">> setHandle: handle=0x%.2x, characteristic uuid=%s", handle, getUUID().toString().c_str()); - m_handle = handle; - log_v("<< setHandle"); -} // setHandle - - -/** - * @brief Set the Indicate property value. - * @param [in] value Set to true if we are to allow indicate messages. - */ -void BLECharacteristic::setIndicateProperty(bool value) { - //log_d("setIndicateProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_INDICATE); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_INDICATE); - } -} // setIndicateProperty - - -/** - * @brief Set the Notify property value. - * @param [in] value Set to true if we are to allow notification messages. - */ -void BLECharacteristic::setNotifyProperty(bool value) { - //log_d("setNotifyProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_NOTIFY); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_NOTIFY); - } -} // setNotifyProperty - - -/** - * @brief Set the Read property value. - * @param [in] value Set to true if we are to allow reads. - */ -void BLECharacteristic::setReadProperty(bool value) { - //log_d("setReadProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_READ); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_READ); - } -} // setReadProperty - - -/** - * @brief Set the value of the characteristic. - * @param [in] data The data to set for the characteristic. - * @param [in] length The length of the data in bytes. - */ -void BLECharacteristic::setValue(uint8_t* data, size_t length) { - char* pHex = BLEUtils::buildHexData(nullptr, data, length); - log_v(">> setValue: length=%d, data=%s, characteristic UUID=%s", length, pHex, getUUID().toString().c_str()); - free(pHex); - if (length > ESP_GATT_MAX_ATTR_LEN) { - log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); - return; - } - m_semaphoreSetValue.take(); - m_value.setValue(data, length); - m_semaphoreSetValue.give(); - log_v("<< setValue"); -} // setValue - - -/** - * @brief Set the value of the characteristic from string data. - * We set the value of the characteristic from the bytes contained in the - * string. - * @param [in] Set the value of the characteristic. - * @return N/A. - */ -void BLECharacteristic::setValue(std::string value) { - setValue((uint8_t*)(value.data()), value.length()); -} // setValue - -void BLECharacteristic::setValue(uint16_t& data16) { - uint8_t temp[2]; - temp[0] = data16; - temp[1] = data16 >> 8; - setValue(temp, 2); -} // setValue - -void BLECharacteristic::setValue(uint32_t& data32) { - uint8_t temp[4]; - temp[0] = data32; - temp[1] = data32 >> 8; - temp[2] = data32 >> 16; - temp[3] = data32 >> 24; - setValue(temp, 4); -} // setValue - -void BLECharacteristic::setValue(int& data32) { - uint8_t temp[4]; - temp[0] = data32; - temp[1] = data32 >> 8; - temp[2] = data32 >> 16; - temp[3] = data32 >> 24; - setValue(temp, 4); -} // setValue - -void BLECharacteristic::setValue(float& data32) { - float temp = data32; - setValue((uint8_t*)&temp, 4); -} // setValue - -void BLECharacteristic::setValue(double& data64) { - double temp = data64; - setValue((uint8_t*)&temp, 8); -} // setValue - - -/** - * @brief Set the Write No Response property value. - * @param [in] value Set to true if we are to allow writes with no response. - */ -void BLECharacteristic::setWriteNoResponseProperty(bool value) { - //log_d("setWriteNoResponseProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE_NR); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE_NR); - } -} // setWriteNoResponseProperty - - -/** - * @brief Set the Write property value. - * @param [in] value Set to true if we are to allow writes. - */ -void BLECharacteristic::setWriteProperty(bool value) { - //log_d("setWriteProperty(%d)", value); - if (value) { - m_properties = (esp_gatt_char_prop_t)(m_properties | ESP_GATT_CHAR_PROP_BIT_WRITE); - } else { - m_properties = (esp_gatt_char_prop_t)(m_properties & ~ESP_GATT_CHAR_PROP_BIT_WRITE); - } -} // setWriteProperty - - -/** - * @brief Return a string representation of the characteristic. - * @return A string representation of the characteristic. - */ -std::string BLECharacteristic::toString() { - std::string res = "UUID: " + m_bleUUID.toString() + ", handle : 0x"; - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", m_handle); - res += hex; - res += " "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_READ) res += "Read "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE) res += "Write "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) res += "WriteNoResponse "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_BROADCAST) res += "Broadcast "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_NOTIFY) res += "Notify "; - if (m_properties & ESP_GATT_CHAR_PROP_BIT_INDICATE) res += "Indicate "; - return res; -} // toString - - -BLECharacteristicCallbacks::~BLECharacteristicCallbacks() {} - - -/** - * @brief Callback function to support a read request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onRead(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onRead: default"); - log_d("BLECharacteristicCallbacks", "<< onRead"); -} // onRead - - -/** - * @brief Callback function to support a write request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onWrite(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onWrite: default"); - log_d("BLECharacteristicCallbacks", "<< onWrite"); -} // onWrite - - -/** - * @brief Callback function to support a Notify request. - * @param [in] pCharacteristic The characteristic that is the source of the event. - */ -void BLECharacteristicCallbacks::onNotify(BLECharacteristic* pCharacteristic) { - log_d("BLECharacteristicCallbacks", ">> onNotify: default"); - log_d("BLECharacteristicCallbacks", "<< onNotify"); -} // onNotify - - -/** - * @brief Callback function to support a Notify/Indicate Status report. - * @param [in] pCharacteristic The characteristic that is the source of the event. - * @param [in] s Status of the notification/indication - * @param [in] code Additional code of underlying errors - */ -void BLECharacteristicCallbacks::onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code) { - log_d("BLECharacteristicCallbacks", ">> onStatus: default"); - log_d("BLECharacteristicCallbacks", "<< onStatus"); -} // onStatus - - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLECharacteristic.h b/libraries/BLE/src/BLECharacteristic.h deleted file mode 100644 index 3db891eb..00000000 --- a/libraries/BLE/src/BLECharacteristic.h +++ /dev/null @@ -1,154 +0,0 @@ -/* - * BLECharacteristic.h - * - * Created on: Jun 22, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ -#define COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "BLEUUID.h" -#include -#include -#include "BLEDescriptor.h" -#include "BLEValue.h" -#include "RTOS.h" - -class BLEService; -class BLEDescriptor; -class BLECharacteristicCallbacks; - -/** - * @brief A management structure for %BLE descriptors. - */ -class BLEDescriptorMap { -public: - void setByUUID(const char* uuid, BLEDescriptor* pDescriptor); - void setByUUID(BLEUUID uuid, BLEDescriptor* pDescriptor); - void setByHandle(uint16_t handle, BLEDescriptor* pDescriptor); - BLEDescriptor* getByUUID(const char* uuid); - BLEDescriptor* getByUUID(BLEUUID uuid); - BLEDescriptor* getByHandle(uint16_t handle); - std::string toString(); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); - BLEDescriptor* getFirst(); - BLEDescriptor* getNext(); -private: - std::map m_uuidMap; - std::map m_handleMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE Characteristic. - * - * A BLE Characteristic is an identified value container that manages a value. It is exposed by a BLE server and - * can be read and written to by a %BLE client. - */ -class BLECharacteristic { -public: - BLECharacteristic(const char* uuid, uint32_t properties = 0); - BLECharacteristic(BLEUUID uuid, uint32_t properties = 0); - virtual ~BLECharacteristic(); - - void addDescriptor(BLEDescriptor* pDescriptor); - BLEDescriptor* getDescriptorByUUID(const char* descriptorUUID); - BLEDescriptor* getDescriptorByUUID(BLEUUID descriptorUUID); - BLEUUID getUUID(); - std::string getValue(); - uint8_t* getData(); - - void indicate(); - void notify(bool is_notification = true); - void setBroadcastProperty(bool value); - void setCallbacks(BLECharacteristicCallbacks* pCallbacks); - void setIndicateProperty(bool value); - void setNotifyProperty(bool value); - void setReadProperty(bool value); - void setValue(uint8_t* data, size_t size); - void setValue(std::string value); - void setValue(uint16_t& data16); - void setValue(uint32_t& data32); - void setValue(int& data32); - void setValue(float& data32); - void setValue(double& data64); - void setWriteProperty(bool value); - void setWriteNoResponseProperty(bool value); - std::string toString(); - uint16_t getHandle(); - void setAccessPermissions(esp_gatt_perm_t perm); - - static const uint32_t PROPERTY_READ = 1<<0; - static const uint32_t PROPERTY_WRITE = 1<<1; - static const uint32_t PROPERTY_NOTIFY = 1<<2; - static const uint32_t PROPERTY_BROADCAST = 1<<3; - static const uint32_t PROPERTY_INDICATE = 1<<4; - static const uint32_t PROPERTY_WRITE_NR = 1<<5; - - static const uint32_t indicationTimeout = 1000; - -private: - - friend class BLEServer; - friend class BLEService; - friend class BLEDescriptor; - friend class BLECharacteristicMap; - - BLEUUID m_bleUUID; - BLEDescriptorMap m_descriptorMap; - uint16_t m_handle; - esp_gatt_char_prop_t m_properties; - BLECharacteristicCallbacks* m_pCallbacks; - BLEService* m_pService; - BLEValue m_value; - esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; - bool m_writeEvt = false; // If we have started a long write, this tells the commit code that we were the target - - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - void executeCreate(BLEService* pService); - esp_gatt_char_prop_t getProperties(); - BLEService* getService(); - void setHandle(uint16_t handle); - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - FreeRTOS::Semaphore m_semaphoreConfEvt = FreeRTOS::Semaphore("ConfEvt"); - FreeRTOS::Semaphore m_semaphoreSetValue = FreeRTOS::Semaphore("SetValue"); -}; // BLECharacteristic - - -/** - * @brief Callbacks that can be associated with a %BLE characteristic to inform of events. - * - * When a server application creates a %BLE characteristic, we may wish to be informed when there is either - * a read or write request to the characteristic's value. An application can register a - * sub-classed instance of this class and will be notified when such an event happens. - */ -class BLECharacteristicCallbacks { -public: - typedef enum { - SUCCESS_INDICATE, - SUCCESS_NOTIFY, - ERROR_INDICATE_DISABLED, - ERROR_NOTIFY_DISABLED, - ERROR_GATT, - ERROR_NO_CLIENT, - ERROR_INDICATE_TIMEOUT, - ERROR_INDICATE_FAILURE - }Status; - - virtual ~BLECharacteristicCallbacks(); - virtual void onRead(BLECharacteristic* pCharacteristic); - virtual void onWrite(BLECharacteristic* pCharacteristic); - virtual void onNotify(BLECharacteristic* pCharacteristic); - virtual void onStatus(BLECharacteristic* pCharacteristic, Status s, uint32_t code); -}; -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLECHARACTERISTIC_H_ */ diff --git a/libraries/BLE/src/BLECharacteristicMap.cpp b/libraries/BLE/src/BLECharacteristicMap.cpp deleted file mode 100644 index 06aeb5bb..00000000 --- a/libraries/BLE/src/BLECharacteristicMap.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/* - * BLECharacteristicMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "BLEService.h" -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - - -/** - * @brief Return the characteristic by handle. - * @param [in] handle The handle to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Return the characteristic by UUID. - * @param [in] UUID The UUID to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - - -/** - * @brief Return the characteristic by UUID. - * @param [in] UUID The UUID to look up the characteristic. - * @return The characteristic. - */ -BLECharacteristic* BLECharacteristicMap::getByUUID(BLEUUID uuid) { - for (auto &myPair : m_uuidMap) { - if (myPair.first->getUUID().equals(uuid)) { - return myPair.first; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Get the first characteristic in the map. - * @return The first characteristic in the map. - */ -BLECharacteristic* BLECharacteristicMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) return nullptr; - BLECharacteristic* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getFirst - - -/** - * @brief Get the next characteristic in the map. - * @return The next characteristic in the map. - */ -BLECharacteristic* BLECharacteristicMap::getNext() { - if (m_iterator == m_uuidMap.end()) return nullptr; - BLECharacteristic* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getNext - - -/** - * @brief Pass the GATT server event onwards to each of the characteristics found in the mapping - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLECharacteristicMap::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { - // Invoke the handler for every Service we have. - for (auto& myPair : m_uuidMap) { - myPair.first->handleGATTServerEvent(event, gatts_if, param); - } -} // handleGATTServerEvent - - -/** - * @brief Set the characteristic by handle. - * @param [in] handle The handle of the characteristic. - * @param [in] characteristic The characteristic to cache. - * @return N/A. - */ -void BLECharacteristicMap::setByHandle(uint16_t handle, BLECharacteristic* characteristic) { - m_handleMap.insert(std::pair(handle, characteristic)); -} // setByHandle - - -/** - * @brief Set the characteristic by UUID. - * @param [in] uuid The uuid of the characteristic. - * @param [in] characteristic The characteristic to cache. - * @return N/A. - */ -void BLECharacteristicMap::setByUUID(BLECharacteristic* pCharacteristic, BLEUUID uuid) { - m_uuidMap.insert(std::pair(pCharacteristic, uuid.toString())); -} // setByUUID - - -/** - * @brief Return a string representation of the characteristic map. - * @return A string representation of the characteristic map. - */ -std::string BLECharacteristicMap::toString() { - std::string res; - int count = 0; - char hex[5]; - for (auto &myPair: m_uuidMap) { - if (count > 0) {res += "\n";} - snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); - count++; - res += "handle: 0x"; - res += hex; - res += ", uuid: " + myPair.first->getUUID().toString(); - } - return res; -} // toString - - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEClient.cpp b/libraries/BLE/src/BLEClient.cpp deleted file mode 100644 index 3895e1fb..00000000 --- a/libraries/BLE/src/BLEClient.cpp +++ /dev/null @@ -1,538 +0,0 @@ -/* - * BLEDevice.cpp - * - * Created on: Mar 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include -#include -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEService.h" -#include "GeneralUtils.h" -#include -#include -#include -#include "BLEDevice.h" -#include "esp32-hal-log.h" - -/* - * Design - * ------ - * When we perform a searchService() requests, we are asking the BLE server to return each of the services - * that it exposes. For each service, we received an ESP_GATTC_SEARCH_RES_EVT event which contains details - * of the exposed service including its UUID. - * - * The objects we will invent for a BLEClient will be as follows: - * * BLERemoteService - A model of a remote service. - * * BLERemoteCharacteristic - A model of a remote characteristic - * * BLERemoteDescriptor - A model of a remote descriptor. - * - * Since there is a hierarchical relationship here, we will have the idea that from a BLERemoteService will own - * zero or more remote characteristics and a BLERemoteCharacteristic will own zero or more remote BLEDescriptors. - * - * We will assume that a BLERemoteService contains a map that maps BLEUUIDs to the set of owned characteristics - * and that a BLECharacteristic contains a map that maps BLEUUIDs to the set of owned descriptors. - * - * - */ - -BLEClient::BLEClient() { - m_pClientCallbacks = nullptr; - m_conn_id = ESP_GATT_IF_NONE; - m_gattc_if = ESP_GATT_IF_NONE; - m_haveServices = false; - m_isConnected = false; // Initially, we are flagged as not connected. -} // BLEClient - - -/** - * @brief Destructor. - */ -BLEClient::~BLEClient() { - // We may have allocated service references associated with this client. Before we are finished - // with the client, we must release resources. - for (auto &myPair : m_servicesMap) { - delete myPair.second; - } - m_servicesMap.clear(); -} // ~BLEClient - - -/** - * @brief Clear any existing services. - * - */ -void BLEClient::clearServices() { - log_v(">> clearServices"); - // Delete all the services. - for (auto &myPair : m_servicesMap) { - delete myPair.second; - } - m_servicesMap.clear(); - m_haveServices = false; - log_v("<< clearServices"); -} // clearServices - -/** - * Add overloaded function to ease connect to peer device with not public address - */ -bool BLEClient::connect(BLEAdvertisedDevice* device) { - BLEAddress address = device->getAddress(); - esp_ble_addr_type_t type = device->getAddressType(); - return connect(address, type); -} - -/** - * @brief Connect to the partner (BLE Server). - * @param [in] address The address of the partner. - * @return True on success. - */ -bool BLEClient::connect(BLEAddress address, esp_ble_addr_type_t type) { - log_v(">> connect(%s)", address.toString().c_str()); - -// We need the connection handle that we get from registering the application. We register the app -// and then block on its completion. When the event has arrived, we will have the handle. - m_appId = BLEDevice::m_appId++; - BLEDevice::addPeerDevice(this, true, m_appId); - m_semaphoreRegEvt.take("connect"); - - // clearServices(); // we dont need to delete services since every client is unique? - esp_err_t errRc = ::esp_ble_gattc_app_register(m_appId); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_app_register: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - BLEDevice::removePeerDevice(m_appId, true); - return false; - } - - m_semaphoreRegEvt.wait("connect"); - - m_peerAddress = address; - - // Perform the open connection request against the target BLE Server. - m_semaphoreOpenEvt.take("connect"); - errRc = ::esp_ble_gattc_open( - m_gattc_if, - *getPeerAddress().getNative(), // address - type, // Note: This was added on 2018-04-03 when the latest ESP-IDF was detected to have changed the signature. - 1 // direct connection <-- maybe needs to be changed in case of direct indirect connection??? - ); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - BLEDevice::removePeerDevice(m_appId, true); - return false; - } - - uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. - log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); - return rc == ESP_GATT_OK; -} // connect - - -/** - * @brief Disconnect from the peer. - * @return N/A. - */ -void BLEClient::disconnect() { - log_v(">> disconnect()"); - esp_err_t errRc = ::esp_ble_gattc_close(getGattcIf(), getConnId()); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_close: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - log_v("<< disconnect()"); -} // disconnect - - -/** - * @brief Handle GATT Client events - */ -void BLEClient::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - - log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", - gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); - - // Execute handler code based on the type of event received. - switch(event) { - - case ESP_GATTC_SRVC_CHG_EVT: - log_i("SERVICE CHANGED"); - break; - - case ESP_GATTC_CLOSE_EVT: { - // esp_ble_gattc_app_unregister(m_appId); - // BLEDevice::removePeerDevice(m_gattc_if, true); - break; - } - - // - // ESP_GATTC_DISCONNECT_EVT - // - // disconnect: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_DISCONNECT_EVT: { - if (evtParam->disconnect.conn_id != getConnId()) break; - // If we receive a disconnect event, set the class flag that indicates that we are - // no longer connected. - if (m_isConnected && m_pClientCallbacks != nullptr) { - m_pClientCallbacks->onDisconnect(this); - } - m_isConnected = false; - esp_ble_gattc_app_unregister(m_gattc_if); - m_semaphoreOpenEvt.give(ESP_GATT_IF_NONE); - m_semaphoreRssiCmplEvt.give(); - m_semaphoreSearchCmplEvt.give(1); - BLEDevice::removePeerDevice(m_appId, true); - break; - } // ESP_GATTC_DISCONNECT_EVT - - // - // ESP_GATTC_OPEN_EVT - // - // open: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - case ESP_GATTC_OPEN_EVT: { - m_conn_id = evtParam->open.conn_id; - if (evtParam->open.status == ESP_GATT_OK) { - m_isConnected = true; // Flag us as connected. - if (m_pClientCallbacks != nullptr) { - m_pClientCallbacks->onConnect(this); - } - } else { - log_e("Failed to connect, status=%s", GeneralUtils::errorToString(evtParam->open.status)); - } - m_semaphoreOpenEvt.give(evtParam->open.status); - break; - } // ESP_GATTC_OPEN_EVT - - - // - // ESP_GATTC_REG_EVT - // - // reg: - // esp_gatt_status_t status - // uint16_t app_id - // - case ESP_GATTC_REG_EVT: { - m_gattc_if = gattc_if; - m_semaphoreRegEvt.give(); - break; - } // ESP_GATTC_REG_EVT - - case ESP_GATTC_CFG_MTU_EVT: - if (evtParam->cfg_mtu.conn_id != getConnId()) break; - if(evtParam->cfg_mtu.status != ESP_GATT_OK) { - log_e("Config mtu failed"); - } - m_mtu = evtParam->cfg_mtu.mtu; - break; - - case ESP_GATTC_CONNECT_EVT: { - if (evtParam->connect.conn_id != getConnId()) break; - BLEDevice::updatePeerDevice(this, true, m_appId); - esp_err_t errRc = esp_ble_gattc_send_mtu_req(gattc_if, evtParam->connect.conn_id); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_send_mtu_req: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityLevel){ - esp_ble_set_encryption(evtParam->connect.remote_bda, BLEDevice::m_securityLevel); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - } // ESP_GATTC_CONNECT_EVT - - // - // ESP_GATTC_SEARCH_CMPL_EVT - // - // search_cmpl: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - case ESP_GATTC_SEARCH_CMPL_EVT: { - if (evtParam->search_cmpl.conn_id != getConnId()) break; - esp_ble_gattc_cb_param_t* p_data = (esp_ble_gattc_cb_param_t*)evtParam; - if (p_data->search_cmpl.status != ESP_GATT_OK){ - log_e("search service failed, error status = %x", p_data->search_cmpl.status); - break; - } -#ifndef ARDUINO_ARCH_ESP32 -// commented out just for now to keep backward compatibility - // if(p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_REMOTE_DEVICE) { - // log_i("Get service information from remote device"); - // } else if (p_data->search_cmpl.searched_service_source == ESP_GATT_SERVICE_FROM_NVS_FLASH) { - // log_i("Get service information from flash"); - // } else { - // log_i("unknown service source"); - // } -#endif - m_semaphoreSearchCmplEvt.give(0); - break; - } // ESP_GATTC_SEARCH_CMPL_EVT - - - // - // ESP_GATTC_SEARCH_RES_EVT - // - // search_res: - // - uint16_t conn_id - // - uint16_t start_handle - // - uint16_t end_handle - // - esp_gatt_id_t srvc_id - // - case ESP_GATTC_SEARCH_RES_EVT: { - if (evtParam->search_res.conn_id != getConnId()) break; - BLEUUID uuid = BLEUUID(evtParam->search_res.srvc_id); - BLERemoteService* pRemoteService = new BLERemoteService( - evtParam->search_res.srvc_id, - this, - evtParam->search_res.start_handle, - evtParam->search_res.end_handle - ); - m_servicesMap.insert(std::pair(uuid.toString(), pRemoteService)); - m_servicesMapByInstID.insert(std::pair(pRemoteService, evtParam->search_res.srvc_id.inst_id)); - break; - } // ESP_GATTC_SEARCH_RES_EVT - - - default: { - break; - } - } // Switch - - // Pass the request on to all services. - for (auto &myPair : m_servicesMap) { - myPair.second->gattClientEventHandler(event, gattc_if, evtParam); - } - -} // gattClientEventHandler - - -uint16_t BLEClient::getConnId() { - return m_conn_id; -} // getConnId - - - -esp_gatt_if_t BLEClient::getGattcIf() { - return m_gattc_if; -} // getGattcIf - - -/** - * @brief Retrieve the address of the peer. - * - * Returns the Bluetooth device address of the %BLE peer to which this client is connected. - */ -BLEAddress BLEClient::getPeerAddress() { - return m_peerAddress; -} // getAddress - - -/** - * @brief Ask the BLE server for the RSSI value. - * @return The RSSI value. - */ -int BLEClient::getRssi() { - log_v(">> getRssi()"); - if (!isConnected()) { - log_v("<< getRssi(): Not connected"); - return 0; - } - // We make the API call to read the RSSI value which is an asynchronous operation. We expect to receive - // an ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT to indicate completion. - // - m_semaphoreRssiCmplEvt.take("getRssi"); - esp_err_t rc = ::esp_ble_gap_read_rssi(*getPeerAddress().getNative()); - if (rc != ESP_OK) { - log_e("<< getRssi: esp_ble_gap_read_rssi: rc=%d %s", rc, GeneralUtils::errorToString(rc)); - return 0; - } - int rssiValue = m_semaphoreRssiCmplEvt.wait("getRssi"); - log_v("<< getRssi(): %d", rssiValue); - return rssiValue; -} // getRssi - - -/** - * @brief Get the service BLE Remote Service instance corresponding to the uuid. - * @param [in] uuid The UUID of the service being sought. - * @return A reference to the Service or nullptr if don't know about it. - */ -BLERemoteService* BLEClient::getService(const char* uuid) { - return getService(BLEUUID(uuid)); -} // getService - - -/** - * @brief Get the service object corresponding to the uuid. - * @param [in] uuid The UUID of the service being sought. - * @return A reference to the Service or nullptr if don't know about it. - * @throws BLEUuidNotFound - */ -BLERemoteService* BLEClient::getService(BLEUUID uuid) { - log_v(">> getService: uuid: %s", uuid.toString().c_str()); -// Design -// ------ -// We wish to retrieve the service given its UUID. It is possible that we have not yet asked the -// device what services it has in which case we have nothing to match against. If we have not -// asked the device about its services, then we do that now. Once we get the results we can then -// examine the services map to see if it has the service we are looking for. - if (!m_haveServices) { - getServices(); - } - std::string uuidStr = uuid.toString(); - for (auto &myPair : m_servicesMap) { - if (myPair.first == uuidStr) { - log_v("<< getService: found the service with uuid: %s", uuid.toString().c_str()); - return myPair.second; - } - } // End of each of the services. - log_v("<< getService: not found"); - return nullptr; -} // getService - - -/** - * @brief Ask the remote %BLE server for its services. - * A %BLE Server exposes a set of services for its partners. Here we ask the server for its set of - * services and wait until we have received them all. - * @return N/A - */ -std::map* BLEClient::getServices() { -/* - * Design - * ------ - * We invoke esp_ble_gattc_search_service. This will request a list of the service exposed by the - * peer BLE partner to be returned as events. Each event will be an an instance of ESP_GATTC_SEARCH_RES_EVT - * and will culminate with an ESP_GATTC_SEARCH_CMPL_EVT when all have been received. - */ - log_v(">> getServices"); -// TODO implement retrieving services from cache - clearServices(); // Clear any services that may exist. - - esp_err_t errRc = esp_ble_gattc_search_service( - getGattcIf(), - getConnId(), - NULL // Filter UUID - ); - - m_semaphoreSearchCmplEvt.take("getServices"); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_search_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return &m_servicesMap; - } - // If sucessfull, remember that we now have services. - m_haveServices = (m_semaphoreSearchCmplEvt.wait("getServices") == 0); - log_v("<< getServices"); - return &m_servicesMap; -} // getServices - - -/** - * @brief Get the value of a specific characteristic associated with a specific service. - * @param [in] serviceUUID The service that owns the characteristic. - * @param [in] characteristicUUID The characteristic whose value we wish to read. - * @throws BLEUuidNotFound - */ -std::string BLEClient::getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID) { - log_v(">> getValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - std::string ret = getService(serviceUUID)->getCharacteristic(characteristicUUID)->readValue(); - log_v("<read_rssi_cmpl.rssi); - break; - } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - - default: - break; - } -} // handleGAPEvent - - -/** - * @brief Are we connected to a partner? - * @return True if we are connected and false if we are not connected. - */ -bool BLEClient::isConnected() { - return m_isConnected; -} // isConnected - - - - -/** - * @brief Set the callbacks that will be invoked. - */ -void BLEClient::setClientCallbacks(BLEClientCallbacks* pClientCallbacks) { - m_pClientCallbacks = pClientCallbacks; -} // setClientCallbacks - - -/** - * @brief Set the value of a specific characteristic associated with a specific service. - * @param [in] serviceUUID The service that owns the characteristic. - * @param [in] characteristicUUID The characteristic whose value we wish to write. - * @throws BLEUuidNotFound - */ -void BLEClient::setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { - log_v(">> setValue: serviceUUID: %s, characteristicUUID: %s", serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - getService(serviceUUID)->getCharacteristic(characteristicUUID)->writeValue(value); - log_v("<< setValue"); -} // setValue - -uint16_t BLEClient::getMTU() { - return m_mtu; -} - -/** - * @brief Return a string representation of this client. - * @return A string representation of this client. - */ -std::string BLEClient::toString() { - std::string res = "peer address: " + m_peerAddress.toString(); - res += "\nServices:\n"; - for (auto &myPair : m_servicesMap) { - res += myPair.second->toString() + "\n"; - // myPair.second is the value - } - return res; -} // toString - - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEClient.h b/libraries/BLE/src/BLEClient.h deleted file mode 100644 index faf2f0c3..00000000 --- a/libraries/BLE/src/BLEClient.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * BLEDevice.h - * - * Created on: Mar 22, 2017 - * Author: kolban - */ - -#ifndef MAIN_BLEDEVICE_H_ -#define MAIN_BLEDEVICE_H_ - -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include -#include -#include -#include -//#include "BLEExceptions.h" -#include "BLERemoteService.h" -#include "BLEService.h" -#include "BLEAddress.h" -#include "BLEAdvertisedDevice.h" - -class BLERemoteService; -class BLEClientCallbacks; -class BLEAdvertisedDevice; - -/** - * @brief A model of a %BLE client. - */ -class BLEClient { -public: - BLEClient(); - ~BLEClient(); - - bool connect(BLEAdvertisedDevice* device); - bool connect(BLEAddress address, esp_ble_addr_type_t type = BLE_ADDR_TYPE_PUBLIC); // Connect to the remote BLE Server - void disconnect(); // Disconnect from the remote BLE Server - BLEAddress getPeerAddress(); // Get the address of the remote BLE Server - int getRssi(); // Get the RSSI of the remote BLE Server - std::map* getServices(); // Get a map of the services offered by the remote BLE Server - BLERemoteService* getService(const char* uuid); // Get a reference to a specified service offered by the remote BLE server. - BLERemoteService* getService(BLEUUID uuid); // Get a reference to a specified service offered by the remote BLE server. - std::string getValue(BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a given characteristic at a given service. - - - void handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - - bool isConnected(); // Return true if we are connected. - - void setClientCallbacks(BLEClientCallbacks *pClientCallbacks); - void setValue(BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a given characteristic at a given service. - - std::string toString(); // Return a string representation of this client. - uint16_t getConnId(); - esp_gatt_if_t getGattcIf(); - uint16_t getMTU(); - -uint16_t m_appId; -private: - friend class BLEDevice; - friend class BLERemoteService; - friend class BLERemoteCharacteristic; - friend class BLERemoteDescriptor; - - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param); - - BLEAddress m_peerAddress = BLEAddress((uint8_t*)"\0\0\0\0\0\0"); // The BD address of the remote server. - uint16_t m_conn_id; -// int m_deviceType; - esp_gatt_if_t m_gattc_if; - bool m_haveServices = false; // Have we previously obtain the set of services from the remote server. - bool m_isConnected = false; // Are we currently connected. - - BLEClientCallbacks* m_pClientCallbacks; - FreeRTOS::Semaphore m_semaphoreRegEvt = FreeRTOS::Semaphore("RegEvt"); - FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); - FreeRTOS::Semaphore m_semaphoreSearchCmplEvt = FreeRTOS::Semaphore("SearchCmplEvt"); - FreeRTOS::Semaphore m_semaphoreRssiCmplEvt = FreeRTOS::Semaphore("RssiCmplEvt"); - std::map m_servicesMap; - std::map m_servicesMapByInstID; - void clearServices(); // Clear any existing services. - uint16_t m_mtu = 23; -}; // class BLEDevice - - -/** - * @brief Callbacks associated with a %BLE client. - */ -class BLEClientCallbacks { -public: - virtual ~BLEClientCallbacks() {}; - virtual void onConnect(BLEClient *pClient) = 0; - virtual void onDisconnect(BLEClient *pClient) = 0; -}; - -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* MAIN_BLEDEVICE_H_ */ diff --git a/libraries/BLE/src/BLEDescriptor.cpp b/libraries/BLE/src/BLEDescriptor.cpp deleted file mode 100644 index ef96dbe7..00000000 --- a/libraries/BLE/src/BLEDescriptor.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/* - * BLEDescriptor.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include -#include -#include "sdkconfig.h" -#include -#include "BLEService.h" -#include "BLEDescriptor.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -#define NULL_HANDLE (0xffff) - - -/** - * @brief BLEDescriptor constructor. - */ -BLEDescriptor::BLEDescriptor(const char* uuid, uint16_t len) : BLEDescriptor(BLEUUID(uuid), len) { -} - -/** - * @brief BLEDescriptor constructor. - */ -BLEDescriptor::BLEDescriptor(BLEUUID uuid, uint16_t max_len) { - m_bleUUID = uuid; - m_value.attr_len = 0; // Initial length is 0. - m_value.attr_max_len = max_len; // Maximum length of the data. - m_handle = NULL_HANDLE; // Handle is initially unknown. - m_pCharacteristic = nullptr; // No initial characteristic. - m_pCallback = nullptr; // No initial callback. - - m_value.attr_value = (uint8_t*) malloc(max_len); // Allocate storage for the value. -} // BLEDescriptor - - -/** - * @brief BLEDescriptor destructor. - */ -BLEDescriptor::~BLEDescriptor() { - free(m_value.attr_value); // Release the storage we created in the constructor. -} // ~BLEDescriptor - - -/** - * @brief Execute the creation of the descriptor with the BLE runtime in ESP. - * @param [in] pCharacteristic The characteristic to which to register this descriptor. - */ -void BLEDescriptor::executeCreate(BLECharacteristic* pCharacteristic) { - log_v(">> executeCreate(): %s", toString().c_str()); - - if (m_handle != NULL_HANDLE) { - log_e("Descriptor already has a handle."); - return; - } - - m_pCharacteristic = pCharacteristic; // Save the characteristic associated with this service. - - esp_attr_control_t control; - control.auto_rsp = ESP_GATT_AUTO_RSP; - m_semaphoreCreateEvt.take("executeCreate"); - esp_err_t errRc = ::esp_ble_gatts_add_char_descr( - pCharacteristic->getService()->getHandle(), - getUUID().getNative(), - (esp_gatt_perm_t)m_permissions, - &m_value, - &control); - if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_add_char_descr: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreCreateEvt.wait("executeCreate"); - log_v("<< executeCreate"); -} // executeCreate - - -/** - * @brief Get the BLE handle for this descriptor. - * @return The handle for this descriptor. - */ -uint16_t BLEDescriptor::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Get the length of the value of this descriptor. - * @return The length (in bytes) of the value of this descriptor. - */ -size_t BLEDescriptor::getLength() { - return m_value.attr_len; -} // getLength - - -/** - * @brief Get the UUID of the descriptor. - */ -BLEUUID BLEDescriptor::getUUID() { - return m_bleUUID; -} // getUUID - - - -/** - * @brief Get the value of this descriptor. - * @return A pointer to the value of this descriptor. - */ -uint8_t* BLEDescriptor::getValue() { - return m_value.attr_value; -} // getValue - - -/** - * @brief Handle GATT server events for the descripttor. - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLEDescriptor::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - switch (event) { - // ESP_GATTS_ADD_CHAR_DESCR_EVT - // - // add_char_descr: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - case ESP_GATTS_ADD_CHAR_DESCR_EVT: { - if (m_pCharacteristic != nullptr && - m_bleUUID.equals(BLEUUID(param->add_char_descr.descr_uuid)) && - m_pCharacteristic->getService()->getHandle() == param->add_char_descr.service_handle && - m_pCharacteristic == m_pCharacteristic->getService()->getLastCreatedCharacteristic()) { - setHandle(param->add_char_descr.attr_handle); - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_ADD_CHAR_DESCR_EVT - - // ESP_GATTS_WRITE_EVT - A request to write the value of a descriptor has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t *value - case ESP_GATTS_WRITE_EVT: { - if (param->write.handle == m_handle) { - setValue(param->write.value, param->write.len); // Set the value of the descriptor. - - if (m_pCallback != nullptr) { // We have completed the write, if there is a user supplied callback handler, invoke it now. - m_pCallback->onWrite(this); // Invoke the onWrite callback handler. - } - } // End of ... this is our handle. - - break; - } // ESP_GATTS_WRITE_EVT - - // ESP_GATTS_READ_EVT - A request to read the value of a descriptor has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - if (param->read.handle == m_handle) { // If this event is for this descriptor ... process it - - if (m_pCallback != nullptr) { // If we have a user supplied callback, invoke it now. - m_pCallback->onRead(this); // Invoke the onRead callback method in the callback handler. - } - - } // End of this is our handle - break; - } // ESP_GATTS_READ_EVT - - default: - break; - } // switch event -} // handleGATTServerEvent - - -/** - * @brief Set the callback handlers for this descriptor. - * @param [in] pCallbacks An instance of a callback structure used to define any callbacks for the descriptor. - */ -void BLEDescriptor::setCallbacks(BLEDescriptorCallbacks* pCallback) { - log_v(">> setCallbacks: 0x%x", (uint32_t) pCallback); - m_pCallback = pCallback; - log_v("<< setCallbacks"); -} // setCallbacks - - -/** - * @brief Set the handle of this descriptor. - * Set the handle of this descriptor to be the supplied value. - * @param [in] handle The handle to be associated with this descriptor. - * @return N/A. - */ -void BLEDescriptor::setHandle(uint16_t handle) { - log_v(">> setHandle(0x%.2x): Setting descriptor handle to be 0x%.2x", handle, handle); - m_handle = handle; - log_v("<< setHandle()"); -} // setHandle - - -/** - * @brief Set the value of the descriptor. - * @param [in] data The data to set for the descriptor. - * @param [in] length The length of the data in bytes. - */ -void BLEDescriptor::setValue(uint8_t* data, size_t length) { - if (length > ESP_GATT_MAX_ATTR_LEN) { - log_e("Size %d too large, must be no bigger than %d", length, ESP_GATT_MAX_ATTR_LEN); - return; - } - m_value.attr_len = length; - memcpy(m_value.attr_value, data, length); -} // setValue - - -/** - * @brief Set the value of the descriptor. - * @param [in] value The value of the descriptor in string form. - */ -void BLEDescriptor::setValue(std::string value) { - setValue((uint8_t*) value.data(), value.length()); -} // setValue - -void BLEDescriptor::setAccessPermissions(esp_gatt_perm_t perm) { - m_permissions = perm; -} - -/** - * @brief Return a string representation of the descriptor. - * @return A string representation of the descriptor. - */ -std::string BLEDescriptor::toString() { - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", m_handle); - std::string res = "UUID: " + m_bleUUID.toString() + ", handle: 0x" + hex; - return res; -} // toString - - -BLEDescriptorCallbacks::~BLEDescriptorCallbacks() {} - -/** - * @brief Callback function to support a read request. - * @param [in] pDescriptor The descriptor that is the source of the event. - */ -void BLEDescriptorCallbacks::onRead(BLEDescriptor* pDescriptor) { - log_d("BLEDescriptorCallbacks", ">> onRead: default"); - log_d("BLEDescriptorCallbacks", "<< onRead"); -} // onRead - - -/** - * @brief Callback function to support a write request. - * @param [in] pDescriptor The descriptor that is the source of the event. - */ -void BLEDescriptorCallbacks::onWrite(BLEDescriptor* pDescriptor) { - log_d("BLEDescriptorCallbacks", ">> onWrite: default"); - log_d("BLEDescriptorCallbacks", "<< onWrite"); -} // onWrite - - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEDescriptor.h b/libraries/BLE/src/BLEDescriptor.h deleted file mode 100644 index e3ccc57b..00000000 --- a/libraries/BLE/src/BLEDescriptor.h +++ /dev/null @@ -1,77 +0,0 @@ -/* - * BLEDescriptor.h - * - * Created on: Jun 22, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ -#define COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "BLEUUID.h" -#include "BLECharacteristic.h" -#include -#include "RTOS.h" - -class BLEService; -class BLECharacteristic; -class BLEDescriptorCallbacks; - -/** - * @brief A model of a %BLE descriptor. - */ -class BLEDescriptor { -public: - BLEDescriptor(const char* uuid, uint16_t max_len = 100); - BLEDescriptor(BLEUUID uuid, uint16_t max_len = 100); - virtual ~BLEDescriptor(); - - uint16_t getHandle(); // Get the handle of the descriptor. - size_t getLength(); // Get the length of the value of the descriptor. - BLEUUID getUUID(); // Get the UUID of the descriptor. - uint8_t* getValue(); // Get a pointer to the value of the descriptor. - void handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - void setAccessPermissions(esp_gatt_perm_t perm); // Set the permissions of the descriptor. - void setCallbacks(BLEDescriptorCallbacks* pCallbacks); // Set callbacks to be invoked for the descriptor. - void setValue(uint8_t* data, size_t size); // Set the value of the descriptor as a pointer to data. - void setValue(std::string value); // Set the value of the descriptor as a data buffer. - - std::string toString(); // Convert the descriptor to a string representation. - -private: - friend class BLEDescriptorMap; - friend class BLECharacteristic; - BLEUUID m_bleUUID; - uint16_t m_handle; - BLEDescriptorCallbacks* m_pCallback; - BLECharacteristic* m_pCharacteristic; - esp_gatt_perm_t m_permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE; - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - esp_attr_value_t m_value; - - void executeCreate(BLECharacteristic* pCharacteristic); - void setHandle(uint16_t handle); -}; // BLEDescriptor - - -/** - * @brief Callbacks that can be associated with a %BLE descriptors to inform of events. - * - * When a server application creates a %BLE descriptor, we may wish to be informed when there is either - * a read or write request to the descriptors value. An application can register a - * sub-classed instance of this class and will be notified when such an event happens. - */ -class BLEDescriptorCallbacks { -public: - virtual ~BLEDescriptorCallbacks(); - virtual void onRead(BLEDescriptor* pDescriptor); - virtual void onWrite(BLEDescriptor* pDescriptor); -}; -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEDESCRIPTOR_H_ */ diff --git a/libraries/BLE/src/BLEDescriptorMap.cpp b/libraries/BLE/src/BLEDescriptorMap.cpp deleted file mode 100644 index 49aeea21..00000000 --- a/libraries/BLE/src/BLEDescriptorMap.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * BLEDescriptorMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "BLECharacteristic.h" -#include "BLEDescriptor.h" -#include // ESP32 BLE -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -/** - * @brief Return the descriptor by UUID. - * @param [in] UUID The UUID to look up the descriptor. - * @return The descriptor. If not present, then nullptr is returned. - */ -BLEDescriptor* BLEDescriptorMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - - -/** - * @brief Return the descriptor by UUID. - * @param [in] UUID The UUID to look up the descriptor. - * @return The descriptor. If not present, then nullptr is returned. - */ -BLEDescriptor* BLEDescriptorMap::getByUUID(BLEUUID uuid) { - for (auto &myPair : m_uuidMap) { - if (myPair.first->getUUID().equals(uuid)) { - return myPair.first; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Return the descriptor by handle. - * @param [in] handle The handle to look up the descriptor. - * @return The descriptor. - */ -BLEDescriptor* BLEDescriptorMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Set the descriptor by UUID. - * @param [in] uuid The uuid of the descriptor. - * @param [in] characteristic The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByUUID(const char* uuid, BLEDescriptor* pDescriptor){ - m_uuidMap.insert(std::pair(pDescriptor, uuid)); -} // setByUUID - - - -/** - * @brief Set the descriptor by UUID. - * @param [in] uuid The uuid of the descriptor. - * @param [in] characteristic The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByUUID(BLEUUID uuid, BLEDescriptor* pDescriptor) { - m_uuidMap.insert(std::pair(pDescriptor, uuid.toString())); -} // setByUUID - - -/** - * @brief Set the descriptor by handle. - * @param [in] handle The handle of the descriptor. - * @param [in] descriptor The descriptor to cache. - * @return N/A. - */ -void BLEDescriptorMap::setByHandle(uint16_t handle, BLEDescriptor* pDescriptor) { - m_handleMap.insert(std::pair(handle, pDescriptor)); -} // setByHandle - - -/** - * @brief Return a string representation of the descriptor map. - * @return A string representation of the descriptor map. - */ -std::string BLEDescriptorMap::toString() { - std::string res; - char hex[5]; - int count = 0; - for (auto &myPair : m_uuidMap) { - if (count > 0) {res += "\n";} - snprintf(hex, sizeof(hex), "%04x", myPair.first->getHandle()); - count++; - res += "handle: 0x"; - res += hex; - res += ", uuid: " + myPair.first->getUUID().toString(); - } - return res; -} // toString - - -/** - * @breif Pass the GATT server event onwards to each of the descriptors found in the mapping - * @param [in] event - * @param [in] gatts_if - * @param [in] param - */ -void BLEDescriptorMap::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - // Invoke the handler for every descriptor we have. - for (auto &myPair : m_uuidMap) { - myPair.first->handleGATTServerEvent(event, gatts_if, param); - } -} // handleGATTServerEvent - - -/** - * @brief Get the first descriptor in the map. - * @return The first descriptor in the map. - */ -BLEDescriptor* BLEDescriptorMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) return nullptr; - BLEDescriptor* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getFirst - - -/** - * @brief Get the next descriptor in the map. - * @return The next descriptor in the map. - */ -BLEDescriptor* BLEDescriptorMap::getNext() { - if (m_iterator == m_uuidMap.end()) return nullptr; - BLEDescriptor* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getNext -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEDevice.cpp b/libraries/BLE/src/BLEDevice.cpp deleted file mode 100644 index 681f0e40..00000000 --- a/libraries/BLE/src/BLEDevice.cpp +++ /dev/null @@ -1,672 +0,0 @@ -/* - * BLE.cpp - * - * Created on: Mar 16, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include -#include -#include -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 ESP-IDF -#include // Part of C++ Standard library -#include // Part of C++ Standard library -#include // Part of C++ Standard library - -#include "BLEDevice.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" - -#if defined(ARDUINO_ARCH_ESP32) -#include "esp32-hal-bt.h" -#endif - -#include "esp32-hal-log.h" - - -/** - * Singletons for the BLEDevice. - */ -BLEServer* BLEDevice::m_pServer = nullptr; -BLEScan* BLEDevice::m_pScan = nullptr; -BLEClient* BLEDevice::m_pClient = nullptr; -bool initialized = false; -esp_ble_sec_act_t BLEDevice::m_securityLevel = (esp_ble_sec_act_t)0; -BLESecurityCallbacks* BLEDevice::m_securityCallbacks = nullptr; -uint16_t BLEDevice::m_localMTU = 23; // not sure if this variable is useful -BLEAdvertising* BLEDevice::m_bleAdvertising = nullptr; -uint16_t BLEDevice::m_appId = 0; -std::map BLEDevice::m_connectedClientsMap; -gap_event_handler BLEDevice::m_customGapHandler = nullptr; -gattc_event_handler BLEDevice::m_customGattcHandler = nullptr; -gatts_event_handler BLEDevice::m_customGattsHandler = nullptr; - -/** - * @brief Create a new instance of a client. - * @return A new instance of the client. - */ -/* STATIC */ BLEClient* BLEDevice::createClient() { - log_v(">> createClient"); -#ifndef CONFIG_GATTC_ENABLE // Check that BLE GATTC is enabled in make menuconfig - log_e("BLE GATTC is not enabled - CONFIG_GATTC_ENABLE not defined"); - abort(); -#endif // CONFIG_GATTC_ENABLE - m_pClient = new BLEClient(); - log_v("<< createClient"); - return m_pClient; -} // createClient - - -/** - * @brief Create a new instance of a server. - * @return A new instance of the server. - */ -/* STATIC */ BLEServer* BLEDevice::createServer() { - log_v(">> createServer"); -#ifndef CONFIG_GATTS_ENABLE // Check that BLE GATTS is enabled in make menuconfig - log_e("BLE GATTS is not enabled - CONFIG_GATTS_ENABLE not defined"); - abort(); -#endif // CONFIG_GATTS_ENABLE - m_pServer = new BLEServer(); - m_pServer->createApp(m_appId++); - log_v("<< createServer"); - return m_pServer; -} // createServer - - -/** - * @brief Handle GATT server events. - * - * @param [in] event The event that has been newly received. - * @param [in] gatts_if The connection to the GATT interface. - * @param [in] param Parameters for the event. - */ -/* STATIC */ void BLEDevice::gattServerEventHandler( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param -) { - log_d("gattServerEventHandler [esp_gatt_if: %d] ... %s", - gatts_if, - BLEUtils::gattServerEventTypeToString(event).c_str()); - - BLEUtils::dumpGattServerEvent(event, gatts_if, param); - - switch (event) { - case ESP_GATTS_CONNECT_EVT: { -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityLevel){ - esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - } // ESP_GATTS_CONNECT_EVT - - default: { - break; - } - } // switch - - - if (BLEDevice::m_pServer != nullptr) { - BLEDevice::m_pServer->handleGATTServerEvent(event, gatts_if, param); - } - - if(m_customGattsHandler != nullptr) { - m_customGattsHandler(event, gatts_if, param); - } - -} // gattServerEventHandler - - -/** - * @brief Handle GATT client events. - * - * Handler for the GATT client events. - * - * @param [in] event - * @param [in] gattc_if - * @param [in] param - */ -/* STATIC */ void BLEDevice::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param) { - - log_d("gattClientEventHandler [esp_gatt_if: %d] ... %s", - gattc_if, BLEUtils::gattClientEventTypeToString(event).c_str()); - BLEUtils::dumpGattClientEvent(event, gattc_if, param); - - switch(event) { - case ESP_GATTC_CONNECT_EVT: { -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityLevel){ - esp_ble_set_encryption(param->connect.remote_bda, BLEDevice::m_securityLevel); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - } // ESP_GATTS_CONNECT_EVT - - default: - break; - } // switch - for(auto &myPair : BLEDevice::getPeerDevices(true)) { - conn_status_t conn_status = (conn_status_t)myPair.second; - if(((BLEClient*)conn_status.peer_device)->getGattcIf() == gattc_if || ((BLEClient*)conn_status.peer_device)->getGattcIf() == ESP_GATT_IF_NONE || gattc_if == ESP_GATT_IF_NONE){ - ((BLEClient*)conn_status.peer_device)->gattClientEventHandler(event, gattc_if, param); - } - } - - if(m_customGattcHandler != nullptr) { - m_customGattcHandler(event, gattc_if, param); - } - - -} // gattClientEventHandler - - -/** - * @brief Handle GAP events. - */ -/* STATIC */ void BLEDevice::gapEventHandler( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t *param) { - - BLEUtils::dumpGapEvent(event, param); - - switch(event) { - - case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ - log_i("ESP_GAP_BLE_OOB_REQ_EVT"); - break; - case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ - log_i("ESP_GAP_BLE_LOCAL_IR_EVT"); - break; - case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ - log_i("ESP_GAP_BLE_LOCAL_ER_EVT"); - break; - case ESP_GAP_BLE_NC_REQ_EVT: /* NUMERIC CONFIRMATION */ - log_i("ESP_GAP_BLE_NC_REQ_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks != nullptr){ - esp_ble_confirm_reply(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onConfirmPIN(param->ble_security.key_notif.passkey)); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ - log_i("ESP_GAP_BLE_PASSKEY_REQ_EVT: "); - // esp_log_buffer_hex(m_remote_bda, sizeof(m_remote_bda)); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks != nullptr){ - esp_ble_passkey_reply(param->ble_security.ble_req.bd_addr, true, BLEDevice::m_securityCallbacks->onPassKeyRequest()); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - /* - * TODO should we add white/black list comparison? - */ - case ESP_GAP_BLE_SEC_REQ_EVT: - /* send the positive(true) security response to the peer device to accept the security request. - If not accept the security request, should sent the security response with negative(false) accept value*/ - log_i("ESP_GAP_BLE_SEC_REQ_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks!=nullptr){ - esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, BLEDevice::m_securityCallbacks->onSecurityRequest()); - } - else{ - esp_ble_gap_security_rsp(param->ble_security.ble_req.bd_addr, true); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - /* - * - */ - case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: //the app will receive this evt when the IO has Output capability and the peer device IO has Input capability. - //display the passkey number to the user to input it in the peer deivce within 30 seconds - log_i("ESP_GAP_BLE_PASSKEY_NOTIF_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - log_i("passKey = %d", param->ble_security.key_notif.passkey); - if(BLEDevice::m_securityCallbacks!=nullptr){ - BLEDevice::m_securityCallbacks->onPassKeyNotify(param->ble_security.key_notif.passkey); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_KEY_EVT: - //shows the ble key type info share with peer device to the user. - log_d("ESP_GAP_BLE_KEY_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - log_i("key type = %s", BLESecurity::esp_key_type_to_str(param->ble_security.ble_key.key_type)); -#endif // CONFIG_BLE_SMP_ENABLE - break; - case ESP_GAP_BLE_AUTH_CMPL_EVT: - log_i("ESP_GAP_BLE_AUTH_CMPL_EVT"); -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - if(BLEDevice::m_securityCallbacks != nullptr){ - BLEDevice::m_securityCallbacks->onAuthenticationComplete(param->ble_security.auth_cmpl); - } -#endif // CONFIG_BLE_SMP_ENABLE - break; - default: { - break; - } - } // switch - - if (BLEDevice::m_pClient != nullptr) { - BLEDevice::m_pClient->handleGAPEvent(event, param); - } - - if (BLEDevice::m_pScan != nullptr) { - BLEDevice::getScan()->handleGAPEvent(event, param); - } - - if(m_bleAdvertising != nullptr) { - BLEDevice::getAdvertising()->handleGAPEvent(event, param); - } - - if(m_customGapHandler != nullptr) { - BLEDevice::m_customGapHandler(event, param); - } - -} // gapEventHandler - - -/** - * @brief Get the BLE device address. - * @return The BLE device address. - */ -/* STATIC*/ BLEAddress BLEDevice::getAddress() { - const uint8_t* bdAddr = esp_bt_dev_get_address(); - esp_bd_addr_t addr; - memcpy(addr, bdAddr, sizeof(addr)); - return BLEAddress(addr); -} // getAddress - - -/** - * @brief Retrieve the Scan object that we use for scanning. - * @return The scanning object reference. This is a singleton object. The caller should not - * try and release/delete it. - */ -/* STATIC */ BLEScan* BLEDevice::getScan() { - //log_v(">> getScan"); - if (m_pScan == nullptr) { - m_pScan = new BLEScan(); - //log_d(" - creating a new scan object"); - } - //log_v("<< getScan: Returning object at 0x%x", (uint32_t)m_pScan); - return m_pScan; -} // getScan - - -/** - * @brief Get the value of a characteristic of a service on a remote device. - * @param [in] bdAddress - * @param [in] serviceUUID - * @param [in] characteristicUUID - */ -/* STATIC */ std::string BLEDevice::getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID) { - log_v(">> getValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - BLEClient* pClient = createClient(); - pClient->connect(bdAddress); - std::string ret = pClient->getValue(serviceUUID, characteristicUUID); - pClient->disconnect(); - log_v("<< getValue"); - return ret; -} // getValue - - -/** - * @brief Initialize the %BLE environment. - * @param deviceName The device name of the device. - */ -/* STATIC */ void BLEDevice::init(std::string deviceName) { - if(!initialized){ - initialized = true; // Set the initialization flag to ensure we are only initialized once. - - esp_err_t errRc = ESP_OK; -#ifdef ARDUINO_ARCH_ESP32 - if (!btStart()) { - errRc = ESP_FAIL; - return; - } -#else - errRc = ::nvs_flash_init(); - if (errRc != ESP_OK) { - log_e("nvs_flash_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - -#ifndef CLASSIC_BT_ENABLED - esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT); -#endif - esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); - errRc = esp_bt_controller_init(&bt_cfg); - if (errRc != ESP_OK) { - log_e("esp_bt_controller_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - -#ifndef CLASSIC_BT_ENABLED - errRc = esp_bt_controller_enable(ESP_BT_MODE_BLE); - if (errRc != ESP_OK) { - log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#else - errRc = esp_bt_controller_enable(ESP_BT_MODE_BTDM); - if (errRc != ESP_OK) { - log_e("esp_bt_controller_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif -#endif - - esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); - if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED) { - errRc = esp_bluedroid_init(); - if (errRc != ESP_OK) { - log_e("esp_bluedroid_init: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - if (bt_state != ESP_BLUEDROID_STATUS_ENABLED) { - errRc = esp_bluedroid_enable(); - if (errRc != ESP_OK) { - log_e("esp_bluedroid_enable: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - } - - errRc = esp_ble_gap_register_callback(BLEDevice::gapEventHandler); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - -#ifdef CONFIG_GATTC_ENABLE // Check that BLE client is configured in make menuconfig - errRc = esp_ble_gattc_register_callback(BLEDevice::gattClientEventHandler); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif // CONFIG_GATTC_ENABLE - -#ifdef CONFIG_GATTS_ENABLE // Check that BLE server is configured in make menuconfig - errRc = esp_ble_gatts_register_callback(BLEDevice::gattServerEventHandler); - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_register_callback: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } -#endif // CONFIG_GATTS_ENABLE - - errRc = ::esp_ble_gap_set_device_name(deviceName.c_str()); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_device_name: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - }; - -#ifdef CONFIG_BLE_SMP_ENABLE // Check that BLE SMP (security) is configured in make menuconfig - esp_ble_io_cap_t iocap = ESP_IO_CAP_NONE; - errRc = ::esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); - if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_security_param: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - }; -#endif // CONFIG_BLE_SMP_ENABLE - } - vTaskDelay(200 / portTICK_PERIOD_MS); // Delay for 200 msecs as a workaround to an apparent Arduino environment issue. -} // init - - -/** - * @brief Set the transmission power. - * The power level can be one of: - * * ESP_PWR_LVL_N14 - * * ESP_PWR_LVL_N11 - * * ESP_PWR_LVL_N8 - * * ESP_PWR_LVL_N5 - * * ESP_PWR_LVL_N2 - * * ESP_PWR_LVL_P1 - * * ESP_PWR_LVL_P4 - * * ESP_PWR_LVL_P7 - * - * The power types can be one of: - * * ESP_BLE_PWR_TYPE_CONN_HDL0 - * * ESP_BLE_PWR_TYPE_CONN_HDL1 - * * ESP_BLE_PWR_TYPE_CONN_HDL2 - * * ESP_BLE_PWR_TYPE_CONN_HDL3 - * * ESP_BLE_PWR_TYPE_CONN_HDL4 - * * ESP_BLE_PWR_TYPE_CONN_HDL5 - * * ESP_BLE_PWR_TYPE_CONN_HDL6 - * * ESP_BLE_PWR_TYPE_CONN_HDL7 - * * ESP_BLE_PWR_TYPE_CONN_HDL8 - * * ESP_BLE_PWR_TYPE_ADV - * * ESP_BLE_PWR_TYPE_SCAN - * * ESP_BLE_PWR_TYPE_DEFAULT - * @param [in] powerType. - * @param [in] powerLevel. - */ -/* STATIC */ void BLEDevice::setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType) { - log_v(">> setPower: %d (type: %d)", powerLevel, powerType); - esp_err_t errRc = ::esp_ble_tx_power_set(powerType, powerLevel); - if (errRc != ESP_OK) { - log_e("esp_ble_tx_power_set: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - }; - log_v("<< setPower"); -} // setPower - - -/** - * @brief Set the value of a characteristic of a service on a remote device. - * @param [in] bdAddress - * @param [in] serviceUUID - * @param [in] characteristicUUID - */ -/* STATIC */ void BLEDevice::setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value) { - log_v(">> setValue: bdAddress: %s, serviceUUID: %s, characteristicUUID: %s", bdAddress.toString().c_str(), serviceUUID.toString().c_str(), characteristicUUID.toString().c_str()); - BLEClient* pClient = createClient(); - pClient->connect(bdAddress); - pClient->setValue(serviceUUID, characteristicUUID, value); - pClient->disconnect(); -} // setValue - - -/** - * @brief Return a string representation of the nature of this device. - * @return A string representation of the nature of this device. - */ -/* STATIC */ std::string BLEDevice::toString() { - std::string res = "BD Address: " + getAddress().toString(); - return res; -} // toString - - -/** - * @brief Add an entry to the BLE white list. - * @param [in] address The address to add to the white list. - */ -void BLEDevice::whiteListAdd(BLEAddress address) { - log_v(">> whiteListAdd: %s", address.toString().c_str()); -#ifdef ESP_IDF_VERSION_MAJOR - esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC); // HACK!!! True to add an entry. -#else - esp_err_t errRc = esp_ble_gap_update_whitelist(true, *address.getNative()); // True to add an entry. -#endif - if (errRc != ESP_OK) { - log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - log_v("<< whiteListAdd"); -} // whiteListAdd - - -/** - * @brief Remove an entry from the BLE white list. - * @param [in] address The address to remove from the white list. - */ -void BLEDevice::whiteListRemove(BLEAddress address) { - log_v(">> whiteListRemove: %s", address.toString().c_str()); -#ifdef ESP_IDF_VERSION_MAJOR - esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative(), BLE_WL_ADDR_TYPE_PUBLIC); // HACK!!! False to remove an entry. -#else - esp_err_t errRc = esp_ble_gap_update_whitelist(false, *address.getNative()); // False to remove an entry. -#endif - if (errRc != ESP_OK) { - log_e("esp_ble_gap_update_whitelist: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - log_v("<< whiteListRemove"); -} // whiteListRemove - -/* - * @brief Set encryption level that will be negotiated with peer device durng connection - * @param [in] level Requested encryption level - */ -void BLEDevice::setEncryptionLevel(esp_ble_sec_act_t level) { - BLEDevice::m_securityLevel = level; -} - -/* - * @brief Set callbacks that will be used to handle encryption negotiation events and authentication events - * @param [in] cllbacks Pointer to BLESecurityCallbacks class callback - */ -void BLEDevice::setSecurityCallbacks(BLESecurityCallbacks* callbacks) { - BLEDevice::m_securityCallbacks = callbacks; -} - -/* - * @brief Setup local mtu that will be used to negotiate mtu during request from client peer - * @param [in] mtu Value to set local mtu, should be larger than 23 and lower or equal to 517 - */ -esp_err_t BLEDevice::setMTU(uint16_t mtu) { - log_v(">> setLocalMTU: %d", mtu); - esp_err_t err = esp_ble_gatt_set_local_mtu(mtu); - if (err == ESP_OK) { - m_localMTU = mtu; - } else { - log_e("can't set local mtu value: %d", mtu); - } - log_v("<< setLocalMTU"); - return err; -} - -/* - * @brief Get local MTU value set during mtu request or default value - */ -uint16_t BLEDevice::getMTU() { - return m_localMTU; -} - -bool BLEDevice::getInitialized() { - return initialized; -} - -BLEAdvertising* BLEDevice::getAdvertising() { - if(m_bleAdvertising == nullptr) { - m_bleAdvertising = new BLEAdvertising(); - log_i("create advertising"); - } - log_d("get advertising"); - return m_bleAdvertising; -} - -void BLEDevice::startAdvertising() { - log_v(">> startAdvertising"); - getAdvertising()->start(); - log_v("<< startAdvertising"); -} // startAdvertising - -void BLEDevice::stopAdvertising() { - log_v(">> stopAdvertising"); - getAdvertising()->stop(); - log_v("<< stopAdvertising"); -} // stopAdvertising - -/* multi connect support */ -/* requires a little more work */ -std::map BLEDevice::getPeerDevices(bool _client) { - return m_connectedClientsMap; -} - -BLEClient* BLEDevice::getClientByGattIf(uint16_t conn_id) { - return (BLEClient*)m_connectedClientsMap.find(conn_id)->second.peer_device; -} - -void BLEDevice::updatePeerDevice(void* peer, bool _client, uint16_t conn_id) { - log_d("update conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); - std::map::iterator it = m_connectedClientsMap.find(ESP_GATT_IF_NONE); - if (it != m_connectedClientsMap.end()) { - std::swap(m_connectedClientsMap[conn_id], it->second); - m_connectedClientsMap.erase(it); - }else{ - it = m_connectedClientsMap.find(conn_id); - if (it != m_connectedClientsMap.end()) { - conn_status_t _st = it->second; - _st.peer_device = peer; - std::swap(m_connectedClientsMap[conn_id], _st); - } - } -} - -void BLEDevice::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { - log_i("add conn_id: %d, GATT role: %s", conn_id, _client? "client":"server"); - conn_status_t status = { - .peer_device = peer, - .connected = true, - .mtu = 23 - }; - - m_connectedClientsMap.insert(std::pair(conn_id, status)); -} - -void BLEDevice::removePeerDevice(uint16_t conn_id, bool _client) { - log_i("remove: %d, GATT role %s", conn_id, _client?"client":"server"); - if(m_connectedClientsMap.find(conn_id) != m_connectedClientsMap.end()) - m_connectedClientsMap.erase(conn_id); -} - -/* multi connect support */ - -/** - * @brief de-Initialize the %BLE environment. - * @param release_memory release the internal BT stack memory - */ -/* STATIC */ void BLEDevice::deinit(bool release_memory) { - if (!initialized) return; - - esp_bluedroid_disable(); - esp_bluedroid_deinit(); - esp_bt_controller_disable(); - esp_bt_controller_deinit(); -#ifdef ARDUINO_ARCH_ESP32 - if (release_memory) { - esp_bt_controller_mem_release(ESP_BT_MODE_BTDM); // <-- require tests because we released classic BT memory and this can cause crash (most likely not, esp-idf takes care of it) - } else { - initialized = false; - } -#endif -} - -void BLEDevice::setCustomGapHandler(gap_event_handler handler) { - m_customGapHandler = handler; -} - -void BLEDevice::setCustomGattcHandler(gattc_event_handler handler) { - m_customGattcHandler = handler; -} - -void BLEDevice::setCustomGattsHandler(gatts_event_handler handler) { - m_customGattsHandler = handler; -} - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEDevice.h b/libraries/BLE/src/BLEDevice.h deleted file mode 100644 index aa548ddf..00000000 --- a/libraries/BLE/src/BLEDevice.h +++ /dev/null @@ -1,100 +0,0 @@ -/* - * BLEDevice.h - * - * Created on: Mar 16, 2017 - * Author: kolban - */ - -#ifndef MAIN_BLEDevice_H_ -#define MAIN_BLEDevice_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include // ESP32 BLE -#include // ESP32 BLE -#include // Part of C++ STL -#include -#include - -#include "BLEServer.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEScan.h" -#include "BLEAddress.h" - -/** - * @brief BLE functions. - */ -typedef void (*gap_event_handler)(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t* param); -typedef void (*gattc_event_handler)(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* param); -typedef void (*gatts_event_handler)(esp_gatts_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gatts_cb_param_t* param); - -class BLEDevice { -public: - - static BLEClient* createClient(); // Create a new BLE client. - static BLEServer* createServer(); // Cretae a new BLE server. - static BLEAddress getAddress(); // Retrieve our own local BD address. - static BLEScan* getScan(); // Get the scan object - static std::string getValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID); // Get the value of a characteristic of a service on a server. - static void init(std::string deviceName); // Initialize the local BLE environment. - static void setPower(esp_power_level_t powerLevel, esp_ble_power_type_t powerType=ESP_BLE_PWR_TYPE_DEFAULT); // Set our power level. - static void setValue(BLEAddress bdAddress, BLEUUID serviceUUID, BLEUUID characteristicUUID, std::string value); // Set the value of a characteristic on a service on a server. - static std::string toString(); // Return a string representation of our device. - static void whiteListAdd(BLEAddress address); // Add an entry to the BLE white list. - static void whiteListRemove(BLEAddress address); // Remove an entry from the BLE white list. - static void setEncryptionLevel(esp_ble_sec_act_t level); - static void setSecurityCallbacks(BLESecurityCallbacks* pCallbacks); - static esp_err_t setMTU(uint16_t mtu); - static uint16_t getMTU(); - static bool getInitialized(); // Returns the state of the device, is it initialized or not? - /* move advertising to BLEDevice for saving ram and flash in beacons */ - static BLEAdvertising* getAdvertising(); - static void startAdvertising(); - static void stopAdvertising(); - static uint16_t m_appId; - /* multi connect */ - static std::map getPeerDevices(bool client); - static void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); - static void updatePeerDevice(void* peer, bool _client, uint16_t conn_id); - static void removePeerDevice(uint16_t conn_id, bool client); - static BLEClient* getClientByGattIf(uint16_t conn_id); - static void setCustomGapHandler(gap_event_handler handler); - static void setCustomGattcHandler(gattc_event_handler handler); - static void setCustomGattsHandler(gatts_event_handler handler); - static void deinit(bool release_memory = false); - static uint16_t m_localMTU; - static esp_ble_sec_act_t m_securityLevel; - -private: - static BLEServer* m_pServer; - static BLEScan* m_pScan; - static BLEClient* m_pClient; - static BLESecurityCallbacks* m_securityCallbacks; - static BLEAdvertising* m_bleAdvertising; - static esp_gatt_if_t getGattcIF(); - static std::map m_connectedClientsMap; - - static void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* param); - - static void gattServerEventHandler( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param); - - static void gapEventHandler( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - -public: -/* custom gap and gatt handlers for flexibility */ - static gap_event_handler m_customGapHandler; - static gattc_event_handler m_customGattcHandler; - static gatts_event_handler m_customGattsHandler; - -}; // class BLE - -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* MAIN_BLEDevice_H_ */ diff --git a/libraries/BLE/src/BLEEddystoneTLM.cpp b/libraries/BLE/src/BLEEddystoneTLM.cpp deleted file mode 100644 index 10cc657a..00000000 --- a/libraries/BLE/src/BLEEddystoneTLM.cpp +++ /dev/null @@ -1,146 +0,0 @@ -/* - * BLEEddystoneTLM.cpp - * - * Created on: Mar 12, 2018 - * Author: pcbreflux - * Edited on: Mar 20, 2020 by beegee-tokyo - * Fix temperature value (8.8 fixed format) - * Fix time stamp (0.1 second resolution) - * Fixes based on EddystoneTLM frame specification https://github.com/google/eddystone/blob/master/eddystone-tlm/tlm-plain.md - * - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "esp32-hal-log.h" -#include "BLEEddystoneTLM.h" - -static const char LOG_TAG[] = "BLEEddystoneTLM"; -#define ENDIAN_CHANGE_U16(x) ((((x)&0xFF00)>>8) + (((x)&0xFF)<<8)) -#define ENDIAN_CHANGE_U32(x) ((((x)&0xFF000000)>>24) + (((x)&0x00FF0000)>>8)) + ((((x)&0xFF00)<<8) + (((x)&0xFF)<<24)) - -BLEEddystoneTLM::BLEEddystoneTLM() { - beaconUUID = 0xFEAA; - m_eddystoneData.frameType = EDDYSTONE_TLM_FRAME_TYPE; - m_eddystoneData.version = 0; - m_eddystoneData.volt = 3300; // 3300mV = 3.3V - m_eddystoneData.temp = (uint16_t) ((float) 23.00)/256; - m_eddystoneData.advCount = 0; - m_eddystoneData.tmil = 0; -} // BLEEddystoneTLM - -std::string BLEEddystoneTLM::getData() { - return std::string((char*) &m_eddystoneData, sizeof(m_eddystoneData)); -} // getData - -BLEUUID BLEEddystoneTLM::getUUID() { - return BLEUUID(beaconUUID); -} // getUUID - -uint8_t BLEEddystoneTLM::getVersion() { - return m_eddystoneData.version; -} // getVersion - -uint16_t BLEEddystoneTLM::getVolt() { - return ENDIAN_CHANGE_U16(m_eddystoneData.volt); -} // getVolt - -float BLEEddystoneTLM::getTemp() { - return ENDIAN_CHANGE_U16(m_eddystoneData.temp) / 256.0f; -} // getTemp - -uint32_t BLEEddystoneTLM::getCount() { - return ENDIAN_CHANGE_U32(m_eddystoneData.advCount); -} // getCount - -uint32_t BLEEddystoneTLM::getTime() { - return (ENDIAN_CHANGE_U32(m_eddystoneData.tmil)) / 10; -} // getTime - -std::string BLEEddystoneTLM::toString() { - std::string out = ""; - uint32_t rawsec = ENDIAN_CHANGE_U32(m_eddystoneData.tmil); - char val[12]; - - out += "Version "; // + std::string(m_eddystoneData.version); - snprintf(val, sizeof(val), "%d", m_eddystoneData.version); - out += val; - out += "\n"; - out += "Battery Voltage "; // + ENDIAN_CHANGE_U16(m_eddystoneData.volt); - snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U16(m_eddystoneData.volt)); - out += val; - out += " mV\n"; - - out += "Temperature "; - snprintf(val, sizeof(val), "%.2f", ENDIAN_CHANGE_U16(m_eddystoneData.temp) / 256.0f); - out += val; - out += " C\n"; - - out += "Adv. Count "; - snprintf(val, sizeof(val), "%d", ENDIAN_CHANGE_U32(m_eddystoneData.advCount)); - out += val; - out += "\n"; - - out += "Time in seconds "; - snprintf(val, sizeof(val), "%d", rawsec/10); - out += val; - out += "\n"; - - out += "Time "; - - snprintf(val, sizeof(val), "%04d", rawsec / 864000); - out += val; - out += "."; - - snprintf(val, sizeof(val), "%02d", (rawsec / 36000) % 24); - out += val; - out += ":"; - - snprintf(val, sizeof(val), "%02d", (rawsec / 600) % 60); - out += val; - out += ":"; - - snprintf(val, sizeof(val), "%02d", (rawsec / 10) % 60); - out += val; - out += "\n"; - - return out; -} // toString - -/** - * Set the raw data for the beacon record. - */ -void BLEEddystoneTLM::setData(std::string data) { - if (data.length() != sizeof(m_eddystoneData)) { - log_e("Unable to set the data ... length passed in was %d and expected %d", data.length(), sizeof(m_eddystoneData)); - return; - } - memcpy(&m_eddystoneData, data.data(), data.length()); -} // setData - -void BLEEddystoneTLM::setUUID(BLEUUID l_uuid) { - beaconUUID = l_uuid.getNative()->uuid.uuid16; -} // setUUID - -void BLEEddystoneTLM::setVersion(uint8_t version) { - m_eddystoneData.version = version; -} // setVersion - -void BLEEddystoneTLM::setVolt(uint16_t volt) { - m_eddystoneData.volt = volt; -} // setVolt - -void BLEEddystoneTLM::setTemp(float temp) { - m_eddystoneData.temp = (uint16_t)temp; -} // setTemp - -void BLEEddystoneTLM::setCount(uint32_t advCount) { - m_eddystoneData.advCount = advCount; -} // setCount - -void BLEEddystoneTLM::setTime(uint32_t tmil) { - m_eddystoneData.tmil = tmil; -} // setTime - -#endif diff --git a/libraries/BLE/src/BLEEddystoneTLM.h b/libraries/BLE/src/BLEEddystoneTLM.h deleted file mode 100644 index a93e224f..00000000 --- a/libraries/BLE/src/BLEEddystoneTLM.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * BLEEddystoneTLM.cpp - * - * Created on: Mar 12, 2018 - * Author: pcbreflux - */ - -#ifndef _BLEEddystoneTLM_H_ -#define _BLEEddystoneTLM_H_ -#include "BLEUUID.h" - -#define EDDYSTONE_TLM_FRAME_TYPE 0x20 - -/** - * @brief Representation of a beacon. - * See: - * * https://github.com/google/eddystone - */ -class BLEEddystoneTLM { -public: - BLEEddystoneTLM(); - std::string getData(); - BLEUUID getUUID(); - uint8_t getVersion(); - uint16_t getVolt(); - float getTemp(); - uint32_t getCount(); - uint32_t getTime(); - std::string toString(); - void setData(std::string data); - void setUUID(BLEUUID l_uuid); - void setVersion(uint8_t version); - void setVolt(uint16_t volt); - void setTemp(float temp); - void setCount(uint32_t advCount); - void setTime(uint32_t tmil); - -private: - uint16_t beaconUUID; - struct { - uint8_t frameType; - uint8_t version; - uint16_t volt; - uint16_t temp; - uint32_t advCount; - uint32_t tmil; - } __attribute__((packed)) m_eddystoneData; - -}; // BLEEddystoneTLM - -#endif /* _BLEEddystoneTLM_H_ */ diff --git a/libraries/BLE/src/BLEEddystoneURL.cpp b/libraries/BLE/src/BLEEddystoneURL.cpp deleted file mode 100644 index 1c23e52b..00000000 --- a/libraries/BLE/src/BLEEddystoneURL.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * BLEEddystoneURL.cpp - * - * Created on: Mar 12, 2018 - * Author: pcbreflux - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "esp32-hal-log.h" -#include "BLEEddystoneURL.h" - -static const char LOG_TAG[] = "BLEEddystoneURL"; - -BLEEddystoneURL::BLEEddystoneURL() { - beaconUUID = 0xFEAA; - lengthURL = 0; - m_eddystoneData.frameType = EDDYSTONE_URL_FRAME_TYPE; - m_eddystoneData.advertisedTxPower = 0; - memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); -} // BLEEddystoneURL - -std::string BLEEddystoneURL::getData() { - return std::string((char*) &m_eddystoneData, sizeof(m_eddystoneData)); -} // getData - -BLEUUID BLEEddystoneURL::getUUID() { - return BLEUUID(beaconUUID); -} // getUUID - -int8_t BLEEddystoneURL::getPower() { - return m_eddystoneData.advertisedTxPower; -} // getPower - -std::string BLEEddystoneURL::getURL() { - return std::string((char*) &m_eddystoneData.url, sizeof(m_eddystoneData.url)); -} // getURL - -std::string BLEEddystoneURL::getDecodedURL() { - std::string decodedURL = ""; - - switch (m_eddystoneData.url[0]) { - case 0x00: - decodedURL += "http://www."; - break; - case 0x01: - decodedURL += "https://www."; - break; - case 0x02: - decodedURL += "http://"; - break; - case 0x03: - decodedURL += "https://"; - break; - default: - decodedURL += m_eddystoneData.url[0]; - } - - for (int i = 1; i < lengthURL; i++) { - if (m_eddystoneData.url[i] > 33 && m_eddystoneData.url[i] < 127) { - decodedURL += m_eddystoneData.url[i]; - } else { - switch (m_eddystoneData.url[i]) { - case 0x00: - decodedURL += ".com/"; - break; - case 0x01: - decodedURL += ".org/"; - break; - case 0x02: - decodedURL += ".edu/"; - break; - case 0x03: - decodedURL += ".net/"; - break; - case 0x04: - decodedURL += ".info/"; - break; - case 0x05: - decodedURL += ".biz/"; - break; - case 0x06: - decodedURL += ".gov/"; - break; - case 0x07: - decodedURL += ".com"; - break; - case 0x08: - decodedURL += ".org"; - break; - case 0x09: - decodedURL += ".edu"; - break; - case 0x0A: - decodedURL += ".net"; - break; - case 0x0B: - decodedURL += ".info"; - break; - case 0x0C: - decodedURL += ".biz"; - break; - case 0x0D: - decodedURL += ".gov"; - break; - default: - break; - } - } - } - return decodedURL; -} // getDecodedURL - - - -/** - * Set the raw data for the beacon record. - */ -void BLEEddystoneURL::setData(std::string data) { - if (data.length() > sizeof(m_eddystoneData)) { - log_e("Unable to set the data ... length passed in was %d and max expected %d", data.length(), sizeof(m_eddystoneData)); - return; - } - memset(&m_eddystoneData, 0, sizeof(m_eddystoneData)); - memcpy(&m_eddystoneData, data.data(), data.length()); - lengthURL = data.length() - (sizeof(m_eddystoneData) - sizeof(m_eddystoneData.url)); -} // setData - -void BLEEddystoneURL::setUUID(BLEUUID l_uuid) { - beaconUUID = l_uuid.getNative()->uuid.uuid16; -} // setUUID - -void BLEEddystoneURL::setPower(int8_t advertisedTxPower) { - m_eddystoneData.advertisedTxPower = advertisedTxPower; -} // setPower - -void BLEEddystoneURL::setURL(std::string url) { - if (url.length() > sizeof(m_eddystoneData.url)) { - log_e("Unable to set the url ... length passed in was %d and max expected %d", url.length(), sizeof(m_eddystoneData.url)); - return; - } - memset(m_eddystoneData.url, 0, sizeof(m_eddystoneData.url)); - memcpy(m_eddystoneData.url, url.data(), url.length()); - lengthURL = url.length(); -} // setURL - - -#endif diff --git a/libraries/BLE/src/BLEEddystoneURL.h b/libraries/BLE/src/BLEEddystoneURL.h deleted file mode 100644 index 0b538c07..00000000 --- a/libraries/BLE/src/BLEEddystoneURL.h +++ /dev/null @@ -1,43 +0,0 @@ -/* - * BLEEddystoneURL.cpp - * - * Created on: Mar 12, 2018 - * Author: pcbreflux - */ - -#ifndef _BLEEddystoneURL_H_ -#define _BLEEddystoneURL_H_ -#include "BLEUUID.h" - -#define EDDYSTONE_URL_FRAME_TYPE 0x10 - -/** - * @brief Representation of a beacon. - * See: - * * https://github.com/google/eddystone - */ -class BLEEddystoneURL { -public: - BLEEddystoneURL(); - std::string getData(); - BLEUUID getUUID(); - int8_t getPower(); - std::string getURL(); - std::string getDecodedURL(); - void setData(std::string data); - void setUUID(BLEUUID l_uuid); - void setPower(int8_t advertisedTxPower); - void setURL(std::string url); - -private: - uint16_t beaconUUID; - uint8_t lengthURL; - struct { - uint8_t frameType; - int8_t advertisedTxPower; - uint8_t url[16]; - } __attribute__((packed)) m_eddystoneData; - -}; // BLEEddystoneURL - -#endif /* _BLEEddystoneURL_H_ */ diff --git a/libraries/BLE/src/BLEExceptions.cpp b/libraries/BLE/src/BLEExceptions.cpp deleted file mode 100644 index 549e4425..00000000 --- a/libraries/BLE/src/BLEExceptions.cpp +++ /dev/null @@ -1,9 +0,0 @@ -/* - * BLExceptions.cpp - * - * Created on: Nov 27, 2017 - * Author: kolban - */ - -//#include "BLEExceptions.h" - diff --git a/libraries/BLE/src/BLEExceptions.h b/libraries/BLE/src/BLEExceptions.h deleted file mode 100644 index ea9db855..00000000 --- a/libraries/BLE/src/BLEExceptions.h +++ /dev/null @@ -1,31 +0,0 @@ -/* - * BLExceptions.h - * - * Created on: Nov 27, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ -#define COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ -#include "sdkconfig.h" - -#if CONFIG_CXX_EXCEPTIONS != 1 -#error "C++ exception handling must be enabled within make menuconfig. See Compiler Options > Enable C++ Exceptions." -#endif - -#include - - -class BLEDisconnectedException : public std::exception { - const char* what() const throw () { - return "BLE Disconnected"; - } -}; - -class BLEUuidNotFoundException : public std::exception { - const char* what() const throw () { - return "No such UUID"; - } -}; - -#endif /* COMPONENTS_CPP_UTILS_BLEEXCEPTIONS_H_ */ diff --git a/libraries/BLE/src/BLEHIDDevice.cpp b/libraries/BLE/src/BLEHIDDevice.cpp deleted file mode 100644 index 5a02f496..00000000 --- a/libraries/BLE/src/BLEHIDDevice.cpp +++ /dev/null @@ -1,244 +0,0 @@ -/* - * BLEHIDDevice.cpp - * - * Created on: Jan 03, 2018 - * Author: chegewara - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLEHIDDevice.h" -#include "BLE2904.h" - - -BLEHIDDevice::BLEHIDDevice(BLEServer* server) { - /* - * Here we create mandatory services described in bluetooth specification - */ - m_deviceInfoService = server->createService(BLEUUID((uint16_t) 0x180a)); - m_hidService = server->createService(BLEUUID((uint16_t) 0x1812), 40); - m_batteryService = server->createService(BLEUUID((uint16_t) 0x180f)); - - /* - * Mandatory characteristic for device info service - */ - m_pnpCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a50, BLECharacteristic::PROPERTY_READ); - - /* - * Mandatory characteristics for HID service - */ - m_hidInfoCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4a, BLECharacteristic::PROPERTY_READ); - m_reportMapCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4b, BLECharacteristic::PROPERTY_READ); - m_hidControlCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4c, BLECharacteristic::PROPERTY_WRITE_NR); - m_protocolModeCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4e, BLECharacteristic::PROPERTY_WRITE_NR | BLECharacteristic::PROPERTY_READ); - - /* - * Mandatory battery level characteristic with notification and presence descriptor - */ - BLE2904* batteryLevelDescriptor = new BLE2904(); - batteryLevelDescriptor->setFormat(BLE2904::FORMAT_UINT8); - batteryLevelDescriptor->setNamespace(1); - batteryLevelDescriptor->setUnit(0x27ad); - - m_batteryLevelCharacteristic = m_batteryService->createCharacteristic((uint16_t) 0x2a19, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); - m_batteryLevelCharacteristic->addDescriptor(batteryLevelDescriptor); - m_batteryLevelCharacteristic->addDescriptor(new BLE2902()); - - /* - * This value is setup here because its default value in most usage cases, its very rare to use boot mode - * and we want to simplify library using as much as possible - */ - const uint8_t pMode[] = { 0x01 }; - protocolMode()->setValue((uint8_t*) pMode, 1); -} - -BLEHIDDevice::~BLEHIDDevice() { -} - -/* - * @brief - */ -void BLEHIDDevice::reportMap(uint8_t* map, uint16_t size) { - m_reportMapCharacteristic->setValue(map, size); -} - -/* - * @brief This function suppose to be called at the end, when we have created all characteristics we need to build HID service - */ -void BLEHIDDevice::startServices() { - m_deviceInfoService->start(); - m_hidService->start(); - m_batteryService->start(); -} - -/* - * @brief Create manufacturer characteristic (this characteristic is optional) - */ -BLECharacteristic* BLEHIDDevice::manufacturer() { - m_manufacturerCharacteristic = m_deviceInfoService->createCharacteristic((uint16_t) 0x2a29, BLECharacteristic::PROPERTY_READ); - return m_manufacturerCharacteristic; -} - -/* - * @brief Set manufacturer name - * @param [in] name manufacturer name - */ -void BLEHIDDevice::manufacturer(std::string name) { - m_manufacturerCharacteristic->setValue(name); -} - -/* - * @brief - */ -void BLEHIDDevice::pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version) { - uint8_t pnp[] = { sig, (uint8_t) (vid >> 8), (uint8_t) vid, (uint8_t) (pid >> 8), (uint8_t) pid, (uint8_t) (version >> 8), (uint8_t) version }; - m_pnpCharacteristic->setValue(pnp, sizeof(pnp)); -} - -/* - * @brief - */ -void BLEHIDDevice::hidInfo(uint8_t country, uint8_t flags) { - uint8_t info[] = { 0x11, 0x1, country, flags }; - m_hidInfoCharacteristic->setValue(info, sizeof(info)); -} - -/* - * @brief Create input report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID input report ID, the same as in report map for input object related to created characteristic - * @return pointer to new input report characteristic - */ -BLECharacteristic* BLEHIDDevice::inputReport(uint8_t reportID) { - BLECharacteristic* inputReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_NOTIFY); - BLEDescriptor* inputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); - BLE2902* p2902 = new BLE2902(); - inputReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - inputReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - p2902->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - - uint8_t desc1_val[] = { reportID, 0x01 }; - inputReportDescriptor->setValue((uint8_t*) desc1_val, 2); - inputReportCharacteristic->addDescriptor(p2902); - inputReportCharacteristic->addDescriptor(inputReportDescriptor); - - return inputReportCharacteristic; -} - -/* - * @brief Create output report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID Output report ID, the same as in report map for output object related to created characteristic - * @return Pointer to new output report characteristic - */ -BLECharacteristic* BLEHIDDevice::outputReport(uint8_t reportID) { - BLECharacteristic* outputReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); - BLEDescriptor* outputReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); - outputReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - outputReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - - uint8_t desc1_val[] = { reportID, 0x02 }; - outputReportDescriptor->setValue((uint8_t*) desc1_val, 2); - outputReportCharacteristic->addDescriptor(outputReportDescriptor); - - return outputReportCharacteristic; -} - -/* - * @brief Create feature report characteristic that need to be saved as new characteristic object so can be further used - * @param [in] reportID Feature report ID, the same as in report map for feature object related to created characteristic - * @return Pointer to new feature report characteristic - */ -BLECharacteristic* BLEHIDDevice::featureReport(uint8_t reportID) { - BLECharacteristic* featureReportCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a4d, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE); - BLEDescriptor* featureReportDescriptor = new BLEDescriptor(BLEUUID((uint16_t) 0x2908)); - - featureReportCharacteristic->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - featureReportDescriptor->setAccessPermissions(ESP_GATT_PERM_READ_ENCRYPTED | ESP_GATT_PERM_WRITE_ENCRYPTED); - - uint8_t desc1_val[] = { reportID, 0x03 }; - featureReportDescriptor->setValue((uint8_t*) desc1_val, 2); - featureReportCharacteristic->addDescriptor(featureReportDescriptor); - - return featureReportCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::bootInput() { - BLECharacteristic* bootInputCharacteristic = m_hidService->createCharacteristic((uint16_t) 0x2a22, BLECharacteristic::PROPERTY_NOTIFY); - bootInputCharacteristic->addDescriptor(new BLE2902()); - - return bootInputCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::bootOutput() { - return m_hidService->createCharacteristic((uint16_t) 0x2a32, BLECharacteristic::PROPERTY_READ | BLECharacteristic::PROPERTY_WRITE | BLECharacteristic::PROPERTY_WRITE_NR); -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::hidControl() { - return m_hidControlCharacteristic; -} - -/* - * @brief - */ -BLECharacteristic* BLEHIDDevice::protocolMode() { - return m_protocolModeCharacteristic; -} - -void BLEHIDDevice::setBatteryLevel(uint8_t level) { - m_batteryLevelCharacteristic->setValue(&level, 1); - m_batteryLevelCharacteristic->notify(); -} -/* - * @brief Returns battery level characteristic - * @ return battery level characteristic - *//* -BLECharacteristic* BLEHIDDevice::batteryLevel() { - return m_batteryLevelCharacteristic; -} - - - -BLECharacteristic* BLEHIDDevice::reportMap() { - return m_reportMapCharacteristic; -} - -BLECharacteristic* BLEHIDDevice::pnp() { - return m_pnpCharacteristic; -} - - -BLECharacteristic* BLEHIDDevice::hidInfo() { - return m_hidInfoCharacteristic; -} -*/ -/* - * @brief - */ -BLEService* BLEHIDDevice::deviceInfo() { - return m_deviceInfoService; -} - -/* - * @brief - */ -BLEService* BLEHIDDevice::hidService() { - return m_hidService; -} - -/* - * @brief - */ -BLEService* BLEHIDDevice::batteryService() { - return m_batteryService; -} - -#endif // CONFIG_BLUEDROID_ENABLED - diff --git a/libraries/BLE/src/BLEHIDDevice.h b/libraries/BLE/src/BLEHIDDevice.h deleted file mode 100644 index fead92b7..00000000 --- a/libraries/BLE/src/BLEHIDDevice.h +++ /dev/null @@ -1,75 +0,0 @@ -/* - * BLEHIDDevice.h - * - * Created on: Jan 03, 2018 - * Author: chegewara - */ - -#ifndef _BLEHIDDEVICE_H_ -#define _BLEHIDDEVICE_H_ - -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLEDescriptor.h" -#include "BLE2902.h" -#include "HIDTypes.h" - -#define GENERIC_HID 0x03C0 -#define HID_KEYBOARD 0x03C1 -#define HID_MOUSE 0x03C2 -#define HID_JOYSTICK 0x03C3 -#define HID_GAMEPAD 0x03C4 -#define HID_TABLET 0x03C5 -#define HID_CARD_READER 0x03C6 -#define HID_DIGITAL_PEN 0x03C7 -#define HID_BARCODE 0x03C8 - -class BLEHIDDevice { -public: - BLEHIDDevice(BLEServer*); - virtual ~BLEHIDDevice(); - - void reportMap(uint8_t* map, uint16_t); - void startServices(); - - BLEService* deviceInfo(); - BLEService* hidService(); - BLEService* batteryService(); - - BLECharacteristic* manufacturer(); - void manufacturer(std::string name); - //BLECharacteristic* pnp(); - void pnp(uint8_t sig, uint16_t vid, uint16_t pid, uint16_t version); - //BLECharacteristic* hidInfo(); - void hidInfo(uint8_t country, uint8_t flags); - //BLECharacteristic* batteryLevel(); - void setBatteryLevel(uint8_t level); - - - //BLECharacteristic* reportMap(); - BLECharacteristic* hidControl(); - BLECharacteristic* inputReport(uint8_t reportID); - BLECharacteristic* outputReport(uint8_t reportID); - BLECharacteristic* featureReport(uint8_t reportID); - BLECharacteristic* protocolMode(); - BLECharacteristic* bootInput(); - BLECharacteristic* bootOutput(); - -private: - BLEService* m_deviceInfoService; //0x180a - BLEService* m_hidService; //0x1812 - BLEService* m_batteryService = 0; //0x180f - - BLECharacteristic* m_manufacturerCharacteristic; //0x2a29 - BLECharacteristic* m_pnpCharacteristic; //0x2a50 - BLECharacteristic* m_hidInfoCharacteristic; //0x2a4a - BLECharacteristic* m_reportMapCharacteristic; //0x2a4b - BLECharacteristic* m_hidControlCharacteristic; //0x2a4c - BLECharacteristic* m_protocolModeCharacteristic; //0x2a4e - BLECharacteristic* m_batteryLevelCharacteristic; //0x2a19 -}; -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* _BLEHIDDEVICE_H_ */ diff --git a/libraries/BLE/src/BLERemoteCharacteristic.cpp b/libraries/BLE/src/BLERemoteCharacteristic.cpp deleted file mode 100644 index 0a0b057e..00000000 --- a/libraries/BLE/src/BLERemoteCharacteristic.cpp +++ /dev/null @@ -1,616 +0,0 @@ -/* - * BLERemoteCharacteristic.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#include "BLERemoteCharacteristic.h" - -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include -#include - -#include -//#include "BLEExceptions.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include "BLERemoteDescriptor.h" -#include "esp32-hal-log.h" - - -/** - * @brief Constructor. - * @param [in] handle The BLE server side handle of this characteristic. - * @param [in] uuid The UUID of this characteristic. - * @param [in] charProp The properties of this characteristic. - * @param [in] pRemoteService A reference to the remote service to which this remote characteristic pertains. - */ -BLERemoteCharacteristic::BLERemoteCharacteristic( - uint16_t handle, - BLEUUID uuid, - esp_gatt_char_prop_t charProp, - BLERemoteService* pRemoteService) { - log_v(">> BLERemoteCharacteristic: handle: %d 0x%d, uuid: %s", handle, handle, uuid.toString().c_str()); - m_handle = handle; - m_uuid = uuid; - m_charProp = charProp; - m_pRemoteService = pRemoteService; - m_notifyCallback = nullptr; - m_rawData = nullptr; - m_auth = ESP_GATT_AUTH_REQ_NONE; - - retrieveDescriptors(); // Get the descriptors for this characteristic - log_v("<< BLERemoteCharacteristic"); -} // BLERemoteCharacteristic - - -/** - *@brief Destructor. - */ -BLERemoteCharacteristic::~BLERemoteCharacteristic() { - removeDescriptors(); // Release resources for any descriptor information we may have allocated. -} // ~BLERemoteCharacteristic - - -/** - * @brief Does the characteristic support broadcasting? - * @return True if the characteristic supports broadcasting. - */ -bool BLERemoteCharacteristic::canBroadcast() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_BROADCAST) != 0; -} // canBroadcast - - -/** - * @brief Does the characteristic support indications? - * @return True if the characteristic supports indications. - */ -bool BLERemoteCharacteristic::canIndicate() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_INDICATE) != 0; -} // canIndicate - - -/** - * @brief Does the characteristic support notifications? - * @return True if the characteristic supports notifications. - */ -bool BLERemoteCharacteristic::canNotify() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_NOTIFY) != 0; -} // canNotify - - -/** - * @brief Does the characteristic support reading? - * @return True if the characteristic supports reading. - */ -bool BLERemoteCharacteristic::canRead() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_READ) != 0; -} // canRead - - -/** - * @brief Does the characteristic support writing? - * @return True if the characteristic supports writing. - */ -bool BLERemoteCharacteristic::canWrite() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE) != 0; -} // canWrite - - -/** - * @brief Does the characteristic support writing with no response? - * @return True if the characteristic supports writing with no response. - */ -bool BLERemoteCharacteristic::canWriteNoResponse() { - return (m_charProp & ESP_GATT_CHAR_PROP_BIT_WRITE_NR) != 0; -} // canWriteNoResponse - - -/* -static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { - if (id1.id.inst_id != id2.id.inst_id) { - return false; - } - if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { - return false; - } - return true; -} // compareSrvcId -*/ - -/* -static bool compareGattId(esp_gatt_id_t id1, esp_gatt_id_t id2) { - if (id1.inst_id != id2.inst_id) { - return false; - } - if (!BLEUUID(id1.uuid).equals(BLEUUID(id2.uuid))) { - return false; - } - return true; -} // compareCharId -*/ - - -/** - * @brief Handle GATT Client events. - * When an event arrives for a GATT client we give this characteristic the opportunity to - * take a look at it to see if there is interest in it. - * @param [in] event The type of event. - * @param [in] gattc_if The interface on which the event was received. - * @param [in] evtParam Payload data for the event. - * @returns N/A - */ -void BLERemoteCharacteristic::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) { - switch(event) { - // ESP_GATTC_NOTIFY_EVT - // - // notify - // - uint16_t conn_id - The connection identifier of the server. - // - esp_bd_addr_t remote_bda - The device address of the BLE server. - // - uint16_t handle - The handle of the characteristic for which the event is being received. - // - uint16_t value_len - The length of the received data. - // - uint8_t* value - The received data. - // - bool is_notify - True if this is a notify, false if it is an indicate. - // - // We have received a notification event which means that the server wishes us to know about a notification - // piece of data. What we must now do is find the characteristic with the associated handle and then - // invoke its notification callback (if it has one). - case ESP_GATTC_NOTIFY_EVT: { - if (evtParam->notify.handle != getHandle()) break; - if (m_notifyCallback != nullptr) { - log_d("Invoking callback for notification on characteristic %s", toString().c_str()); - m_notifyCallback(this, evtParam->notify.value, evtParam->notify.value_len, evtParam->notify.is_notify); - } // End we have a callback function ... - break; - } // ESP_GATTC_NOTIFY_EVT - - // ESP_GATTC_READ_CHAR_EVT - // This event indicates that the server has responded to the read request. - // - // read: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - // - uint8_t* value - // - uint16_t value_len - case ESP_GATTC_READ_CHAR_EVT: { - // If this event is not for us, then nothing further to do. - if (evtParam->read.handle != getHandle()) break; - - // At this point, we have determined that the event is for us, so now we save the value - // and unlock the semaphore to ensure that the requestor of the data can continue. - if (evtParam->read.status == ESP_GATT_OK) { - m_value = std::string((char*) evtParam->read.value, evtParam->read.value_len); - if(m_rawData != nullptr) free(m_rawData); - m_rawData = (uint8_t*) calloc(evtParam->read.value_len, sizeof(uint8_t)); - memcpy(m_rawData, evtParam->read.value, evtParam->read.value_len); - } else { - m_value = ""; - } - - m_semaphoreReadCharEvt.give(); - break; - } // ESP_GATTC_READ_CHAR_EVT - - // ESP_GATTC_REG_FOR_NOTIFY_EVT - // - // reg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - case ESP_GATTC_REG_FOR_NOTIFY_EVT: { - // If the request is not for this BLERemoteCharacteristic then move on to the next. - if (evtParam->reg_for_notify.handle != getHandle()) break; - - // We have processed the notify registration and can unlock the semaphore. - m_semaphoreRegForNotifyEvt.give(); - break; - } // ESP_GATTC_REG_FOR_NOTIFY_EVT - - // ESP_GATTC_UNREG_FOR_NOTIFY_EVT - // - // unreg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: { - if (evtParam->unreg_for_notify.handle != getHandle()) break; - // We have processed the notify un-registration and can unlock the semaphore. - m_semaphoreRegForNotifyEvt.give(); - break; - } // ESP_GATTC_UNREG_FOR_NOTIFY_EVT: - - // ESP_GATTC_WRITE_CHAR_EVT - // - // write: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - case ESP_GATTC_WRITE_CHAR_EVT: { - // Determine if this event is for us and, if not, pass onwards. - if (evtParam->write.handle != getHandle()) break; - - // There is nothing further we need to do here. This is merely an indication - // that the write has completed and we can unlock the caller. - m_semaphoreWriteCharEvt.give(); - break; - } // ESP_GATTC_WRITE_CHAR_EVT - - case ESP_GATTC_READ_DESCR_EVT: - case ESP_GATTC_WRITE_DESCR_EVT: - for (auto &myPair : m_descriptorMap) { - myPair.second->gattClientEventHandler( - event, gattc_if, evtParam); - } - break; - - default: - break; - } // End switch -}; // gattClientEventHandler - - -/** - * @brief Populate the descriptors (if any) for this characteristic. - */ -void BLERemoteCharacteristic::retrieveDescriptors() { - log_v(">> retrieveDescriptors() for characteristic: %s", getUUID().toString().c_str()); - - removeDescriptors(); // Remove any existing descriptors. - - // Loop over each of the descriptors within the service associated with this characteristic. - // For each descriptor we find, create a BLERemoteDescriptor instance. - uint16_t offset = 0; - esp_gattc_descr_elem_t result; - while(true) { - uint16_t count = 10; - esp_gatt_status_t status = ::esp_ble_gattc_get_all_descr( - getRemoteService()->getClient()->getGattcIf(), - getRemoteService()->getClient()->getConnId(), - getHandle(), - &result, - &count, - offset - ); - - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. - break; - } - - if (status != ESP_GATT_OK) { - log_e("esp_ble_gattc_get_all_descr: %s", BLEUtils::gattStatusToString(status).c_str()); - break; - } - - if (count == 0) break; - - log_d("Found a descriptor: Handle: %d, UUID: %s", result.handle, BLEUUID(result.uuid).toString().c_str()); - - // We now have a new characteristic ... let us add that to our set of known characteristics - BLERemoteDescriptor* pNewRemoteDescriptor = new BLERemoteDescriptor( - result.handle, - BLEUUID(result.uuid), - this - ); - - m_descriptorMap.insert(std::pair(pNewRemoteDescriptor->getUUID().toString(), pNewRemoteDescriptor)); - - offset++; - } // while true - //m_haveCharacteristics = true; // Remember that we have received the characteristics. - log_v("<< retrieveDescriptors(): Found %d descriptors.", offset); -} // getDescriptors - - -/** - * @brief Retrieve the map of descriptors keyed by UUID. - */ -std::map* BLERemoteCharacteristic::getDescriptors() { - return &m_descriptorMap; -} // getDescriptors - - -/** - * @brief Get the handle for this characteristic. - * @return The handle for this characteristic. - */ -uint16_t BLERemoteCharacteristic::getHandle() { - //log_v(">> getHandle: Characteristic: %s", getUUID().toString().c_str()); - //log_v("<< getHandle: %d 0x%.2x", m_handle, m_handle); - return m_handle; -} // getHandle - - -/** - * @brief Get the descriptor instance with the given UUID that belongs to this characteristic. - * @param [in] uuid The UUID of the descriptor to find. - * @return The Remote descriptor (if present) or null if not present. - */ -BLERemoteDescriptor* BLERemoteCharacteristic::getDescriptor(BLEUUID uuid) { - log_v(">> getDescriptor: uuid: %s", uuid.toString().c_str()); - std::string v = uuid.toString(); - for (auto &myPair : m_descriptorMap) { - if (myPair.first == v) { - log_v("<< getDescriptor: found"); - return myPair.second; - } - } - log_v("<< getDescriptor: Not found"); - return nullptr; -} // getDescriptor - - -/** - * @brief Get the remote service associated with this characteristic. - * @return The remote service associated with this characteristic. - */ -BLERemoteService* BLERemoteCharacteristic::getRemoteService() { - return m_pRemoteService; -} // getRemoteService - - -/** - * @brief Get the UUID for this characteristic. - * @return The UUID for this characteristic. - */ -BLEUUID BLERemoteCharacteristic::getUUID() { - return m_uuid; -} // getUUID - - -/** - * @brief Read an unsigned 16 bit value - * @return The unsigned 16 bit value. - */ -uint16_t BLERemoteCharacteristic::readUInt16() { - std::string value = readValue(); - if (value.length() >= 2) { - return *(uint16_t*)(value.data()); - } - return 0; -} // readUInt16 - - -/** - * @brief Read an unsigned 32 bit value. - * @return the unsigned 32 bit value. - */ -uint32_t BLERemoteCharacteristic::readUInt32() { - std::string value = readValue(); - if (value.length() >= 4) { - return *(uint32_t*)(value.data()); - } - return 0; -} // readUInt32 - - -/** - * @brief Read a byte value - * @return The value as a byte - */ -uint8_t BLERemoteCharacteristic::readUInt8() { - std::string value = readValue(); - if (value.length() >= 1) { - return (uint8_t)value[0]; - } - return 0; -} // readUInt8 - -/** - * @brief Read a float value. - * @return the float value. - */ -float BLERemoteCharacteristic::readFloat() { - std::string value = readValue(); - if (value.length() >= 4) { - return *(float*)(value.data()); - } - return 0.0; -} // readFloat - -/** - * @brief Read the value of the remote characteristic. - * @return The value of the remote characteristic. - */ -std::string BLERemoteCharacteristic::readValue() { - log_v(">> readValue(): uuid: %s, handle: %d 0x%.2x", getUUID().toString().c_str(), getHandle(), getHandle()); - - // Check to see that we are connected. - if (!getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return std::string(); - } - - m_semaphoreReadCharEvt.take("readValue"); - - // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. - // This is an asynchronous request which means that we must block waiting for the response - // to become available. - esp_err_t errRc = ::esp_ble_gattc_read_char( - m_pRemoteService->getClient()->getGattcIf(), - m_pRemoteService->getClient()->getConnId(), // The connection ID to the BLE server - getHandle(), // The handle of this characteristic - m_auth); // Security - - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return ""; - } - - // Block waiting for the event that indicates that the read has completed. When it has, the std::string found - // in m_value will contain our data. - m_semaphoreReadCharEvt.wait("readValue"); - - log_v("<< readValue(): length: %d", m_value.length()); - return m_value; -} // readValue - - -/** - * @brief Register for notifications. - * @param [in] notifyCallback A callback to be invoked for a notification. If NULL is provided then we are - * unregistering a notification. - * @return N/A. - */ -void BLERemoteCharacteristic::registerForNotify(notify_callback notifyCallback, bool notifications) { - log_v(">> registerForNotify(): %s", toString().c_str()); - - m_notifyCallback = notifyCallback; // Save the notification callback. - - m_semaphoreRegForNotifyEvt.take("registerForNotify"); - - if (notifyCallback != nullptr) { // If we have a callback function, then this is a registration. - esp_err_t errRc = ::esp_ble_gattc_register_for_notify( - m_pRemoteService->getClient()->getGattcIf(), - *m_pRemoteService->getClient()->getPeerAddress().getNative(), - getHandle() - ); - - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_register_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - - uint8_t val[] = {0x01, 0x00}; - if(!notifications) val[0] = 0x02; - BLERemoteDescriptor* desc = getDescriptor(BLEUUID((uint16_t)0x2902)); - if (desc != nullptr) - desc->writeValue(val, 2, true); - } // End Register - else { // If we weren't passed a callback function, then this is an unregistration. - esp_err_t errRc = ::esp_ble_gattc_unregister_for_notify( - m_pRemoteService->getClient()->getGattcIf(), - *m_pRemoteService->getClient()->getPeerAddress().getNative(), - getHandle() - ); - - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_unregister_for_notify: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - } - - uint8_t val[] = {0x00, 0x00}; - BLERemoteDescriptor* desc = getDescriptor((uint16_t)0x2902); - if (desc != nullptr) - desc->writeValue(val, 2, true); - } // End Unregister - - m_semaphoreRegForNotifyEvt.wait("registerForNotify"); - - log_v("<< registerForNotify()"); -} // registerForNotify - - -/** - * @brief Delete the descriptors in the descriptor map. - * We maintain a map called m_descriptorMap that contains pointers to BLERemoteDescriptors - * object references. Since we allocated these in this class, we are also responsible for deleteing - * them. This method does just that. - * @return N/A. - */ -void BLERemoteCharacteristic::removeDescriptors() { - // Iterate through all the descriptors releasing their storage and erasing them from the map. - for (auto &myPair : m_descriptorMap) { - m_descriptorMap.erase(myPair.first); - delete myPair.second; - } - m_descriptorMap.clear(); // Technically not neeeded, but just to be sure. -} // removeCharacteristics - - -/** - * @brief Convert a BLERemoteCharacteristic to a string representation; - * @return a String representation. - */ -std::string BLERemoteCharacteristic::toString() { - std::string res = "Characteristic: uuid: " + m_uuid.toString(); - char val[6]; - res += ", handle: "; - snprintf(val, sizeof(val), "%d", getHandle()); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", getHandle()); - res += val; - res += ", props: " + BLEUtils::characteristicPropertiesToString(m_charProp); - return res; -} // toString - - -/** - * @brief Write the new value for the characteristic. - * @param [in] newValue The new value to write. - * @param [in] response Do we expect a response? - * @return N/A. - */ -void BLERemoteCharacteristic::writeValue(std::string newValue, bool response) { - writeValue((uint8_t*)newValue.data(), newValue.length(), response); -} // writeValue - - -/** - * @brief Write the new value for the characteristic. - * - * This is a convenience function. Many BLE characteristics are a single byte of data. - * @param [in] newValue The new byte value to write. - * @param [in] response Whether we require a response from the write. - * @return N/A. - */ -void BLERemoteCharacteristic::writeValue(uint8_t newValue, bool response) { - writeValue(&newValue, 1, response); -} // writeValue - - -/** - * @brief Write the new value for the characteristic from a data buffer. - * @param [in] data A pointer to a data buffer. - * @param [in] length The length of the data in the data buffer. - * @param [in] response Whether we require a response from the write. - */ -void BLERemoteCharacteristic::writeValue(uint8_t* data, size_t length, bool response) { - // writeValue(std::string((char*)data, length), response); - log_v(">> writeValue(), length: %d", length); - - // Check to see that we are connected. - if (!getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return; - } - - m_semaphoreWriteCharEvt.take("writeValue"); - // Invoke the ESP-IDF API to perform the write. - esp_err_t errRc = ::esp_ble_gattc_write_char( - m_pRemoteService->getClient()->getGattcIf(), - m_pRemoteService->getClient()->getConnId(), - getHandle(), - length, - data, - response?ESP_GATT_WRITE_TYPE_RSP:ESP_GATT_WRITE_TYPE_NO_RSP, - m_auth - ); - - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_write_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreWriteCharEvt.wait("writeValue"); - - log_v("<< writeValue"); -} // writeValue - -/** - * @brief Read raw data from remote characteristic as hex bytes - * @return return pointer data read - */ -uint8_t* BLERemoteCharacteristic::readRawData() { - return m_rawData; -} - -/** - * @brief Set authentication request type for characteristic - * @param [in] auth Authentication request type. - */ -void BLERemoteCharacteristic::setAuth(esp_gatt_auth_req_t auth) { - m_auth = auth; -} - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteCharacteristic.h b/libraries/BLE/src/BLERemoteCharacteristic.h deleted file mode 100644 index 5f7d4d82..00000000 --- a/libraries/BLE/src/BLERemoteCharacteristic.h +++ /dev/null @@ -1,87 +0,0 @@ -/* - * BLERemoteCharacteristic.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include - -#include - -#include "BLERemoteService.h" -#include "BLERemoteDescriptor.h" -#include "BLEUUID.h" -#include "RTOS.h" - -class BLERemoteService; -class BLERemoteDescriptor; -typedef void (*notify_callback)(BLERemoteCharacteristic* pBLERemoteCharacteristic, uint8_t* pData, size_t length, bool isNotify); - -/** - * @brief A model of a remote %BLE characteristic. - */ -class BLERemoteCharacteristic { -public: - ~BLERemoteCharacteristic(); - - // Public member functions - bool canBroadcast(); - bool canIndicate(); - bool canNotify(); - bool canRead(); - bool canWrite(); - bool canWriteNoResponse(); - BLERemoteDescriptor* getDescriptor(BLEUUID uuid); - std::map* getDescriptors(); - uint16_t getHandle(); - BLEUUID getUUID(); - std::string readValue(); - uint8_t readUInt8(); - uint16_t readUInt16(); - uint32_t readUInt32(); - float readFloat(); - void registerForNotify(notify_callback _callback, bool notifications = true); - void writeValue(uint8_t* data, size_t length, bool response = false); - void writeValue(std::string newValue, bool response = false); - void writeValue(uint8_t newValue, bool response = false); - std::string toString(); - uint8_t* readRawData(); - void setAuth(esp_gatt_auth_req_t auth); - -private: - BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService); - friend class BLEClient; - friend class BLERemoteService; - friend class BLERemoteDescriptor; - - // Private member functions - void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam); - - BLERemoteService* getRemoteService(); - void removeDescriptors(); - void retrieveDescriptors(); - - // Private properties - BLEUUID m_uuid; - esp_gatt_char_prop_t m_charProp; - esp_gatt_auth_req_t m_auth; - uint16_t m_handle; - BLERemoteService* m_pRemoteService; - FreeRTOS::Semaphore m_semaphoreReadCharEvt = FreeRTOS::Semaphore("ReadCharEvt"); - FreeRTOS::Semaphore m_semaphoreRegForNotifyEvt = FreeRTOS::Semaphore("RegForNotifyEvt"); - FreeRTOS::Semaphore m_semaphoreWriteCharEvt = FreeRTOS::Semaphore("WriteCharEvt"); - std::string m_value; - uint8_t *m_rawData; - notify_callback m_notifyCallback; - - // We maintain a map of descriptors owned by this characteristic keyed by a string representation of the UUID. - std::map m_descriptorMap; -}; // BLERemoteCharacteristic -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTECHARACTERISTIC_H_ */ diff --git a/libraries/BLE/src/BLERemoteDescriptor.cpp b/libraries/BLE/src/BLERemoteDescriptor.cpp deleted file mode 100644 index 1538741d..00000000 --- a/libraries/BLE/src/BLERemoteDescriptor.cpp +++ /dev/null @@ -1,204 +0,0 @@ -/* - * BLERemoteDescriptor.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include "BLERemoteDescriptor.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -BLERemoteDescriptor::BLERemoteDescriptor( - uint16_t handle, - BLEUUID uuid, - BLERemoteCharacteristic* pRemoteCharacteristic) { - - m_handle = handle; - m_uuid = uuid; - m_pRemoteCharacteristic = pRemoteCharacteristic; - m_auth = ESP_GATT_AUTH_REQ_NONE; -} - - -/** - * @brief Retrieve the handle associated with this remote descriptor. - * @return The handle associated with this remote descriptor. - */ -uint16_t BLERemoteDescriptor::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Get the characteristic that owns this descriptor. - * @return The characteristic that owns this descriptor. - */ -BLERemoteCharacteristic* BLERemoteDescriptor::getRemoteCharacteristic() { - return m_pRemoteCharacteristic; -} // getRemoteCharacteristic - - -/** - * @brief Retrieve the UUID associated this remote descriptor. - * @return The UUID associated this remote descriptor. - */ -BLEUUID BLERemoteDescriptor::getUUID() { - return m_uuid; -} // getUUID - -void BLERemoteDescriptor::gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam) { - switch(event) { - case ESP_GATTC_READ_DESCR_EVT: - if (evtParam->read.handle != getHandle()) - break; - m_semaphoreReadDescrEvt.give(); - break; - - case ESP_GATTC_WRITE_DESCR_EVT: - if (evtParam->write.handle != getHandle()) - break; - m_semaphoreWriteDescrEvt.give(); - break; - default: - break; - } -} - -std::string BLERemoteDescriptor::readValue() { - log_v(">> readValue: %s", toString().c_str()); - - // Check to see that we are connected. - if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return std::string(); - } - - m_semaphoreReadDescrEvt.take("readValue"); - - // Ask the BLE subsystem to retrieve the value for the remote hosted characteristic. - esp_err_t errRc = ::esp_ble_gattc_read_char_descr( - m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), - m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), // The connection ID to the BLE server - getHandle(), // The handle of this characteristic - m_auth); // Security - - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_read_char: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return ""; - } - - // Block waiting for the event that indicates that the read has completed. When it has, the std::string found - // in m_value will contain our data. - m_semaphoreReadDescrEvt.wait("readValue"); - - log_v("<< readValue(): length: %d", m_value.length()); - return m_value; -} // readValue - - -uint8_t BLERemoteDescriptor::readUInt8() { - std::string value = readValue(); - if (value.length() >= 1) { - return (uint8_t) value[0]; - } - return 0; -} // readUInt8 - - -uint16_t BLERemoteDescriptor::readUInt16() { - std::string value = readValue(); - if (value.length() >= 2) { - return *(uint16_t*) value.data(); - } - return 0; -} // readUInt16 - - -uint32_t BLERemoteDescriptor::readUInt32() { - std::string value = readValue(); - if (value.length() >= 4) { - return *(uint32_t*) value.data(); - } - return 0; -} // readUInt32 - - -/** - * @brief Return a string representation of this BLE Remote Descriptor. - * @retun A string representation of this BLE Remote Descriptor. - */ -std::string BLERemoteDescriptor::toString() { - char val[6]; - snprintf(val, sizeof(val), "%d", getHandle()); - std::string res = "handle: "; - res += val; - res += ", uuid: " + getUUID().toString(); - return res; -} // toString - - -/** - * @brief Write data to the BLE Remote Descriptor. - * @param [in] data The data to send to the remote descriptor. - * @param [in] length The length of the data to send. - * @param [in] response True if we expect a response. - */ -void BLERemoteDescriptor::writeValue(uint8_t* data, size_t length, bool response) { - log_v(">> writeValue: %s", toString().c_str()); - // Check to see that we are connected. - if (!getRemoteCharacteristic()->getRemoteService()->getClient()->isConnected()) { - log_e("Disconnected"); - return; - } - - m_semaphoreWriteDescrEvt.take("writeValue"); - - esp_err_t errRc = ::esp_ble_gattc_write_char_descr( - m_pRemoteCharacteristic->getRemoteService()->getClient()->getGattcIf(), - m_pRemoteCharacteristic->getRemoteService()->getClient()->getConnId(), - getHandle(), - length, // Data length - data, // Data - response ? ESP_GATT_WRITE_TYPE_RSP : ESP_GATT_WRITE_TYPE_NO_RSP, - m_auth - ); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_write_char_descr: %d", errRc); - } - - m_semaphoreWriteDescrEvt.wait("writeValue"); - log_v("<< writeValue"); -} // writeValue - - -/** - * @brief Write data represented as a string to the BLE Remote Descriptor. - * @param [in] newValue The data to send to the remote descriptor. - * @param [in] response True if we expect a response. - */ -void BLERemoteDescriptor::writeValue(std::string newValue, bool response) { - writeValue((uint8_t*) newValue.data(), newValue.length(), response); -} // writeValue - - -/** - * @brief Write a byte value to the Descriptor. - * @param [in] The single byte to write. - * @param [in] True if we expect a response. - */ -void BLERemoteDescriptor::writeValue(uint8_t newValue, bool response) { - writeValue(&newValue, 1, response); -} // writeValue - -/** - * @brief Set authentication request type for characteristic - * @param [in] auth Authentication request type. - */ -void BLERemoteDescriptor::setAuth(esp_gatt_auth_req_t auth) { - m_auth = auth; -} - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteDescriptor.h b/libraries/BLE/src/BLERemoteDescriptor.h deleted file mode 100644 index af370e43..00000000 --- a/libraries/BLE/src/BLERemoteDescriptor.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * BLERemoteDescriptor.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include - -#include - -#include "BLERemoteCharacteristic.h" -#include "BLEUUID.h" -#include "RTOS.h" - -class BLERemoteCharacteristic; -/** - * @brief A model of remote %BLE descriptor. - */ -class BLERemoteDescriptor { -public: - uint16_t getHandle(); - BLERemoteCharacteristic* getRemoteCharacteristic(); - BLEUUID getUUID(); - std::string readValue(void); - uint8_t readUInt8(void); - uint16_t readUInt16(void); - uint32_t readUInt32(void); - std::string toString(void); - void writeValue(uint8_t* data, size_t length, bool response = false); - void writeValue(std::string newValue, bool response = false); - void writeValue(uint8_t newValue, bool response = false); - void setAuth(esp_gatt_auth_req_t auth); - void gattClientEventHandler(esp_gattc_cb_event_t event, esp_gatt_if_t gattc_if, esp_ble_gattc_cb_param_t* evtParam); - -private: - friend class BLERemoteCharacteristic; - BLERemoteDescriptor( - uint16_t handle, - BLEUUID uuid, - BLERemoteCharacteristic* pRemoteCharacteristic - ); - uint16_t m_handle; // Server handle of this descriptor. - BLEUUID m_uuid; // UUID of this descriptor. - std::string m_value; // Last received value of the descriptor. - BLERemoteCharacteristic* m_pRemoteCharacteristic; // Reference to the Remote characteristic of which this descriptor is associated. - FreeRTOS::Semaphore m_semaphoreReadDescrEvt = FreeRTOS::Semaphore("ReadDescrEvt"); - FreeRTOS::Semaphore m_semaphoreWriteDescrEvt = FreeRTOS::Semaphore("WriteDescrEvt"); - esp_gatt_auth_req_t m_auth; - - -}; -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTEDESCRIPTOR_H_ */ diff --git a/libraries/BLE/src/BLERemoteService.cpp b/libraries/BLE/src/BLERemoteService.cpp deleted file mode 100644 index 9c6396b9..00000000 --- a/libraries/BLE/src/BLERemoteService.cpp +++ /dev/null @@ -1,362 +0,0 @@ -/* - * BLERemoteService.cpp - * - * Created on: Jul 8, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include -#include "BLERemoteService.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include -#include "esp32-hal-log.h" - -#pragma GCC diagnostic warning "-Wunused-but-set-parameter" - -BLERemoteService::BLERemoteService( - esp_gatt_id_t srvcId, - BLEClient* pClient, - uint16_t startHandle, - uint16_t endHandle - ) { - - log_v(">> BLERemoteService()"); - m_srvcId = srvcId; - m_pClient = pClient; - m_uuid = BLEUUID(m_srvcId); - m_haveCharacteristics = false; - m_startHandle = startHandle; - m_endHandle = endHandle; - - log_v("<< BLERemoteService()"); -} - - -BLERemoteService::~BLERemoteService() { - removeCharacteristics(); -} - -/* -static bool compareSrvcId(esp_gatt_srvc_id_t id1, esp_gatt_srvc_id_t id2) { - if (id1.id.inst_id != id2.id.inst_id) { - return false; - } - if (!BLEUUID(id1.id.uuid).equals(BLEUUID(id2.id.uuid))) { - return false; - } - return true; -} // compareSrvcId -*/ - -/** - * @brief Handle GATT Client events - */ -void BLERemoteService::gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - switch (event) { - // - // ESP_GATTC_GET_CHAR_EVT - // - // get_char: - // - esp_gatt_status_t status - // - uin1t6_t conn_id - // - esp_gatt_srvc_id_t srvc_id - // - esp_gatt_id_t char_id - // - esp_gatt_char_prop_t char_prop - // - /* - case ESP_GATTC_GET_CHAR_EVT: { - // Is this event for this service? If yes, then the local srvc_id and the event srvc_id will be - // the same. - if (compareSrvcId(m_srvcId, evtParam->get_char.srvc_id) == false) { - break; - } - - // If the status is NOT OK then we have a problem and continue. - if (evtParam->get_char.status != ESP_GATT_OK) { - m_semaphoreGetCharEvt.give(); - break; - } - - // This is an indication that we now have the characteristic details for a characteristic owned - // by this service so remember it. - m_characteristicMap.insert(std::pair( - BLEUUID(evtParam->get_char.char_id.uuid).toString(), - new BLERemoteCharacteristic(evtParam->get_char.char_id, evtParam->get_char.char_prop, this) )); - - - // Now that we have received a characteristic, lets ask for the next one. - esp_err_t errRc = ::esp_ble_gattc_get_characteristic( - m_pClient->getGattcIf(), - m_pClient->getConnId(), - &m_srvcId, - &evtParam->get_char.char_id); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_get_characteristic: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - break; - } - - //m_semaphoreGetCharEvt.give(); - break; - } // ESP_GATTC_GET_CHAR_EVT -*/ - default: - break; - } // switch - - // Send the event to each of the characteristics owned by this service. - for (auto &myPair : m_characteristicMapByHandle) { - myPair.second->gattClientEventHandler(event, gattc_if, evtParam); - } -} // gattClientEventHandler - - -/** - * @brief Get the remote characteristic object for the characteristic UUID. - * @param [in] uuid Remote characteristic uuid. - * @return Reference to the remote characteristic object. - * @throws BLEUuidNotFoundException - */ -BLERemoteCharacteristic* BLERemoteService::getCharacteristic(const char* uuid) { - return getCharacteristic(BLEUUID(uuid)); -} // getCharacteristic - -/** - * @brief Get the characteristic object for the UUID. - * @param [in] uuid Characteristic uuid. - * @return Reference to the characteristic object. - * @throws BLEUuidNotFoundException - */ -BLERemoteCharacteristic* BLERemoteService::getCharacteristic(BLEUUID uuid) { -// Design -// ------ -// We wish to retrieve the characteristic given its UUID. It is possible that we have not yet asked the -// device what characteristics it has in which case we have nothing to match against. If we have not -// asked the device about its characteristics, then we do that now. Once we get the results we can then -// examine the characteristics map to see if it has the characteristic we are looking for. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - std::string v = uuid.toString(); - for (auto &myPair : m_characteristicMap) { - if (myPair.first == v) { - return myPair.second; - } - } - // throw new BLEUuidNotFoundException(); // <-- we dont want exception here, which will cause app crash, we want to search if any characteristic can be found one after another - return nullptr; -} // getCharacteristic - - -/** - * @brief Retrieve all the characteristics for this service. - * This function will not return until we have all the characteristics. - * @return N/A - */ -void BLERemoteService::retrieveCharacteristics() { - log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); - - removeCharacteristics(); // Forget any previous characteristics. - - uint16_t offset = 0; - esp_gattc_char_elem_t result; - while (true) { - uint16_t count = 1; // only room for 1 result allocated, so go one by one - esp_gatt_status_t status = ::esp_ble_gattc_get_all_char( - getClient()->getGattcIf(), - getClient()->getConnId(), - m_startHandle, - m_endHandle, - &result, - &count, - offset - ); - - if (status == ESP_GATT_INVALID_OFFSET) { // We have reached the end of the entries. - break; - } - - if (status != ESP_GATT_OK) { // If we got an error, end. - log_e("esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str()); - break; - } - - if (count == 0) { // If we failed to get any new records, end. - break; - } - - log_d("Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str()); - - // We now have a new characteristic ... let us add that to our set of known characteristics - BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic( - result.char_handle, - BLEUUID(result.uuid), - result.properties, - this - ); - - m_characteristicMap.insert(std::pair(pNewRemoteCharacteristic->getUUID().toString(), pNewRemoteCharacteristic)); - m_characteristicMapByHandle.insert(std::pair(result.char_handle, pNewRemoteCharacteristic)); - offset++; // Increment our count of number of descriptors found. - } // Loop forever (until we break inside the loop). - - m_haveCharacteristics = true; // Remember that we have received the characteristics. - log_v("<< getCharacteristics()"); -} // getCharacteristics - - -/** - * @brief Retrieve a map of all the characteristics of this service. - * @return A map of all the characteristics of this service. - */ -std::map* BLERemoteService::getCharacteristics() { - log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); - // If is possible that we have not read the characteristics associated with the service so do that - // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking - // call and does not return until all the characteristics are available. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - log_v("<< getCharacteristics() for service: %s", getUUID().toString().c_str()); - return &m_characteristicMap; -} // getCharacteristics - -/** - * @brief Retrieve a map of all the characteristics of this service. - * @return A map of all the characteristics of this service. - */ -std::map* BLERemoteService::getCharacteristicsByHandle() { - // If is possible that we have not read the characteristics associated with the service so do that - // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking - // call and does not return until all the characteristics are available. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - return &m_characteristicMapByHandle; -} // getCharacteristicsByHandle - -/** - * @brief This function is designed to get characteristics map when we have multiple characteristics with the same UUID - */ -void BLERemoteService::getCharacteristics(std::map** pCharacteristicMap) { - log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str()); - // If is possible that we have not read the characteristics associated with the service so do that - // now. The request to retrieve the characteristics by calling "retrieveCharacteristics" is a blocking - // call and does not return until all the characteristics are available. - if (!m_haveCharacteristics) { - retrieveCharacteristics(); - } - log_v("<< getCharacteristics() for service: %s", getUUID().toString().c_str()); - *pCharacteristicMap = &m_characteristicMapByHandle; -} // Get the characteristics map. - -/** - * @brief Get the client associated with this service. - * @return A reference to the client associated with this service. - */ -BLEClient* BLERemoteService::getClient() { - return m_pClient; -} // getClient - - -uint16_t BLERemoteService::getEndHandle() { - return m_endHandle; -} // getEndHandle - - -esp_gatt_id_t* BLERemoteService::getSrvcId() { - return &m_srvcId; -} // getSrvcId - - -uint16_t BLERemoteService::getStartHandle() { - return m_startHandle; -} // getStartHandle - - -uint16_t BLERemoteService::getHandle() { - log_v(">> getHandle: service: %s", getUUID().toString().c_str()); - log_v("<< getHandle: %d 0x%.2x", getStartHandle(), getStartHandle()); - return getStartHandle(); -} // getHandle - - -BLEUUID BLERemoteService::getUUID() { - return m_uuid; -} - -/** - * @brief Read the value of a characteristic associated with this service. - */ -std::string BLERemoteService::getValue(BLEUUID characteristicUuid) { - log_v(">> readValue: uuid: %s", characteristicUuid.toString().c_str()); - std::string ret = getCharacteristic(characteristicUuid)->readValue(); - log_v("<< readValue"); - return ret; -} // readValue - - - -/** - * @brief Delete the characteristics in the characteristics map. - * We maintain a map called m_characteristicsMap that contains pointers to BLERemoteCharacteristic - * object references. Since we allocated these in this class, we are also responsible for deleteing - * them. This method does just that. - * @return N/A. - */ -void BLERemoteService::removeCharacteristics() { - m_characteristicMap.clear(); // Clear the map - for (auto &myPair : m_characteristicMapByHandle) { - delete myPair.second; - // delete the characteristics only once - } - m_characteristicMapByHandle.clear(); // Clear the map -} // removeCharacteristics - - -/** - * @brief Set the value of a characteristic. - * @param [in] characteristicUuid The characteristic to set. - * @param [in] value The value to set. - * @throws BLEUuidNotFound - */ -void BLERemoteService::setValue(BLEUUID characteristicUuid, std::string value) { - log_v(">> setValue: uuid: %s", characteristicUuid.toString().c_str()); - getCharacteristic(characteristicUuid)->writeValue(value); - log_v("<< setValue"); -} // setValue - - -/** - * @brief Create a string representation of this remote service. - * @return A string representation of this remote service. - */ -std::string BLERemoteService::toString() { - std::string res = "Service: uuid: " + m_uuid.toString(); - char val[6]; - res += ", start_handle: "; - snprintf(val, sizeof(val), "%d", m_startHandle); - res += val; - snprintf(val, sizeof(val), "%04x", m_startHandle); - res += " 0x"; - res += val; - res += ", end_handle: "; - snprintf(val, sizeof(val), "%d", m_endHandle); - res += val; - snprintf(val, sizeof(val), "%04x", m_endHandle); - res += " 0x"; - res += val; - for (auto &myPair : m_characteristicMap) { - res += "\n" + myPair.second->toString(); - // myPair.second is the value - } - return res; -} // toString - - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLERemoteService.h b/libraries/BLE/src/BLERemoteService.h deleted file mode 100644 index 64aff5a1..00000000 --- a/libraries/BLE/src/BLERemoteService.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * BLERemoteService.h - * - * Created on: Jul 8, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ -#define COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include - -#include "BLEClient.h" -#include "BLERemoteCharacteristic.h" -#include "BLEUUID.h" -#include "RTOS.h" - -class BLEClient; -class BLERemoteCharacteristic; - - -/** - * @brief A model of a remote %BLE service. - */ -class BLERemoteService { -public: - virtual ~BLERemoteService(); - - // Public methods - BLERemoteCharacteristic* getCharacteristic(const char* uuid); // Get the specified characteristic reference. - BLERemoteCharacteristic* getCharacteristic(BLEUUID uuid); // Get the specified characteristic reference. - BLERemoteCharacteristic* getCharacteristic(uint16_t uuid); // Get the specified characteristic reference. - std::map* getCharacteristics(); - std::map* getCharacteristicsByHandle(); // Get the characteristics map. - void getCharacteristics(std::map** pCharacteristicMap); - - BLEClient* getClient(void); // Get a reference to the client associated with this service. - uint16_t getHandle(); // Get the handle of this service. - BLEUUID getUUID(void); // Get the UUID of this service. - std::string getValue(BLEUUID characteristicUuid); // Get the value of a characteristic. - void setValue(BLEUUID characteristicUuid, std::string value); // Set the value of a characteristic. - std::string toString(void); - -private: - // Private constructor ... never meant to be created by a user application. - BLERemoteService(esp_gatt_id_t srvcId, BLEClient* pClient, uint16_t startHandle, uint16_t endHandle); - - // Friends - friend class BLEClient; - friend class BLERemoteCharacteristic; - - // Private methods - void retrieveCharacteristics(void); // Retrieve the characteristics from the BLE Server. - esp_gatt_id_t* getSrvcId(void); - uint16_t getStartHandle(); // Get the start handle for this service. - uint16_t getEndHandle(); // Get the end handle for this service. - - void gattClientEventHandler( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam); - - void removeCharacteristics(); - - // Properties - - // We maintain a map of characteristics owned by this service keyed by a string representation of the UUID. - std::map m_characteristicMap; - - // We maintain a map of characteristics owned by this service keyed by a handle. - std::map m_characteristicMapByHandle; - - bool m_haveCharacteristics; // Have we previously obtained the characteristics. - BLEClient* m_pClient; - FreeRTOS::Semaphore m_semaphoreGetCharEvt = FreeRTOS::Semaphore("GetCharEvt"); - esp_gatt_id_t m_srvcId; - BLEUUID m_uuid; // The UUID of this service. - uint16_t m_startHandle; // The starting handle of this service. - uint16_t m_endHandle; // The ending handle of this service. -}; // BLERemoteService - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEREMOTESERVICE_H_ */ diff --git a/libraries/BLE/src/BLEScan.cpp b/libraries/BLE/src/BLEScan.cpp deleted file mode 100644 index fd16c899..00000000 --- a/libraries/BLE/src/BLEScan.cpp +++ /dev/null @@ -1,333 +0,0 @@ -/* - * BLEScan.cpp - * - * Created on: Jul 1, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - - -#include - -#include - -#include "BLEAdvertisedDevice.h" -#include "BLEScan.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -/** - * Constructor - */ -BLEScan::BLEScan() { - memset(&m_scan_params, 0, sizeof(m_scan_params)); // Initialize all params - m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; // Default is a passive scan. - m_scan_params.own_addr_type = BLE_ADDR_TYPE_PUBLIC; - m_scan_params.scan_filter_policy = BLE_SCAN_FILTER_ALLOW_ALL; - m_scan_params.scan_duplicate = BLE_SCAN_DUPLICATE_DISABLE; - m_pAdvertisedDeviceCallbacks = nullptr; - m_stopped = true; - m_wantDuplicates = false; - m_shouldParse = true; - setInterval(100); - setWindow(100); -} // BLEScan - - -/** - * @brief Handle GAP events related to scans. - * @param [in] event The event type for this event. - * @param [in] param Parameter data for this event. - */ -void BLEScan::handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param) { - - switch(event) { - - // --------------------------- - // scan_rst: - // esp_gap_search_evt_t search_evt - // esp_bd_addr_t bda - // esp_bt_dev_type_t dev_type - // esp_ble_addr_type_t ble_addr_type - // esp_ble_evt_type_t ble_evt_type - // int rssi - // uint8_t ble_adv[ESP_BLE_ADV_DATA_LEN_MAX] - // int flag - // int num_resps - // uint8_t adv_data_len - // uint8_t scan_rsp_len - case ESP_GAP_BLE_SCAN_RESULT_EVT: { - - switch(param->scan_rst.search_evt) { - // - // ESP_GAP_SEARCH_INQ_CMPL_EVT - // - // Event that indicates that the duration allowed for the search has completed or that we have been - // asked to stop. - case ESP_GAP_SEARCH_INQ_CMPL_EVT: { - log_w("ESP_GAP_SEARCH_INQ_CMPL_EVT"); - m_stopped = true; - m_semaphoreScanEnd.give(); - if (m_scanCompleteCB != nullptr) { - m_scanCompleteCB(m_scanResults); - } - break; - } // ESP_GAP_SEARCH_INQ_CMPL_EVT - - // - // ESP_GAP_SEARCH_INQ_RES_EVT - // - // Result that has arrived back from a Scan inquiry. - case ESP_GAP_SEARCH_INQ_RES_EVT: { - if (m_stopped) { // If we are not scanning, nothing to do with the extra results. - break; - } - -// Examine our list of previously scanned addresses and, if we found this one already, -// ignore it. - BLEAddress advertisedAddress(param->scan_rst.bda); - bool found = false; - bool shouldDelete = true; - - if (!m_wantDuplicates) { - if (m_scanResults.m_vectorAdvertisedDevices.count(advertisedAddress.toString()) != 0) { - found = true; - } - - if (found) { // If we found a previous entry AND we don't want duplicates, then we are done. - log_d("Ignoring %s, already seen it.", advertisedAddress.toString().c_str()); - vTaskDelay(1); // <--- allow to switch task in case we scan infinity and dont have new devices to report, or we are blocked here - break; - } - } - - // We now construct a model of the advertised device that we have just found for the first - // time. - // ESP_LOG_BUFFER_HEXDUMP((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len, ESP_LOG_DEBUG); - // log_w("bytes length: %d + %d, addr type: %d", param->scan_rst.adv_data_len, param->scan_rst.scan_rsp_len, param->scan_rst.ble_addr_type); - BLEAdvertisedDevice *advertisedDevice = new BLEAdvertisedDevice(); - advertisedDevice->setAddress(advertisedAddress); - advertisedDevice->setRSSI(param->scan_rst.rssi); - advertisedDevice->setAdFlag(param->scan_rst.flag); - if (m_shouldParse) { - advertisedDevice->parseAdvertisement((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len); - } else { - advertisedDevice->setPayload((uint8_t*)param->scan_rst.ble_adv, param->scan_rst.adv_data_len + param->scan_rst.scan_rsp_len); - } - advertisedDevice->setScan(this); - advertisedDevice->setAddressType(param->scan_rst.ble_addr_type); - - if (m_pAdvertisedDeviceCallbacks) { // if has callback, no need to record to vector - m_pAdvertisedDeviceCallbacks->onResult(*advertisedDevice); - } else if (!m_wantDuplicates && !found) { // if no callback and not want duplicate, and not already in vector, record it - m_scanResults.m_vectorAdvertisedDevices.insert(std::pair(advertisedAddress.toString(), advertisedDevice)); - shouldDelete = false; - } - if (shouldDelete) { - delete advertisedDevice; - } - - break; - } // ESP_GAP_SEARCH_INQ_RES_EVT - - default: { - break; - } - } // switch - search_evt - - - break; - } // ESP_GAP_BLE_SCAN_RESULT_EVT - - default: { - break; - } // default - } // End switch -} // gapEventHandler - - -/** - * @brief Should we perform an active or passive scan? - * The default is a passive scan. An active scan means that we will wish a scan response. - * @param [in] active If true, we perform an active scan otherwise a passive scan. - * @return N/A. - */ -void BLEScan::setActiveScan(bool active) { - if (active) { - m_scan_params.scan_type = BLE_SCAN_TYPE_ACTIVE; - } else { - m_scan_params.scan_type = BLE_SCAN_TYPE_PASSIVE; - } -} // setActiveScan - - -/** - * @brief Set the call backs to be invoked. - * @param [in] pAdvertisedDeviceCallbacks Call backs to be invoked. - * @param [in] wantDuplicates True if we wish to be called back with duplicates. Default is false. - * @param [in] shouldParse True if we wish to parse advertised package or raw payload. Default is true. - */ -void BLEScan::setAdvertisedDeviceCallbacks(BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, bool wantDuplicates, bool shouldParse) { - m_wantDuplicates = wantDuplicates; - m_pAdvertisedDeviceCallbacks = pAdvertisedDeviceCallbacks; - m_shouldParse = shouldParse; -} // setAdvertisedDeviceCallbacks - -/** - * @brief Set the interval to scan. - * @param [in] The interval in msecs. - */ -void BLEScan::setInterval(uint16_t intervalMSecs) { - m_scan_params.scan_interval = intervalMSecs / 0.625; -} // setInterval - - -/** - * @brief Set the window to actively scan. - * @param [in] windowMSecs How long to actively scan. - */ -void BLEScan::setWindow(uint16_t windowMSecs) { - m_scan_params.scan_window = windowMSecs / 0.625; -} // setWindow - - -/** - * @brief Start scanning. - * @param [in] duration The duration in seconds for which to scan. - * @param [in] scanCompleteCB A function to be called when scanning has completed. - * @param [in] are we continue scan (true) or we want to clear stored devices (false) - * @return True if scan started or false if there was an error. - */ -bool BLEScan::start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue) { - log_v(">> start(duration=%d)", duration); - - m_semaphoreScanEnd.take(std::string("start")); - m_scanCompleteCB = scanCompleteCB; // Save the callback to be invoked when the scan completes. - - // if we are connecting to devices that are advertising even after being connected, multiconnecting peripherals - // then we should not clear map or we will connect the same device few times - if(!is_continue) { - for(auto _dev : m_scanResults.m_vectorAdvertisedDevices){ - delete _dev.second; - } - m_scanResults.m_vectorAdvertisedDevices.clear(); - } - - esp_err_t errRc = ::esp_ble_gap_set_scan_params(&m_scan_params); - - if (errRc != ESP_OK) { - log_e("esp_ble_gap_set_scan_params: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - m_semaphoreScanEnd.give(); - return false; - } - - errRc = ::esp_ble_gap_start_scanning(duration); - - if (errRc != ESP_OK) { - log_e("esp_ble_gap_start_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - m_semaphoreScanEnd.give(); - return false; - } - - m_stopped = false; - - log_v("<< start()"); - return true; -} // start - - -/** - * @brief Start scanning and block until scanning has been completed. - * @param [in] duration The duration in seconds for which to scan. - * @return The BLEScanResults. - */ -BLEScanResults BLEScan::start(uint32_t duration, bool is_continue) { - if(start(duration, nullptr, is_continue)) { - m_semaphoreScanEnd.wait("start"); // Wait for the semaphore to release. - } - return m_scanResults; -} // start - - -/** - * @brief Stop an in progress scan. - * @return N/A. - */ -void BLEScan::stop() { - log_v(">> stop()"); - - esp_err_t errRc = ::esp_ble_gap_stop_scanning(); - - m_stopped = true; - m_semaphoreScanEnd.give(); - - if (errRc != ESP_OK) { - log_e("esp_ble_gap_stop_scanning: err: %d, text: %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - log_v("<< stop()"); -} // stop - -// delete peer device from cache after disconnecting, it is required in case we are connecting to devices with not public address -void BLEScan::erase(BLEAddress address) { - log_i("erase device: %s", address.toString().c_str()); - BLEAdvertisedDevice *advertisedDevice = m_scanResults.m_vectorAdvertisedDevices.find(address.toString())->second; - m_scanResults.m_vectorAdvertisedDevices.erase(address.toString()); - delete advertisedDevice; -} - - -/** - * @brief Dump the scan results to the log. - */ -void BLEScanResults::dump() { - log_v(">> Dump scan results:"); - for (int i=0; isecond; - for (auto it = m_vectorAdvertisedDevices.begin(); it != m_vectorAdvertisedDevices.end(); it++) { - dev = *it->second; - if (x==i) break; - x++; - } - return dev; -} - -BLEScanResults BLEScan::getResults() { - return m_scanResults; -} - -void BLEScan::clearResults() { - for(auto _dev : m_scanResults.m_vectorAdvertisedDevices){ - delete _dev.second; - } - m_scanResults.m_vectorAdvertisedDevices.clear(); -} - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEScan.h b/libraries/BLE/src/BLEScan.h deleted file mode 100644 index 14b47153..00000000 --- a/libraries/BLE/src/BLEScan.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * BLEScan.h - * - * Created on: Jul 1, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESCAN_H_ -#define COMPONENTS_CPP_UTILS_BLESCAN_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include - -// #include -#include -#include "BLEAdvertisedDevice.h" -#include "BLEClient.h" -#include "RTOS.h" - -class BLEAdvertisedDevice; -class BLEAdvertisedDeviceCallbacks; -class BLEClient; -class BLEScan; - - -/** - * @brief The result of having performed a scan. - * When a scan completes, we have a set of found devices. Each device is described - * by a BLEAdvertisedDevice object. The number of items in the set is given by - * getCount(). We can retrieve a device by calling getDevice() passing in the - * index (starting at 0) of the desired device. - */ -class BLEScanResults { -public: - void dump(); - int getCount(); - BLEAdvertisedDevice getDevice(uint32_t i); - -private: - friend BLEScan; - std::map m_vectorAdvertisedDevices; -}; - -/** - * @brief Perform and manage %BLE scans. - * - * Scanning is associated with a %BLE client that is attempting to locate BLE servers. - */ -class BLEScan { -public: - void setActiveScan(bool active); - void setAdvertisedDeviceCallbacks( - BLEAdvertisedDeviceCallbacks* pAdvertisedDeviceCallbacks, - bool wantDuplicates = false, - bool shouldParse = true); - void setInterval(uint16_t intervalMSecs); - void setWindow(uint16_t windowMSecs); - bool start(uint32_t duration, void (*scanCompleteCB)(BLEScanResults), bool is_continue = false); - BLEScanResults start(uint32_t duration, bool is_continue = false); - void stop(); - void erase(BLEAddress address); - BLEScanResults getResults(); - void clearResults(); - -private: - BLEScan(); // One doesn't create a new instance instead one asks the BLEDevice for the singleton. - friend class BLEDevice; - void handleGAPEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - void parseAdvertisement(BLEClient* pRemoteDevice, uint8_t *payload); - - - esp_ble_scan_params_t m_scan_params; - BLEAdvertisedDeviceCallbacks* m_pAdvertisedDeviceCallbacks = nullptr; - bool m_stopped = true; - bool m_shouldParse = true; - FreeRTOS::Semaphore m_semaphoreScanEnd = FreeRTOS::Semaphore("ScanEnd"); - BLEScanResults m_scanResults; - bool m_wantDuplicates; - void (*m_scanCompleteCB)(BLEScanResults scanResults); -}; // BLEScan - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLESCAN_H_ */ diff --git a/libraries/BLE/src/BLESecurity.cpp b/libraries/BLE/src/BLESecurity.cpp deleted file mode 100644 index b04acfda..00000000 --- a/libraries/BLE/src/BLESecurity.cpp +++ /dev/null @@ -1,115 +0,0 @@ -/* - * BLESecurity.cpp - * - * Created on: Dec 17, 2017 - * Author: chegewara - */ - -#include "BLESecurity.h" -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -BLESecurity::BLESecurity() { -} - -BLESecurity::~BLESecurity() { -} -/* - * @brief Set requested authentication mode - */ -void BLESecurity::setAuthenticationMode(esp_ble_auth_req_t auth_req) { - m_authReq = auth_req; - esp_ble_gap_set_security_param(ESP_BLE_SM_AUTHEN_REQ_MODE, &m_authReq, sizeof(uint8_t)); // <--- setup requested authentication mode -} - -/** - * @brief Set our device IO capability to let end user perform authorization - * either by displaying or entering generated 6-digits pin code - */ -void BLESecurity::setCapability(esp_ble_io_cap_t iocap) { - m_iocap = iocap; - esp_ble_gap_set_security_param(ESP_BLE_SM_IOCAP_MODE, &iocap, sizeof(uint8_t)); -} // setCapability - - -/** - * @brief Init encryption key by server - * @param key_size is value between 7 and 16 - */ -void BLESecurity::setInitEncryptionKey(uint8_t init_key) { - m_initKey = init_key; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_INIT_KEY, &m_initKey, sizeof(uint8_t)); -} // setInitEncryptionKey - - -/** - * @brief Init encryption key by client - * @param key_size is value between 7 and 16 - */ -void BLESecurity::setRespEncryptionKey(uint8_t resp_key) { - m_respKey = resp_key; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &m_respKey, sizeof(uint8_t)); -} // setRespEncryptionKey - - -/** - * - * - */ -void BLESecurity::setKeySize(uint8_t key_size) { - m_keySize = key_size; - esp_ble_gap_set_security_param(ESP_BLE_SM_MAX_KEY_SIZE, &m_keySize, sizeof(uint8_t)); -} //setKeySize - -/** - * Setup for static PIN connection, call it first and then call setAuthenticationMode eventually to change it - */ -void BLESecurity::setStaticPIN(uint32_t pin){ - uint32_t passkey = pin; - esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t)); - setCapability(ESP_IO_CAP_OUT); - setKeySize(); - setAuthenticationMode(ESP_LE_AUTH_REQ_SC_ONLY); - setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK); -} - -/** - * @brief Debug function to display what keys are exchanged by peers - */ -char* BLESecurity::esp_key_type_to_str(esp_ble_key_type_t key_type) { - char* key_str = nullptr; - switch (key_type) { - case ESP_LE_KEY_NONE: - key_str = (char*) "ESP_LE_KEY_NONE"; - break; - case ESP_LE_KEY_PENC: - key_str = (char*) "ESP_LE_KEY_PENC"; - break; - case ESP_LE_KEY_PID: - key_str = (char*) "ESP_LE_KEY_PID"; - break; - case ESP_LE_KEY_PCSRK: - key_str = (char*) "ESP_LE_KEY_PCSRK"; - break; - case ESP_LE_KEY_PLK: - key_str = (char*) "ESP_LE_KEY_PLK"; - break; - case ESP_LE_KEY_LLK: - key_str = (char*) "ESP_LE_KEY_LLK"; - break; - case ESP_LE_KEY_LENC: - key_str = (char*) "ESP_LE_KEY_LENC"; - break; - case ESP_LE_KEY_LID: - key_str = (char*) "ESP_LE_KEY_LID"; - break; - case ESP_LE_KEY_LCSRK: - key_str = (char*) "ESP_LE_KEY_LCSRK"; - break; - default: - key_str = (char*) "INVALID BLE KEY TYPE"; - break; - } - return key_str; -} // esp_key_type_to_str -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLESecurity.h b/libraries/BLE/src/BLESecurity.h deleted file mode 100644 index 144f4bbd..00000000 --- a/libraries/BLE/src/BLESecurity.h +++ /dev/null @@ -1,73 +0,0 @@ -/* - * BLESecurity.h - * - * Created on: Dec 17, 2017 - * Author: chegewara - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESECURITY_H_ -#define COMPONENTS_CPP_UTILS_BLESECURITY_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include - -class BLESecurity { -public: - BLESecurity(); - virtual ~BLESecurity(); - void setAuthenticationMode(esp_ble_auth_req_t auth_req); - void setCapability(esp_ble_io_cap_t iocap); - void setInitEncryptionKey(uint8_t init_key); - void setRespEncryptionKey(uint8_t resp_key); - void setKeySize(uint8_t key_size = 16); - void setStaticPIN(uint32_t pin); - static char* esp_key_type_to_str(esp_ble_key_type_t key_type); - -private: - esp_ble_auth_req_t m_authReq; - esp_ble_io_cap_t m_iocap; - uint8_t m_initKey; - uint8_t m_respKey; - uint8_t m_keySize; - -}; // BLESecurity - - -/* - * @brief Callbacks to handle GAP events related to authorization - */ -class BLESecurityCallbacks { -public: - virtual ~BLESecurityCallbacks() {}; - - /** - * @brief Its request from peer device to input authentication pin code displayed on peer device. - * It requires that our device is capable to input 6-digits code by end user - * @return Return 6-digits integer value from input device - */ - virtual uint32_t onPassKeyRequest() = 0; - - /** - * @brief Provide us 6-digits code to perform authentication. - * It requires that our device is capable to display this code to end user - * @param - */ - virtual void onPassKeyNotify(uint32_t pass_key) = 0; - - /** - * @brief Here we can make decision if we want to let negotiate authorization with peer device or not - * return Return true if we accept this peer device request - */ - - virtual bool onSecurityRequest() = 0 ; - /** - * Provide us information when authentication process is completed - */ - virtual void onAuthenticationComplete(esp_ble_auth_cmpl_t) = 0; - - virtual bool onConfirmPIN(uint32_t pin) = 0; -}; // BLESecurityCallbacks - -#endif // CONFIG_BLUEDROID_ENABLED -#endif // COMPONENTS_CPP_UTILS_BLESECURITY_H_ diff --git a/libraries/BLE/src/BLEServer.cpp b/libraries/BLE/src/BLEServer.cpp deleted file mode 100644 index 0b39c9ca..00000000 --- a/libraries/BLE/src/BLEServer.cpp +++ /dev/null @@ -1,426 +0,0 @@ -/* - * BLEServer.cpp - * - * Created on: Apr 16, 2017 - * Author: kolban - */ - -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "GeneralUtils.h" -#include "BLEDevice.h" -#include "BLEServer.h" -#include "BLEService.h" -#include "BLEUtils.h" -#include -#include -#include -#include "esp32-hal-log.h" - -/** - * @brief Construct a %BLE Server - * - * This class is not designed to be individually instantiated. Instead one should create a server by asking - * the BLEDevice class. - */ -BLEServer::BLEServer() { - m_appId = ESP_GATT_IF_NONE; - m_gatts_if = ESP_GATT_IF_NONE; - m_connectedCount = 0; - m_connId = ESP_GATT_IF_NONE; - m_pServerCallbacks = nullptr; -} // BLEServer - - -void BLEServer::createApp(uint16_t appId) { - m_appId = appId; - registerApp(appId); -} // createApp - - -/** - * @brief Create a %BLE Service. - * - * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition - * of a new service. Every service must have a unique UUID. - * @param [in] uuid The UUID of the new service. - * @return A reference to the new service object. - */ -BLEService* BLEServer::createService(const char* uuid) { - return createService(BLEUUID(uuid)); -} - - -/** - * @brief Create a %BLE Service. - * - * With a %BLE server, we can host one or more services. Invoking this function causes the creation of a definition - * of a new service. Every service must have a unique UUID. - * @param [in] uuid The UUID of the new service. - * @param [in] numHandles The maximum number of handles associated with this service. - * @param [in] inst_id With multiple services with the same UUID we need to provide inst_id value different for each service. - * @return A reference to the new service object. - */ -BLEService* BLEServer::createService(BLEUUID uuid, uint32_t numHandles, uint8_t inst_id) { - log_v(">> createService - %s", uuid.toString().c_str()); - m_semaphoreCreateEvt.take("createService"); - - // Check that a service with the supplied UUID does not already exist. - if (m_serviceMap.getByUUID(uuid) != nullptr) { - log_w("<< Attempt to create a new service with uuid %s but a service with that UUID already exists.", - uuid.toString().c_str()); - } - - BLEService* pService = new BLEService(uuid, numHandles); - pService->m_instId = inst_id; - m_serviceMap.setByUUID(uuid, pService); // Save a reference to this service being on this server. - pService->executeCreate(this); // Perform the API calls to actually create the service. - - m_semaphoreCreateEvt.wait("createService"); - - log_v("<< createService"); - return pService; -} // createService - - -/** - * @brief Get a %BLE Service by its UUID - * @param [in] uuid The UUID of the new service. - * @return A reference to the service object. - */ -BLEService* BLEServer::getServiceByUUID(const char* uuid) { - return m_serviceMap.getByUUID(uuid); -} - -/** - * @brief Get a %BLE Service by its UUID - * @param [in] uuid The UUID of the new service. - * @return A reference to the service object. - */ -BLEService* BLEServer::getServiceByUUID(BLEUUID uuid) { - return m_serviceMap.getByUUID(uuid); -} - -/** - * @brief Retrieve the advertising object that can be used to advertise the existence of the server. - * - * @return An advertising object. - */ -BLEAdvertising* BLEServer::getAdvertising() { - return BLEDevice::getAdvertising(); -} - -uint16_t BLEServer::getConnId() { - return m_connId; -} - - -/** - * @brief Return the number of connected clients. - * @return The number of connected clients. - */ -uint32_t BLEServer::getConnectedCount() { - return m_connectedCount; -} // getConnectedCount - - -uint16_t BLEServer::getGattsIf() { - return m_gatts_if; -} - - -/** - * @brief Handle a GATT Server Event. - * - * @param [in] event - * @param [in] gatts_if - * @param [in] param - * - */ -void BLEServer::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { - log_v(">> handleGATTServerEvent: %s", - BLEUtils::gattServerEventTypeToString(event).c_str()); - - switch(event) { - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - // - case ESP_GATTS_ADD_CHAR_EVT: { - break; - } // ESP_GATTS_ADD_CHAR_EVT - - case ESP_GATTS_MTU_EVT: - updatePeerMTU(param->mtu.conn_id, param->mtu.mtu); - break; - - // ESP_GATTS_CONNECT_EVT - // connect: - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - case ESP_GATTS_CONNECT_EVT: { - m_connId = param->connect.conn_id; - addPeerDevice((void*)this, false, m_connId); - if (m_pServerCallbacks != nullptr) { - m_pServerCallbacks->onConnect(this); - m_pServerCallbacks->onConnect(this, param); - } - m_connectedCount++; // Increment the number of connected devices count. - break; - } // ESP_GATTS_CONNECT_EVT - - - // ESP_GATTS_CREATE_EVT - // Called when a new service is registered as having been created. - // - // create: - // * esp_gatt_status_t status - // * uint16_t service_handle - // * esp_gatt_srvc_id_t service_id - // - case ESP_GATTS_CREATE_EVT: { - BLEService* pService = m_serviceMap.getByUUID(param->create.service_id.id.uuid, param->create.service_id.id.inst_id); // <--- very big bug for multi services with the same uuid - m_serviceMap.setByHandle(param->create.service_handle, pService); - m_semaphoreCreateEvt.give(); - break; - } // ESP_GATTS_CREATE_EVT - - - // ESP_GATTS_DISCONNECT_EVT - // - // disconnect - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - esp_gatt_conn_reason_t reason - // - // If we receive a disconnect event then invoke the callback for disconnects (if one is present). - // we also want to start advertising again. - case ESP_GATTS_DISCONNECT_EVT: { - if (m_pServerCallbacks != nullptr) { // If we have callbacks, call now. - m_pServerCallbacks->onDisconnect(this); - } - if(m_connId == ESP_GATT_IF_NONE) { - return; - } - - // only decrement if connection is found in map and removed - // sometimes this event triggers w/o a valid connection - if(removePeerDevice(param->disconnect.conn_id, false)) { - m_connectedCount--; // Decrement the number of connected devices count. - } - break; - } // ESP_GATTS_DISCONNECT_EVT - - - // ESP_GATTS_READ_EVT - A request to read the value of a characteristic has arrived. - // - // read: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool is_long - // - bool need_rsp - // - case ESP_GATTS_READ_EVT: { - break; - } // ESP_GATTS_READ_EVT - - - // ESP_GATTS_REG_EVT - // reg: - // - esp_gatt_status_t status - // - uint16_t app_id - // - case ESP_GATTS_REG_EVT: { - m_gatts_if = gatts_if; - m_semaphoreRegisterAppEvt.give(); // Unlock the mutex waiting for the registration of the app. - break; - } // ESP_GATTS_REG_EVT - - - // ESP_GATTS_WRITE_EVT - A request to write the value of a characteristic has arrived. - // - // write: - // - uint16_t conn_id - // - uint16_t trans_id - // - esp_bd_addr_t bda - // - uint16_t handle - // - uint16_t offset - // - bool need_rsp - // - bool is_prep - // - uint16_t len - // - uint8_t* value - // - case ESP_GATTS_WRITE_EVT: { - break; - } - - case ESP_GATTS_OPEN_EVT: - m_semaphoreOpenEvt.give(param->open.status); - break; - - default: - break; - } - - // Invoke the handler for every Service we have. - m_serviceMap.handleGATTServerEvent(event, gatts_if, param); - - log_v("<< handleGATTServerEvent"); -} // handleGATTServerEvent - - -/** - * @brief Register the app. - * - * @return N/A - */ -void BLEServer::registerApp(uint16_t m_appId) { - log_v(">> registerApp - %d", m_appId); - m_semaphoreRegisterAppEvt.take("registerApp"); // Take the mutex, will be released by ESP_GATTS_REG_EVT event. - ::esp_ble_gatts_app_register(m_appId); - m_semaphoreRegisterAppEvt.wait("registerApp"); - log_v("<< registerApp"); -} // registerApp - - -/** - * @brief Set the server callbacks. - * - * As a %BLE server operates, it will generate server level events such as a new client connecting or a previous client - * disconnecting. This function can be called to register a callback handler that will be invoked when these - * events are detected. - * - * @param [in] pCallbacks The callbacks to be invoked. - */ -void BLEServer::setCallbacks(BLEServerCallbacks* pCallbacks) { - m_pServerCallbacks = pCallbacks; -} // setCallbacks - -/* - * Remove service - */ -void BLEServer::removeService(BLEService* service) { - service->stop(); - service->executeDelete(); - m_serviceMap.removeService(service); -} - -/** - * @brief Start advertising. - * - * Start the server advertising its existence. This is a convenience function and is equivalent to - * retrieving the advertising object and invoking start upon it. - */ -void BLEServer::startAdvertising() { - log_v(">> startAdvertising"); - BLEDevice::startAdvertising(); - log_v("<< startAdvertising"); -} // startAdvertising - -/** - * Allow to connect GATT server to peer device - * Probably can be used in ANCS for iPhone - */ -bool BLEServer::connect(BLEAddress address) { - esp_bd_addr_t addr; - memcpy(&addr, address.getNative(), 6); - // Perform the open connection request against the target BLE Server. - m_semaphoreOpenEvt.take("connect"); - esp_err_t errRc = ::esp_ble_gatts_open( - getGattsIf(), - addr, // address - 1 // direct connection - ); - if (errRc != ESP_OK) { - log_e("esp_ble_gattc_open: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return false; - } - - uint32_t rc = m_semaphoreOpenEvt.wait("connect"); // Wait for the connection to complete. - log_v("<< connect(), rc=%d", rc==ESP_GATT_OK); - return rc == ESP_GATT_OK; -} // connect - - - -void BLEServerCallbacks::onConnect(BLEServer* pServer) { - log_d("BLEServerCallbacks", ">> onConnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onConnect()"); -} // onConnect - -void BLEServerCallbacks::onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t* param) { - log_d("BLEServerCallbacks", ">> onConnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onConnect()"); -} // onConnect - - -void BLEServerCallbacks::onDisconnect(BLEServer* pServer) { - log_d("BLEServerCallbacks", ">> onDisconnect(): Default"); - log_d("BLEServerCallbacks", "Device: %s", BLEDevice::toString().c_str()); - log_d("BLEServerCallbacks", "<< onDisconnect()"); -} // onDisconnect - -/* multi connect support */ -/* TODO do some more tweaks */ -void BLEServer::updatePeerMTU(uint16_t conn_id, uint16_t mtu) { - // set mtu in conn_status_t - const std::map::iterator it = m_connectedServersMap.find(conn_id); - if (it != m_connectedServersMap.end()) { - it->second.mtu = mtu; - std::swap(m_connectedServersMap[conn_id], it->second); - } -} - -std::map BLEServer::getPeerDevices(bool _client) { - return m_connectedServersMap; -} - - -uint16_t BLEServer::getPeerMTU(uint16_t conn_id) { - return m_connectedServersMap.find(conn_id)->second.mtu; -} - -void BLEServer::addPeerDevice(void* peer, bool _client, uint16_t conn_id) { - conn_status_t status = { - .peer_device = peer, - .connected = true, - .mtu = 23 - }; - - m_connectedServersMap.insert(std::pair(conn_id, status)); -} - -bool BLEServer::removePeerDevice(uint16_t conn_id, bool _client) { - return m_connectedServersMap.erase(conn_id) > 0; -} -/* multi connect support */ - -/** - * Update connection parameters can be called only after connection has been established - */ -void BLEServer::updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout) { - esp_ble_conn_update_params_t conn_params; - memcpy(conn_params.bda, remote_bda, sizeof(esp_bd_addr_t)); - conn_params.latency = latency; - conn_params.max_int = maxInterval; // max_int = 0x20*1.25ms = 40ms - conn_params.min_int = minInterval; // min_int = 0x10*1.25ms = 20ms - conn_params.timeout = timeout; // timeout = 400*10ms = 4000ms - esp_ble_gap_update_conn_params(&conn_params); -} - -void BLEServer::disconnect(uint16_t connId) { - esp_ble_gatts_close(m_gatts_if, connId); -} - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEServer.h b/libraries/BLE/src/BLEServer.h deleted file mode 100644 index 2ae23edb..00000000 --- a/libraries/BLE/src/BLEServer.h +++ /dev/null @@ -1,141 +0,0 @@ -/* - * BLEServer.h - * - * Created on: Apr 16, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESERVER_H_ -#define COMPONENTS_CPP_UTILS_BLESERVER_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include - -#include -#include -// #include "BLEDevice.h" - -#include "BLEUUID.h" -#include "BLEAdvertising.h" -#include "BLECharacteristic.h" -#include "BLEService.h" -#include "BLESecurity.h" -#include "RTOS.h" -#include "BLEAddress.h" - -class BLEServerCallbacks; -/* TODO possibly refactor this struct */ -typedef struct { - void *peer_device; // peer device BLEClient or BLEServer - maybe its better to have 2 structures or union here - bool connected; // do we need it? - uint16_t mtu; // every peer device negotiate own mtu -} conn_status_t; - - -/** - * @brief A data structure that manages the %BLE servers owned by a BLE server. - */ -class BLEServiceMap { -public: - BLEService* getByHandle(uint16_t handle); - BLEService* getByUUID(const char* uuid); - BLEService* getByUUID(BLEUUID uuid, uint8_t inst_id = 0); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); - void setByHandle(uint16_t handle, BLEService* service); - void setByUUID(const char* uuid, BLEService* service); - void setByUUID(BLEUUID uuid, BLEService* service); - std::string toString(); - BLEService* getFirst(); - BLEService* getNext(); - void removeService(BLEService *service); - int getRegisteredServiceCount(); - -private: - std::map m_handleMap; - std::map m_uuidMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE server. - */ -class BLEServer { -public: - uint32_t getConnectedCount(); - BLEService* createService(const char* uuid); - BLEService* createService(BLEUUID uuid, uint32_t numHandles=15, uint8_t inst_id=0); - BLEAdvertising* getAdvertising(); - void setCallbacks(BLEServerCallbacks* pCallbacks); - void startAdvertising(); - void removeService(BLEService* service); - BLEService* getServiceByUUID(const char* uuid); - BLEService* getServiceByUUID(BLEUUID uuid); - bool connect(BLEAddress address); - void disconnect(uint16_t connId); - uint16_t m_appId; - void updateConnParams(esp_bd_addr_t remote_bda, uint16_t minInterval, uint16_t maxInterval, uint16_t latency, uint16_t timeout); - - /* multi connection support */ - std::map getPeerDevices(bool client); - void addPeerDevice(void* peer, bool is_client, uint16_t conn_id); - bool removePeerDevice(uint16_t conn_id, bool client); - BLEServer* getServerByConnId(uint16_t conn_id); - void updatePeerMTU(uint16_t connId, uint16_t mtu); - uint16_t getPeerMTU(uint16_t conn_id); - uint16_t getConnId(); - - -private: - BLEServer(); - friend class BLEService; - friend class BLECharacteristic; - friend class BLEDevice; - esp_ble_adv_data_t m_adv_data; - // BLEAdvertising m_bleAdvertising; - uint16_t m_connId; - uint32_t m_connectedCount; - uint16_t m_gatts_if; - std::map m_connectedServersMap; - - FreeRTOS::Semaphore m_semaphoreRegisterAppEvt = FreeRTOS::Semaphore("RegisterAppEvt"); - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - FreeRTOS::Semaphore m_semaphoreOpenEvt = FreeRTOS::Semaphore("OpenEvt"); - BLEServiceMap m_serviceMap; - BLEServerCallbacks* m_pServerCallbacks = nullptr; - - void createApp(uint16_t appId); - uint16_t getGattsIf(); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); - void registerApp(uint16_t); -}; // BLEServer - - -/** - * @brief Callbacks associated with the operation of a %BLE server. - */ -class BLEServerCallbacks { -public: - virtual ~BLEServerCallbacks() {}; - /** - * @brief Handle a new client connection. - * - * When a new client connects, we are invoked. - * - * @param [in] pServer A reference to the %BLE server that received the client connection. - */ - virtual void onConnect(BLEServer* pServer); - virtual void onConnect(BLEServer* pServer, esp_ble_gatts_cb_param_t *param); - /** - * @brief Handle an existing client disconnection. - * - * When an existing client disconnects, we are invoked. - * - * @param [in] pServer A reference to the %BLE server that received the existing client disconnection. - */ - virtual void onDisconnect(BLEServer* pServer); -}; // BLEServerCallbacks - - -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLESERVER_H_ */ diff --git a/libraries/BLE/src/BLEService.cpp b/libraries/BLE/src/BLEService.cpp deleted file mode 100644 index ea815825..00000000 --- a/libraries/BLE/src/BLEService.cpp +++ /dev/null @@ -1,413 +0,0 @@ -/* - * BLEService.cpp - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -// A service is identified by a UUID. A service is also the container for one or more characteristics. - -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include - -#include -#include -#include - -#include "BLEServer.h" -#include "BLEService.h" -#include "BLEUtils.h" -#include "GeneralUtils.h" -#include "esp32-hal-log.h" - -#define NULL_HANDLE (0xffff) - - -/** - * @brief Construct an instance of the BLEService - * @param [in] uuid The UUID of the service. - * @param [in] numHandles The maximum number of handles associated with the service. - */ -BLEService::BLEService(const char* uuid, uint16_t numHandles) : BLEService(BLEUUID(uuid), numHandles) { -} - - -/** - * @brief Construct an instance of the BLEService - * @param [in] uuid The UUID of the service. - * @param [in] numHandles The maximum number of handles associated with the service. - */ -BLEService::BLEService(BLEUUID uuid, uint16_t numHandles) { - m_uuid = uuid; - m_handle = NULL_HANDLE; - m_pServer = nullptr; - //m_serializeMutex.setName("BLEService"); - m_lastCreatedCharacteristic = nullptr; - m_numHandles = numHandles; -} // BLEService - - -/** - * @brief Create the service. - * Create the service. - * @param [in] gatts_if The handle of the GATT server interface. - * @return N/A. - */ - -void BLEService::executeCreate(BLEServer* pServer) { - log_v(">> executeCreate() - Creating service (esp_ble_gatts_create_service) service uuid: %s", getUUID().toString().c_str()); - m_pServer = pServer; - m_semaphoreCreateEvt.take("executeCreate"); // Take the mutex and release at event ESP_GATTS_CREATE_EVT - - esp_gatt_srvc_id_t srvc_id; - srvc_id.is_primary = true; - srvc_id.id.inst_id = m_instId; - srvc_id.id.uuid = *m_uuid.getNative(); - esp_err_t errRc = ::esp_ble_gatts_create_service(getServer()->getGattsIf(), &srvc_id, m_numHandles); // The maximum number of handles associated with the service. - - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_create_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreCreateEvt.wait("executeCreate"); - log_v("<< executeCreate"); -} // executeCreate - - -/** - * @brief Delete the service. - * Delete the service. - * @return N/A. - */ - -void BLEService::executeDelete() { - log_v(">> executeDelete()"); - m_semaphoreDeleteEvt.take("executeDelete"); // Take the mutex and release at event ESP_GATTS_DELETE_EVT - - esp_err_t errRc = ::esp_ble_gatts_delete_service(getHandle()); - - if (errRc != ESP_OK) { - log_e("esp_ble_gatts_delete_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - - m_semaphoreDeleteEvt.wait("executeDelete"); - log_v("<< executeDelete"); -} // executeDelete - - -/** - * @brief Dump details of this BLE GATT service. - * @return N/A. - */ -void BLEService::dump() { - log_d("Service: uuid:%s, handle: 0x%.2x", - m_uuid.toString().c_str(), - m_handle); - log_d("Characteristics:\n%s", m_characteristicMap.toString().c_str()); -} // dump - - -/** - * @brief Get the UUID of the service. - * @return the UUID of the service. - */ -BLEUUID BLEService::getUUID() { - return m_uuid; -} // getUUID - - -/** - * @brief Start the service. - * Here we wish to start the service which means that we will respond to partner requests about it. - * Starting a service also means that we can create the corresponding characteristics. - * @return Start the service. - */ -void BLEService::start() { -// We ask the BLE runtime to start the service and then create each of the characteristics. -// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event -// obtained as a result of calling esp_ble_gatts_create_service(). -// - log_v(">> start(): Starting service (esp_ble_gatts_start_service): %s", toString().c_str()); - if (m_handle == NULL_HANDLE) { - log_e("<< !!! We attempted to start a service but don't know its handle!"); - return; - } - - BLECharacteristic *pCharacteristic = m_characteristicMap.getFirst(); - - while (pCharacteristic != nullptr) { - m_lastCreatedCharacteristic = pCharacteristic; - pCharacteristic->executeCreate(this); - - pCharacteristic = m_characteristicMap.getNext(); - } - // Start each of the characteristics ... these are found in the m_characteristicMap. - - m_semaphoreStartEvt.take("start"); - esp_err_t errRc = ::esp_ble_gatts_start_service(m_handle); - - if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_start_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - m_semaphoreStartEvt.wait("start"); - - log_v("<< start()"); -} // start - - -/** - * @brief Stop the service. - */ -void BLEService::stop() { -// We ask the BLE runtime to start the service and then create each of the characteristics. -// We start the service through its local handle which was returned in the ESP_GATTS_CREATE_EVT event -// obtained as a result of calling esp_ble_gatts_create_service(). - log_v(">> stop(): Stopping service (esp_ble_gatts_stop_service): %s", toString().c_str()); - if (m_handle == NULL_HANDLE) { - log_e("<< !!! We attempted to stop a service but don't know its handle!"); - return; - } - - m_semaphoreStopEvt.take("stop"); - esp_err_t errRc = ::esp_ble_gatts_stop_service(m_handle); - - if (errRc != ESP_OK) { - log_e("<< esp_ble_gatts_stop_service: rc=%d %s", errRc, GeneralUtils::errorToString(errRc)); - return; - } - m_semaphoreStopEvt.wait("stop"); - - log_v("<< stop()"); -} // start - - -/** - * @brief Set the handle associated with this service. - * @param [in] handle The handle associated with the service. - */ -void BLEService::setHandle(uint16_t handle) { - log_v(">> setHandle - Handle=0x%.2x, service UUID=%s)", handle, getUUID().toString().c_str()); - if (m_handle != NULL_HANDLE) { - log_e("!!! Handle is already set %.2x", m_handle); - return; - } - m_handle = handle; - log_v("<< setHandle"); -} // setHandle - - -/** - * @brief Get the handle associated with this service. - * @return The handle associated with this service. - */ -uint16_t BLEService::getHandle() { - return m_handle; -} // getHandle - - -/** - * @brief Add a characteristic to the service. - * @param [in] pCharacteristic A pointer to the characteristic to be added. - */ -void BLEService::addCharacteristic(BLECharacteristic* pCharacteristic) { - // We maintain a mapping of characteristics owned by this service. These are managed by the - // BLECharacteristicMap class instance found in m_characteristicMap. We add the characteristic - // to the map and then ask the service to add the characteristic at the BLE level (ESP-IDF). - - log_v(">> addCharacteristic()"); - log_d("Adding characteristic: uuid=%s to service: %s", - pCharacteristic->getUUID().toString().c_str(), - toString().c_str()); - - // Check that we don't add the same characteristic twice. - if (m_characteristicMap.getByUUID(pCharacteristic->getUUID()) != nullptr) { - log_w("<< Adding a new characteristic with the same UUID as a previous one"); - //return; - } - - // Remember this characteristic in our map of characteristics. At this point, we can lookup by UUID - // but not by handle. The handle is allocated to us on the ESP_GATTS_ADD_CHAR_EVT. - m_characteristicMap.setByUUID(pCharacteristic, pCharacteristic->getUUID()); - - log_v("<< addCharacteristic()"); -} // addCharacteristic - - -/** - * @brief Create a new BLE Characteristic associated with this service. - * @param [in] uuid - The UUID of the characteristic. - * @param [in] properties - The properties of the characteristic. - * @return The new BLE characteristic. - */ -BLECharacteristic* BLEService::createCharacteristic(const char* uuid, uint32_t properties) { - return createCharacteristic(BLEUUID(uuid), properties); -} - - -/** - * @brief Create a new BLE Characteristic associated with this service. - * @param [in] uuid - The UUID of the characteristic. - * @param [in] properties - The properties of the characteristic. - * @return The new BLE characteristic. - */ -BLECharacteristic* BLEService::createCharacteristic(BLEUUID uuid, uint32_t properties) { - BLECharacteristic* pCharacteristic = new BLECharacteristic(uuid, properties); - addCharacteristic(pCharacteristic); - return pCharacteristic; -} // createCharacteristic - - -/** - * @brief Handle a GATTS server event. - */ -void BLEService::handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param) { - switch (event) { - // ESP_GATTS_ADD_CHAR_EVT - Indicate that a characteristic was added to the service. - // add_char: - // - esp_gatt_status_t status - // - uint16_t attr_handle - // - uint16_t service_handle - // - esp_bt_uuid_t char_uuid - - // If we have reached the correct service, then locate the characteristic and remember the handle - // for that characteristic. - case ESP_GATTS_ADD_CHAR_EVT: { - if (m_handle == param->add_char.service_handle) { - BLECharacteristic *pCharacteristic = getLastCreatedCharacteristic(); - if (pCharacteristic == nullptr) { - log_e("Expected to find characteristic with UUID: %s, but didnt!", - BLEUUID(param->add_char.char_uuid).toString().c_str()); - dump(); - break; - } - pCharacteristic->setHandle(param->add_char.attr_handle); - m_characteristicMap.setByHandle(param->add_char.attr_handle, pCharacteristic); - break; - } // Reached the correct service. - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_START_EVT - // - // start: - // esp_gatt_status_t status - // uint16_t service_handle - case ESP_GATTS_START_EVT: { - if (param->start.service_handle == getHandle()) { - m_semaphoreStartEvt.give(); - } - break; - } // ESP_GATTS_START_EVT - - // ESP_GATTS_STOP_EVT - // - // stop: - // esp_gatt_status_t status - // uint16_t service_handle - // - case ESP_GATTS_STOP_EVT: { - if (param->stop.service_handle == getHandle()) { - m_semaphoreStopEvt.give(); - } - break; - } // ESP_GATTS_STOP_EVT - - - // ESP_GATTS_CREATE_EVT - // Called when a new service is registered as having been created. - // - // create: - // * esp_gatt_status_t status - // * uint16_t service_handle - // * esp_gatt_srvc_id_t service_id - // * - esp_gatt_id id - // * - esp_bt_uuid uuid - // * - uint8_t inst_id - // * - bool is_primary - // - case ESP_GATTS_CREATE_EVT: { - if (getUUID().equals(BLEUUID(param->create.service_id.id.uuid)) && m_instId == param->create.service_id.id.inst_id) { - setHandle(param->create.service_handle); - m_semaphoreCreateEvt.give(); - } - break; - } // ESP_GATTS_CREATE_EVT - - - // ESP_GATTS_DELETE_EVT - // Called when a service is deleted. - // - // delete: - // * esp_gatt_status_t status - // * uint16_t service_handle - // - case ESP_GATTS_DELETE_EVT: { - if (param->del.service_handle == getHandle()) { - m_semaphoreDeleteEvt.give(); - } - break; - } // ESP_GATTS_DELETE_EVT - - default: - break; - } // Switch - - // Invoke the GATTS handler in each of the associated characteristics. - m_characteristicMap.handleGATTServerEvent(event, gatts_if, param); -} // handleGATTServerEvent - - -BLECharacteristic* BLEService::getCharacteristic(const char* uuid) { - return getCharacteristic(BLEUUID(uuid)); -} - - -BLECharacteristic* BLEService::getCharacteristic(BLEUUID uuid) { - return m_characteristicMap.getByUUID(uuid); -} - - -/** - * @brief Return a string representation of this service. - * A service is defined by: - * * Its UUID - * * Its handle - * @return A string representation of this service. - */ -std::string BLEService::toString() { - std::string res = "UUID: " + getUUID().toString(); - char hex[5]; - snprintf(hex, sizeof(hex), "%04x", getHandle()); - res += ", handle: 0x"; - res += hex; - return res; -} // toString - - -/** - * @brief Get the last created characteristic. - * It is lamentable that this function has to exist. It returns the last created characteristic. - * We need this because the descriptor API is built around the notion that a new descriptor, when created, - * is associated with the last characteristics created and we need that information. - * @return The last created characteristic. - */ -BLECharacteristic* BLEService::getLastCreatedCharacteristic() { - return m_lastCreatedCharacteristic; -} // getLastCreatedCharacteristic - - -/** - * @brief Get the BLE server associated with this service. - * @return The BLEServer associated with this service. - */ -BLEServer* BLEService::getServer() { - return m_pServer; -} // getServer - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEService.h b/libraries/BLE/src/BLEService.h deleted file mode 100644 index c801a2f5..00000000 --- a/libraries/BLE/src/BLEService.h +++ /dev/null @@ -1,97 +0,0 @@ -/* - * BLEService.h - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLESERVICE_H_ -#define COMPONENTS_CPP_UTILS_BLESERVICE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) - -#include - -#include "BLECharacteristic.h" -#include "BLEServer.h" -#include "BLEUUID.h" -#include "RTOS.h" - -class BLEServer; - -/** - * @brief A data mapping used to manage the set of %BLE characteristics known to the server. - */ -class BLECharacteristicMap { -public: - void setByUUID(BLECharacteristic* pCharacteristic, const char* uuid); - void setByUUID(BLECharacteristic* pCharacteristic, BLEUUID uuid); - void setByHandle(uint16_t handle, BLECharacteristic* pCharacteristic); - BLECharacteristic* getByUUID(const char* uuid); - BLECharacteristic* getByUUID(BLEUUID uuid); - BLECharacteristic* getByHandle(uint16_t handle); - BLECharacteristic* getFirst(); - BLECharacteristic* getNext(); - std::string toString(); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); - -private: - std::map m_uuidMap; - std::map m_handleMap; - std::map::iterator m_iterator; -}; - - -/** - * @brief The model of a %BLE service. - * - */ -class BLEService { -public: - void addCharacteristic(BLECharacteristic* pCharacteristic); - BLECharacteristic* createCharacteristic(const char* uuid, uint32_t properties); - BLECharacteristic* createCharacteristic(BLEUUID uuid, uint32_t properties); - void dump(); - void executeCreate(BLEServer* pServer); - void executeDelete(); - BLECharacteristic* getCharacteristic(const char* uuid); - BLECharacteristic* getCharacteristic(BLEUUID uuid); - BLEUUID getUUID(); - BLEServer* getServer(); - void start(); - void stop(); - std::string toString(); - uint16_t getHandle(); - uint8_t m_instId = 0; - -private: - BLEService(const char* uuid, uint16_t numHandles); - BLEService(BLEUUID uuid, uint16_t numHandles); - friend class BLEServer; - friend class BLEServiceMap; - friend class BLEDescriptor; - friend class BLECharacteristic; - friend class BLEDevice; - - BLECharacteristicMap m_characteristicMap; - uint16_t m_handle; - BLECharacteristic* m_lastCreatedCharacteristic = nullptr; - BLEServer* m_pServer = nullptr; - BLEUUID m_uuid; - - FreeRTOS::Semaphore m_semaphoreCreateEvt = FreeRTOS::Semaphore("CreateEvt"); - FreeRTOS::Semaphore m_semaphoreDeleteEvt = FreeRTOS::Semaphore("DeleteEvt"); - FreeRTOS::Semaphore m_semaphoreStartEvt = FreeRTOS::Semaphore("StartEvt"); - FreeRTOS::Semaphore m_semaphoreStopEvt = FreeRTOS::Semaphore("StopEvt"); - - uint16_t m_numHandles; - - BLECharacteristic* getLastCreatedCharacteristic(); - void handleGATTServerEvent(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t* param); - void setHandle(uint16_t handle); - //void setService(esp_gatt_srvc_id_t srvc_id); -}; // BLEService - - -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLESERVICE_H_ */ diff --git a/libraries/BLE/src/BLEServiceMap.cpp b/libraries/BLE/src/BLEServiceMap.cpp deleted file mode 100644 index ec6fab25..00000000 --- a/libraries/BLE/src/BLEServiceMap.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/* - * BLEServiceMap.cpp - * - * Created on: Jun 22, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include "BLEService.h" - - -/** - * @brief Return the service by UUID. - * @param [in] UUID The UUID to look up the service. - * @return The characteristic. - */ -BLEService* BLEServiceMap::getByUUID(const char* uuid) { - return getByUUID(BLEUUID(uuid)); -} - -/** - * @brief Return the service by UUID. - * @param [in] UUID The UUID to look up the service. - * @return The characteristic. - */ -BLEService* BLEServiceMap::getByUUID(BLEUUID uuid, uint8_t inst_id) { - for (auto &myPair : m_uuidMap) { - if (myPair.first->getUUID().equals(uuid)) { - return myPair.first; - } - } - //return m_uuidMap.at(uuid.toString()); - return nullptr; -} // getByUUID - - -/** - * @brief Return the service by handle. - * @param [in] handle The handle to look up the service. - * @return The service. - */ -BLEService* BLEServiceMap::getByHandle(uint16_t handle) { - return m_handleMap.at(handle); -} // getByHandle - - -/** - * @brief Set the service by UUID. - * @param [in] uuid The uuid of the service. - * @param [in] characteristic The service to cache. - * @return N/A. - */ -void BLEServiceMap::setByUUID(BLEUUID uuid, BLEService* service) { - m_uuidMap.insert(std::pair(service, uuid.toString())); -} // setByUUID - - -/** - * @brief Set the service by handle. - * @param [in] handle The handle of the service. - * @param [in] service The service to cache. - * @return N/A. - */ -void BLEServiceMap::setByHandle(uint16_t handle, BLEService* service) { - m_handleMap.insert(std::pair(handle, service)); -} // setByHandle - - -/** - * @brief Return a string representation of the service map. - * @return A string representation of the service map. - */ -std::string BLEServiceMap::toString() { - std::string res; - char hex[5]; - for (auto &myPair: m_handleMap) { - res += "handle: 0x"; - snprintf(hex, sizeof(hex), "%04x", myPair.first); - res += hex; - res += ", uuid: " + myPair.second->getUUID().toString() + "\n"; - } - return res; -} // toString - -void BLEServiceMap::handleGATTServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* param) { - // Invoke the handler for every Service we have. - for (auto &myPair : m_uuidMap) { - myPair.first->handleGATTServerEvent(event, gatts_if, param); - } -} - -/** - * @brief Get the first service in the map. - * @return The first service in the map. - */ -BLEService* BLEServiceMap::getFirst() { - m_iterator = m_uuidMap.begin(); - if (m_iterator == m_uuidMap.end()) return nullptr; - BLEService* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getFirst - -/** - * @brief Get the next service in the map. - * @return The next service in the map. - */ -BLEService* BLEServiceMap::getNext() { - if (m_iterator == m_uuidMap.end()) return nullptr; - BLEService* pRet = m_iterator->first; - m_iterator++; - return pRet; -} // getNext - -/** - * @brief Removes service from maps. - * @return N/A. - */ -void BLEServiceMap::removeService(BLEService* service) { - m_handleMap.erase(service->getHandle()); - m_uuidMap.erase(service); -} // removeService - -/** - * @brief Returns the amount of registered services - * @return amount of registered services - */ -int BLEServiceMap::getRegisteredServiceCount(){ - return m_handleMap.size(); -} - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEUUID.cpp b/libraries/BLE/src/BLEUUID.cpp deleted file mode 100644 index 45f698af..00000000 --- a/libraries/BLE/src/BLEUUID.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* - * BLEUUID.cpp - * - * Created on: Jun 21, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include -#include -#include -#include -#include -#include -#include "BLEUUID.h" -#include "esp32-hal-log.h" - -/** - * @brief Copy memory from source to target but in reverse order. - * - * When we move memory from one location it is normally: - * - * ``` - * [0][1][2]...[n] -> [0][1][2]...[n] - * ``` - * - * with this function, it is: - * - * ``` - * [0][1][2]...[n] -> [n][n-1][n-2]...[0] - * ``` - * - * @param [in] target The target of the copy - * @param [in] source The source of the copy - * @param [in] size The number of bytes to copy - */ -static void memrcpy(uint8_t* target, uint8_t* source, uint32_t size) { - assert(size > 0); - target += (size - 1); // Point target to the last byte of the target data - while (size > 0) { - *target = *source; - target--; - source++; - size--; - } -} // memrcpy - - -/** - * @brief Create a UUID from a string. - * - * Create a UUID from a string. There will be two possible stories here. Either the string represents - * a binary data field or the string represents a hex encoding of a UUID. - * For the hex encoding, here is an example: - * - * ``` - * "beb5483e-36e1-4688-b7f5-ea07361b26a8" - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - * 12345678-90ab-cdef-1234-567890abcdef - * ``` - * - * This has a length of 36 characters. We need to parse this into 16 bytes. - * - * @param [in] value The string to build a UUID from. - */ -BLEUUID::BLEUUID(std::string value) { - m_valueSet = true; - if (value.length() == 4) { - m_uuid.len = ESP_UUID_LEN_16; - m_uuid.uuid.uuid16 = 0; - for(int i=0;i '9') MSB -= 7; - if(LSB > '9') LSB -= 7; - m_uuid.uuid.uuid16 += (((MSB&0x0F) <<4) | (LSB & 0x0F))<<(2-i)*4; - i+=2; - } - } - else if (value.length() == 8) { - m_uuid.len = ESP_UUID_LEN_32; - m_uuid.uuid.uuid32 = 0; - for(int i=0;i '9') MSB -= 7; - if(LSB > '9') LSB -= 7; - m_uuid.uuid.uuid32 += (((MSB&0x0F) <<4) | (LSB & 0x0F))<<(6-i)*4; - i+=2; - } - } - else if (value.length() == 16) { // how we can have 16 byte length string reprezenting 128 bit uuid??? needs to be investigated (lack of time) - m_uuid.len = ESP_UUID_LEN_128; - memrcpy(m_uuid.uuid.uuid128, (uint8_t*)value.data(), 16); - } - else if (value.length() == 36) { - // If the length of the string is 36 bytes then we will assume it is a long hex string in - // UUID format. - m_uuid.len = ESP_UUID_LEN_128; - int n = 0; - for(int i=0;i '9') MSB -= 7; - if(LSB > '9') LSB -= 7; - m_uuid.uuid.uuid128[15-n++] = ((MSB&0x0F) <<4) | (LSB & 0x0F); - i+=2; - } - } - else { - log_e("ERROR: UUID value not 2, 4, 16 or 36 bytes"); - m_valueSet = false; - } -} //BLEUUID(std::string) - - -/** - * @brief Create a UUID from 16 bytes of memory. - * - * @param [in] pData The pointer to the start of the UUID. - * @param [in] size The size of the data. - * @param [in] msbFirst Is the MSB first in pData memory? - */ -BLEUUID::BLEUUID(uint8_t* pData, size_t size, bool msbFirst) { - if (size != 16) { - log_e("ERROR: UUID length not 16 bytes"); - return; - } - m_uuid.len = ESP_UUID_LEN_128; - if (msbFirst) { - memrcpy(m_uuid.uuid.uuid128, pData, 16); - } else { - memcpy(m_uuid.uuid.uuid128, pData, 16); - } - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the 16bit value. - * - * @param [in] uuid The 16bit short form UUID. - */ -BLEUUID::BLEUUID(uint16_t uuid) { - m_uuid.len = ESP_UUID_LEN_16; - m_uuid.uuid.uuid16 = uuid; - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the 32bit value. - * - * @param [in] uuid The 32bit short form UUID. - */ -BLEUUID::BLEUUID(uint32_t uuid) { - m_uuid.len = ESP_UUID_LEN_32; - m_uuid.uuid.uuid32 = uuid; - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the native UUID. - * - * @param [in] uuid The native UUID. - */ -BLEUUID::BLEUUID(esp_bt_uuid_t uuid) { - m_uuid = uuid; - m_valueSet = true; -} // BLEUUID - - -/** - * @brief Create a UUID from the ESP32 esp_gat_id_t. - * - * @param [in] gattId The data to create the UUID from. - */ -BLEUUID::BLEUUID(esp_gatt_id_t gattId) : BLEUUID(gattId.uuid) { -} // BLEUUID - - -BLEUUID::BLEUUID() { - m_valueSet = false; -} // BLEUUID - - -/** - * @brief Get the number of bits in this uuid. - * @return The number of bits in the UUID. One of 16, 32 or 128. - */ -uint8_t BLEUUID::bitSize() { - if (!m_valueSet) return 0; - switch (m_uuid.len) { - case ESP_UUID_LEN_16: - return 16; - case ESP_UUID_LEN_32: - return 32; - case ESP_UUID_LEN_128: - return 128; - default: - log_e("Unknown UUID length: %d", m_uuid.len); - return 0; - } // End of switch -} // bitSize - - -/** - * @brief Compare a UUID against this UUID. - * - * @param [in] uuid The UUID to compare against. - * @return True if the UUIDs are equal and false otherwise. - */ -bool BLEUUID::equals(BLEUUID uuid) { - //log_d("Comparing: %s to %s", toString().c_str(), uuid.toString().c_str()); - if (!m_valueSet || !uuid.m_valueSet) return false; - - if (uuid.m_uuid.len != m_uuid.len) { - return uuid.toString() == toString(); - } - - if (uuid.m_uuid.len == ESP_UUID_LEN_16) { - return uuid.m_uuid.uuid.uuid16 == m_uuid.uuid.uuid16; - } - - if (uuid.m_uuid.len == ESP_UUID_LEN_32) { - return uuid.m_uuid.uuid.uuid32 == m_uuid.uuid.uuid32; - } - - return memcmp(uuid.m_uuid.uuid.uuid128, m_uuid.uuid.uuid128, 16) == 0; -} // equals - - -/** - * Create a BLEUUID from a string of the form: - * 0xNNNN - * 0xNNNNNNNN - * 0x - * NNNN - * NNNNNNNN - * - */ -BLEUUID BLEUUID::fromString(std::string _uuid) { - uint8_t start = 0; - if (strstr(_uuid.c_str(), "0x") != nullptr) { // If the string starts with 0x, skip those characters. - start = 2; - } - uint8_t len = _uuid.length() - start; // Calculate the length of the string we are going to use. - - if(len == 4) { - uint16_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); - return BLEUUID(x); - } else if (len == 8) { - uint32_t x = strtoul(_uuid.substr(start, len).c_str(), NULL, 16); - return BLEUUID(x); - } else if (len == 36) { - return BLEUUID(_uuid); - } - return BLEUUID(); -} // fromString - - -/** - * @brief Get the native UUID value. - * - * @return The native UUID value or NULL if not set. - */ -esp_bt_uuid_t* BLEUUID::getNative() { - //log_d(">> getNative()") - if (m_valueSet == false) { - log_v("<< Return of un-initialized UUID!"); - return nullptr; - } - //log_d("<< getNative()"); - return &m_uuid; -} // getNative - - -/** - * @brief Convert a UUID to its 128 bit representation. - * - * A UUID can be internally represented as 16bit, 32bit or the full 128bit. This method - * will convert 16 or 32 bit representations to the full 128bit. - */ -BLEUUID BLEUUID::to128() { - //log_v(">> toFull() - %s", toString().c_str()); - - // If we either don't have a value or are already a 128 bit UUID, nothing further to do. - if (!m_valueSet || m_uuid.len == ESP_UUID_LEN_128) { - return *this; - } - - // If we are 16 bit or 32 bit, then set the 4 bytes of the variable part of the UUID. - if (m_uuid.len == ESP_UUID_LEN_16) { - uint16_t temp = m_uuid.uuid.uuid16; - m_uuid.uuid.uuid128[15] = 0; - m_uuid.uuid.uuid128[14] = 0; - m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; - m_uuid.uuid.uuid128[12] = temp & 0xff; - - } - else if (m_uuid.len == ESP_UUID_LEN_32) { - uint32_t temp = m_uuid.uuid.uuid32; - m_uuid.uuid.uuid128[15] = (temp >> 24) & 0xff; - m_uuid.uuid.uuid128[14] = (temp >> 16) & 0xff; - m_uuid.uuid.uuid128[13] = (temp >> 8) & 0xff; - m_uuid.uuid.uuid128[12] = temp & 0xff; - } - - // Set the fixed parts of the UUID. - m_uuid.uuid.uuid128[11] = 0x00; - m_uuid.uuid.uuid128[10] = 0x00; - - m_uuid.uuid.uuid128[9] = 0x10; - m_uuid.uuid.uuid128[8] = 0x00; - - m_uuid.uuid.uuid128[7] = 0x80; - m_uuid.uuid.uuid128[6] = 0x00; - - m_uuid.uuid.uuid128[5] = 0x00; - m_uuid.uuid.uuid128[4] = 0x80; - m_uuid.uuid.uuid128[3] = 0x5f; - m_uuid.uuid.uuid128[2] = 0x9b; - m_uuid.uuid.uuid128[1] = 0x34; - m_uuid.uuid.uuid128[0] = 0xfb; - - m_uuid.len = ESP_UUID_LEN_128; - //log_d("<< toFull <- %s", toString().c_str()); - return *this; -} // to128 - - - - -/** - * @brief Get a string representation of the UUID. - * - * The format of a string is: - * 01234567 8901 2345 6789 012345678901 - * 0000180d-0000-1000-8000-00805f9b34fb - * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 - * - * @return A string representation of the UUID. - */ -std::string BLEUUID::toString() { - if (!m_valueSet) return ""; // If we have no value, nothing to format. - // If the UUIDs are 16 or 32 bit, pad correctly. - - if (m_uuid.len == ESP_UUID_LEN_16) { // If the UUID is 16bit, pad correctly. - char hex[9]; - snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid16); - return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; - } // End 16bit UUID - - if (m_uuid.len == ESP_UUID_LEN_32) { // If the UUID is 32bit, pad correctly. - char hex[9]; - snprintf(hex, sizeof(hex), "%08x", m_uuid.uuid.uuid32); - return std::string(hex) + "-0000-1000-8000-00805f9b34fb"; - } // End 32bit UUID - - // The UUID is not 16bit or 32bit which means that it is 128bit. - // - // UUID string format: - // AABBCCDD-EEFF-GGHH-IIJJ-KKLLMMNNOOPP - auto size = 37; // 32 for UUID data, 4 for '-' delimiters and one for a terminator == 37 chars - char *hex = (char *)malloc(size); - snprintf(hex, size, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x", - m_uuid.uuid.uuid128[15], m_uuid.uuid.uuid128[14], - m_uuid.uuid.uuid128[13], m_uuid.uuid.uuid128[12], - m_uuid.uuid.uuid128[11], m_uuid.uuid.uuid128[10], - m_uuid.uuid.uuid128[9], m_uuid.uuid.uuid128[8], - m_uuid.uuid.uuid128[7], m_uuid.uuid.uuid128[6], - m_uuid.uuid.uuid128[5], m_uuid.uuid.uuid128[4], - m_uuid.uuid.uuid128[3], m_uuid.uuid.uuid128[2], - m_uuid.uuid.uuid128[1], m_uuid.uuid.uuid128[0]); - std::string res(hex); - free(hex); - return res; -} // toString - -#endif /* CONFIG_BLUEDROID_ENABLED */ diff --git a/libraries/BLE/src/BLEUUID.h b/libraries/BLE/src/BLEUUID.h deleted file mode 100644 index 07617b9d..00000000 --- a/libraries/BLE/src/BLEUUID.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * BLEUUID.h - * - * Created on: Jun 21, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEUUID_H_ -#define COMPONENTS_CPP_UTILS_BLEUUID_H_ -#include "sdkconfig.h" -#include -#if CONFIG_BLUEDROID_ENABLED -#include - -/** - * @brief A model of a %BLE UUID. - */ -class BLEUUID { -public: - BLEUUID(std::string uuid); - BLEUUID(uint16_t uuid); - BLEUUID(uint32_t uuid); - BLEUUID(esp_bt_uuid_t uuid); - BLEUUID(uint8_t* pData, size_t size, bool msbFirst); - BLEUUID(esp_gatt_id_t gattId); - BLEUUID(); - uint8_t bitSize(); // Get the number of bits in this uuid. - bool equals(BLEUUID uuid); - esp_bt_uuid_t* getNative(); - BLEUUID to128(); - std::string toString(); - static BLEUUID fromString(std::string uuid); // Create a BLEUUID from a string - -private: - esp_bt_uuid_t m_uuid; // The underlying UUID structure that this class wraps. - bool m_valueSet = false; // Is there a value set for this instance. -}; // BLEUUID -#endif /* CONFIG_BLUEDROID_ENABLED */ -#endif /* COMPONENTS_CPP_UTILS_BLEUUID_H_ */ diff --git a/libraries/BLE/src/BLEUtils.cpp b/libraries/BLE/src/BLEUtils.cpp deleted file mode 100644 index bd27a079..00000000 --- a/libraries/BLE/src/BLEUtils.cpp +++ /dev/null @@ -1,2040 +0,0 @@ -/* - * BLEUtils.cpp - * - * Created on: Mar 25, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include "BLEAddress.h" -#include "BLEClient.h" -#include "BLEUtils.h" -#include "BLEUUID.h" -#include "GeneralUtils.h" - -#include -#include -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 ESP-IDF -#include // Part of C++ STL -#include -#include - -#include "esp32-hal-log.h" - -/* -static std::map g_addressMap; -static std::map g_connIdMap; -*/ - -typedef struct { - uint32_t assignedNumber; - const char* name; -} member_t; - -static const member_t members_ids[] = { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - {0xFE08, "Microsoft"}, - {0xFE09, "Pillsy, Inc."}, - {0xFE0A, "ruwido austria gmbh"}, - {0xFE0B, "ruwido austria gmbh"}, - {0xFE0C, "Procter & Gamble"}, - {0xFE0D, "Procter & Gamble"}, - {0xFE0E, "Setec Pty Ltd"}, - {0xFE0F, "Philips Lighting B.V."}, - {0xFE10, "Lapis Semiconductor Co., Ltd."}, - {0xFE11, "GMC-I Messtechnik GmbH"}, - {0xFE12, "M-Way Solutions GmbH"}, - {0xFE13, "Apple Inc."}, - {0xFE14, "Flextronics International USA Inc."}, - {0xFE15, "Amazon Fulfillment Services, Inc."}, - {0xFE16, "Footmarks, Inc."}, - {0xFE17, "Telit Wireless Solutions GmbH"}, - {0xFE18, "Runtime, Inc."}, - {0xFE19, "Google Inc."}, - {0xFE1A, "Tyto Life LLC"}, - {0xFE1B, "Tyto Life LLC"}, - {0xFE1C, "NetMedia, Inc."}, - {0xFE1D, "Illuminati Instrument Corporation"}, - {0xFE1E, "Smart Innovations Co., Ltd"}, - {0xFE1F, "Garmin International, Inc."}, - {0xFE20, "Emerson"}, - {0xFE21, "Bose Corporation"}, - {0xFE22, "Zoll Medical Corporation"}, - {0xFE23, "Zoll Medical Corporation"}, - {0xFE24, "August Home Inc"}, - {0xFE25, "Apple, Inc. "}, - {0xFE26, "Google Inc."}, - {0xFE27, "Google Inc."}, - {0xFE28, "Ayla Networks"}, - {0xFE29, "Gibson Innovations"}, - {0xFE2A, "DaisyWorks, Inc."}, - {0xFE2B, "ITT Industries"}, - {0xFE2C, "Google Inc."}, - {0xFE2D, "SMART INNOVATION Co.,Ltd"}, - {0xFE2E, "ERi,Inc."}, - {0xFE2F, "CRESCO Wireless, Inc"}, - {0xFE30, "Volkswagen AG"}, - {0xFE31, "Volkswagen AG"}, - {0xFE32, "Pro-Mark, Inc."}, - {0xFE33, "CHIPOLO d.o.o."}, - {0xFE34, "SmallLoop LLC"}, - {0xFE35, "HUAWEI Technologies Co., Ltd"}, - {0xFE36, "HUAWEI Technologies Co., Ltd"}, - {0xFE37, "Spaceek LTD"}, - {0xFE38, "Spaceek LTD"}, - {0xFE39, "TTS Tooltechnic Systems AG & Co. KG"}, - {0xFE3A, "TTS Tooltechnic Systems AG & Co. KG"}, - {0xFE3B, "Dolby Laboratories"}, - {0xFE3C, "Alibaba"}, - {0xFE3D, "BD Medical"}, - {0xFE3E, "BD Medical"}, - {0xFE3F, "Friday Labs Limited"}, - {0xFE40, "Inugo Systems Limited"}, - {0xFE41, "Inugo Systems Limited"}, - {0xFE42, "Nets A/S "}, - {0xFE43, "Andreas Stihl AG & Co. KG"}, - {0xFE44, "SK Telecom "}, - {0xFE45, "Snapchat Inc"}, - {0xFE46, "B&O Play A/S "}, - {0xFE47, "General Motors"}, - {0xFE48, "General Motors"}, - {0xFE49, "SenionLab AB"}, - {0xFE4A, "OMRON HEALTHCARE Co., Ltd."}, - {0xFE4B, "Philips Lighting B.V."}, - {0xFE4C, "Volkswagen AG"}, - {0xFE4D, "Casambi Technologies Oy"}, - {0xFE4E, "NTT docomo"}, - {0xFE4F, "Molekule, Inc."}, - {0xFE50, "Google Inc."}, - {0xFE51, "SRAM"}, - {0xFE52, "SetPoint Medical"}, - {0xFE53, "3M"}, - {0xFE54, "Motiv, Inc."}, - {0xFE55, "Google Inc."}, - {0xFE56, "Google Inc."}, - {0xFE57, "Dotted Labs"}, - {0xFE58, "Nordic Semiconductor ASA"}, - {0xFE59, "Nordic Semiconductor ASA"}, - {0xFE5A, "Chronologics Corporation"}, - {0xFE5B, "GT-tronics HK Ltd"}, - {0xFE5C, "million hunters GmbH"}, - {0xFE5D, "Grundfos A/S"}, - {0xFE5E, "Plastc Corporation"}, - {0xFE5F, "Eyefi, Inc."}, - {0xFE60, "Lierda Science & Technology Group Co., Ltd."}, - {0xFE61, "Logitech International SA"}, - {0xFE62, "Indagem Tech LLC"}, - {0xFE63, "Connected Yard, Inc."}, - {0xFE64, "Siemens AG"}, - {0xFE65, "CHIPOLO d.o.o."}, - {0xFE66, "Intel Corporation"}, - {0xFE67, "Lab Sensor Solutions"}, - {0xFE68, "Qualcomm Life Inc"}, - {0xFE69, "Qualcomm Life Inc"}, - {0xFE6A, "Kontakt Micro-Location Sp. z o.o."}, - {0xFE6B, "TASER International, Inc."}, - {0xFE6C, "TASER International, Inc."}, - {0xFE6D, "The University of Tokyo"}, - {0xFE6E, "The University of Tokyo"}, - {0xFE6F, "LINE Corporation"}, - {0xFE70, "Beijing Jingdong Century Trading Co., Ltd."}, - {0xFE71, "Plume Design Inc"}, - {0xFE72, "St. Jude Medical, Inc."}, - {0xFE73, "St. Jude Medical, Inc."}, - {0xFE74, "unwire"}, - {0xFE75, "TangoMe"}, - {0xFE76, "TangoMe"}, - {0xFE77, "Hewlett-Packard Company"}, - {0xFE78, "Hewlett-Packard Company"}, - {0xFE79, "Zebra Technologies"}, - {0xFE7A, "Bragi GmbH"}, - {0xFE7B, "Orion Labs, Inc."}, - {0xFE7C, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, - {0xFE7D, "Aterica Health Inc."}, - {0xFE7E, "Awear Solutions Ltd"}, - {0xFE7F, "Doppler Lab"}, - {0xFE80, "Doppler Lab"}, - {0xFE81, "Medtronic Inc."}, - {0xFE82, "Medtronic Inc."}, - {0xFE83, "Blue Bite"}, - {0xFE84, "RF Digital Corp"}, - {0xFE85, "RF Digital Corp"}, - {0xFE86, "HUAWEI Technologies Co., Ltd. ( )"}, - {0xFE87, "Qingdao Yeelink Information Technology Co., Ltd. ( )"}, - {0xFE88, "SALTO SYSTEMS S.L."}, - {0xFE89, "B&O Play A/S"}, - {0xFE8A, "Apple, Inc."}, - {0xFE8B, "Apple, Inc."}, - {0xFE8C, "TRON Forum"}, - {0xFE8D, "Interaxon Inc."}, - {0xFE8E, "ARM Ltd"}, - {0xFE8F, "CSR"}, - {0xFE90, "JUMA"}, - {0xFE91, "Shanghai Imilab Technology Co.,Ltd"}, - {0xFE92, "Jarden Safety & Security"}, - {0xFE93, "OttoQ Inc."}, - {0xFE94, "OttoQ Inc."}, - {0xFE95, "Xiaomi Inc."}, - {0xFE96, "Tesla Motor Inc."}, - {0xFE97, "Tesla Motor Inc."}, - {0xFE98, "Currant, Inc."}, - {0xFE99, "Currant, Inc."}, - {0xFE9A, "Estimote"}, - {0xFE9B, "Samsara Networks, Inc"}, - {0xFE9C, "GSI Laboratories, Inc."}, - {0xFE9D, "Mobiquity Networks Inc"}, - {0xFE9E, "Dialog Semiconductor B.V."}, - {0xFE9F, "Google Inc."}, - {0xFEA0, "Google Inc."}, - {0xFEA1, "Intrepid Control Systems, Inc."}, - {0xFEA2, "Intrepid Control Systems, Inc."}, - {0xFEA3, "ITT Industries"}, - {0xFEA4, "Paxton Access Ltd"}, - {0xFEA5, "GoPro, Inc."}, - {0xFEA6, "GoPro, Inc."}, - {0xFEA7, "UTC Fire and Security"}, - {0xFEA8, "Savant Systems LLC"}, - {0xFEA9, "Savant Systems LLC"}, - {0xFEAA, "Google Inc."}, - {0xFEAB, "Nokia Corporation"}, - {0xFEAC, "Nokia Corporation"}, - {0xFEAD, "Nokia Corporation"}, - {0xFEAE, "Nokia Corporation"}, - {0xFEAF, "Nest Labs Inc."}, - {0xFEB0, "Nest Labs Inc."}, - {0xFEB1, "Electronics Tomorrow Limited"}, - {0xFEB2, "Microsoft Corporation"}, - {0xFEB3, "Taobao"}, - {0xFEB4, "WiSilica Inc."}, - {0xFEB5, "WiSilica Inc."}, - {0xFEB6, "Vencer Co, Ltd"}, - {0xFEB7, "Facebook, Inc."}, - {0xFEB8, "Facebook, Inc."}, - {0xFEB9, "LG Electronics"}, - {0xFEBA, "Tencent Holdings Limited"}, - {0xFEBB, "adafruit industries"}, - {0xFEBC, "Dexcom, Inc. "}, - {0xFEBD, "Clover Network, Inc."}, - {0xFEBE, "Bose Corporation"}, - {0xFEBF, "Nod, Inc."}, - {0xFEC0, "KDDI Corporation"}, - {0xFEC1, "KDDI Corporation"}, - {0xFEC2, "Blue Spark Technologies, Inc."}, - {0xFEC3, "360fly, Inc."}, - {0xFEC4, "PLUS Location Systems"}, - {0xFEC5, "Realtek Semiconductor Corp."}, - {0xFEC6, "Kocomojo, LLC"}, - {0xFEC7, "Apple, Inc."}, - {0xFEC8, "Apple, Inc."}, - {0xFEC9, "Apple, Inc."}, - {0xFECA, "Apple, Inc."}, - {0xFECB, "Apple, Inc."}, - {0xFECC, "Apple, Inc."}, - {0xFECD, "Apple, Inc."}, - {0xFECE, "Apple, Inc."}, - {0xFECF, "Apple, Inc."}, - {0xFED0, "Apple, Inc."}, - {0xFED1, "Apple, Inc."}, - {0xFED2, "Apple, Inc."}, - {0xFED3, "Apple, Inc."}, - {0xFED4, "Apple, Inc."}, - {0xFED5, "Plantronics Inc."}, - {0xFED6, "Broadcom Corporation"}, - {0xFED7, "Broadcom Corporation"}, - {0xFED8, "Google Inc."}, - {0xFED9, "Pebble Technology Corporation"}, - {0xFEDA, "ISSC Technologies Corporation"}, - {0xFEDB, "Perka, Inc."}, - {0xFEDC, "Jawbone"}, - {0xFEDD, "Jawbone"}, - {0xFEDE, "Coin, Inc."}, - {0xFEDF, "Design SHIFT"}, - {0xFEE0, "Anhui Huami Information Technology Co."}, - {0xFEE1, "Anhui Huami Information Technology Co."}, - {0xFEE2, "Anki, Inc."}, - {0xFEE3, "Anki, Inc."}, - {0xFEE4, "Nordic Semiconductor ASA"}, - {0xFEE5, "Nordic Semiconductor ASA"}, - {0xFEE6, "Silvair, Inc."}, - {0xFEE7, "Tencent Holdings Limited"}, - {0xFEE8, "Quintic Corp."}, - {0xFEE9, "Quintic Corp."}, - {0xFEEA, "Swirl Networks, Inc."}, - {0xFEEB, "Swirl Networks, Inc."}, - {0xFEEC, "Tile, Inc."}, - {0xFEED, "Tile, Inc."}, - {0xFEEE, "Polar Electro Oy"}, - {0xFEEF, "Polar Electro Oy"}, - {0xFEF0, "Intel"}, - {0xFEF1, "CSR"}, - {0xFEF2, "CSR"}, - {0xFEF3, "Google Inc."}, - {0xFEF4, "Google Inc."}, - {0xFEF5, "Dialog Semiconductor GmbH"}, - {0xFEF6, "Wicentric, Inc."}, - {0xFEF7, "Aplix Corporation"}, - {0xFEF8, "Aplix Corporation"}, - {0xFEF9, "PayPal, Inc."}, - {0xFEFA, "PayPal, Inc."}, - {0xFEFB, "Telit Wireless Solutions (Formerly Stollmann E+V GmbH)"}, - {0xFEFC, "Gimbal, Inc."}, - {0xFEFD, "Gimbal, Inc."}, - {0xFEFE, "GN ReSound A/S"}, - {0xFEFF, "GN Netcom"}, - {0xFFFF, "Reserved"}, /*for testing purposes only*/ -#endif - {0, "" } -}; - -typedef struct { - uint32_t assignedNumber; - const char* name; -} gattdescriptor_t; - -static const gattdescriptor_t g_descriptor_ids[] = { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - {0x2905,"Characteristic Aggregate Format"}, - {0x2900,"Characteristic Extended Properties"}, - {0x2904,"Characteristic Presentation Format"}, - {0x2901,"Characteristic User Description"}, - {0x2902,"Client Characteristic Configuration"}, - {0x290B,"Environmental Sensing Configuration"}, - {0x290C,"Environmental Sensing Measurement"}, - {0x290D,"Environmental Sensing Trigger Setting"}, - {0x2907,"External Report Reference"}, - {0x2909,"Number of Digitals"}, - {0x2908,"Report Reference"}, - {0x2903,"Server Characteristic Configuration"}, - {0x290E,"Time Trigger Setting"}, - {0x2906,"Valid Range"}, - {0x290A,"Value Trigger Setting"}, -#endif - { 0, "" } -}; - -typedef struct { - uint32_t assignedNumber; - const char* name; -} characteristicMap_t; - -static const characteristicMap_t g_characteristicsMappings[] = { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - {0x2A7E,"Aerobic Heart Rate Lower Limit"}, - {0x2A84,"Aerobic Heart Rate Upper Limit"}, - {0x2A7F,"Aerobic Threshold"}, - {0x2A80,"Age"}, - {0x2A5A,"Aggregate"}, - {0x2A43,"Alert Category ID"}, - {0x2A42,"Alert Category ID Bit Mask"}, - {0x2A06,"Alert Level"}, - {0x2A44,"Alert Notification Control Point"}, - {0x2A3F,"Alert Status"}, - {0x2AB3,"Altitude"}, - {0x2A81,"Anaerobic Heart Rate Lower Limit"}, - {0x2A82,"Anaerobic Heart Rate Upper Limit"}, - {0x2A83,"Anaerobic Threshold"}, - {0x2A58,"Analog"}, - {0x2A59,"Analog Output"}, - {0x2A73,"Apparent Wind Direction"}, - {0x2A72,"Apparent Wind Speed"}, - {0x2A01,"Appearance"}, - {0x2AA3,"Barometric Pressure Trend"}, - {0x2A19,"Battery Level"}, - {0x2A1B,"Battery Level State"}, - {0x2A1A,"Battery Power State"}, - {0x2A49,"Blood Pressure Feature"}, - {0x2A35,"Blood Pressure Measurement"}, - {0x2A9B,"Body Composition Feature"}, - {0x2A9C,"Body Composition Measurement"}, - {0x2A38,"Body Sensor Location"}, - {0x2AA4,"Bond Management Control Point"}, - {0x2AA5,"Bond Management Features"}, - {0x2A22,"Boot Keyboard Input Report"}, - {0x2A32,"Boot Keyboard Output Report"}, - {0x2A33,"Boot Mouse Input Report"}, - {0x2AA6,"Central Address Resolution"}, - {0x2AA8,"CGM Feature"}, - {0x2AA7,"CGM Measurement"}, - {0x2AAB,"CGM Session Run Time"}, - {0x2AAA,"CGM Session Start Time"}, - {0x2AAC,"CGM Specific Ops Control Point"}, - {0x2AA9,"CGM Status"}, - {0x2ACE,"Cross Trainer Data"}, - {0x2A5C,"CSC Feature"}, - {0x2A5B,"CSC Measurement"}, - {0x2A2B,"Current Time"}, - {0x2A66,"Cycling Power Control Point"}, - {0x2A66,"Cycling Power Control Point"}, - {0x2A65,"Cycling Power Feature"}, - {0x2A65,"Cycling Power Feature"}, - {0x2A63,"Cycling Power Measurement"}, - {0x2A64,"Cycling Power Vector"}, - {0x2A99,"Database Change Increment"}, - {0x2A85,"Date of Birth"}, - {0x2A86,"Date of Threshold Assessment"}, - {0x2A08,"Date Time"}, - {0x2A0A,"Day Date Time"}, - {0x2A09,"Day of Week"}, - {0x2A7D,"Descriptor Value Changed"}, - {0x2A00,"Device Name"}, - {0x2A7B,"Dew Point"}, - {0x2A56,"Digital"}, - {0x2A57,"Digital Output"}, - {0x2A0D,"DST Offset"}, - {0x2A6C,"Elevation"}, - {0x2A87,"Email Address"}, - {0x2A0B,"Exact Time 100"}, - {0x2A0C,"Exact Time 256"}, - {0x2A88,"Fat Burn Heart Rate Lower Limit"}, - {0x2A89,"Fat Burn Heart Rate Upper Limit"}, - {0x2A26,"Firmware Revision String"}, - {0x2A8A,"First Name"}, - {0x2AD9,"Fitness Machine Control Point"}, - {0x2ACC,"Fitness Machine Feature"}, - {0x2ADA,"Fitness Machine Status"}, - {0x2A8B,"Five Zone Heart Rate Limits"}, - {0x2AB2,"Floor Number"}, - {0x2A8C,"Gender"}, - {0x2A51,"Glucose Feature"}, - {0x2A18,"Glucose Measurement"}, - {0x2A34,"Glucose Measurement Context"}, - {0x2A74,"Gust Factor"}, - {0x2A27,"Hardware Revision String"}, - {0x2A39,"Heart Rate Control Point"}, - {0x2A8D,"Heart Rate Max"}, - {0x2A37,"Heart Rate Measurement"}, - {0x2A7A,"Heat Index"}, - {0x2A8E,"Height"}, - {0x2A4C,"HID Control Point"}, - {0x2A4A,"HID Information"}, - {0x2A8F,"Hip Circumference"}, - {0x2ABA,"HTTP Control Point"}, - {0x2AB9,"HTTP Entity Body"}, - {0x2AB7,"HTTP Headers"}, - {0x2AB8,"HTTP Status Code"}, - {0x2ABB,"HTTPS Security"}, - {0x2A6F,"Humidity"}, - {0x2A2A,"IEEE 11073-20601 Regulatory Certification Data List"}, - {0x2AD2,"Indoor Bike Data"}, - {0x2AAD,"Indoor Positioning Configuration"}, - {0x2A36,"Intermediate Cuff Pressure"}, - {0x2A1E,"Intermediate Temperature"}, - {0x2A77,"Irradiance"}, - {0x2AA2,"Language"}, - {0x2A90,"Last Name"}, - {0x2AAE,"Latitude"}, - {0x2A6B,"LN Control Point"}, - {0x2A6A,"LN Feature"}, - {0x2AB1,"Local East Coordinate"}, - {0x2AB0,"Local North Coordinate"}, - {0x2A0F,"Local Time Information"}, - {0x2A67,"Location and Speed Characteristic"}, - {0x2AB5,"Location Name"}, - {0x2AAF,"Longitude"}, - {0x2A2C,"Magnetic Declination"}, - {0x2AA0,"Magnetic Flux Density - 2D"}, - {0x2AA1,"Magnetic Flux Density - 3D"}, - {0x2A29,"Manufacturer Name String"}, - {0x2A91,"Maximum Recommended Heart Rate"}, - {0x2A21,"Measurement Interval"}, - {0x2A24,"Model Number String"}, - {0x2A68,"Navigation"}, - {0x2A3E,"Network Availability"}, - {0x2A46,"New Alert"}, - {0x2AC5,"Object Action Control Point"}, - {0x2AC8,"Object Changed"}, - {0x2AC1,"Object First-Created"}, - {0x2AC3,"Object ID"}, - {0x2AC2,"Object Last-Modified"}, - {0x2AC6,"Object List Control Point"}, - {0x2AC7,"Object List Filter"}, - {0x2ABE,"Object Name"}, - {0x2AC4,"Object Properties"}, - {0x2AC0,"Object Size"}, - {0x2ABF,"Object Type"}, - {0x2ABD,"OTS Feature"}, - {0x2A04,"Peripheral Preferred Connection Parameters"}, - {0x2A02,"Peripheral Privacy Flag"}, - {0x2A5F,"PLX Continuous Measurement Characteristic"}, - {0x2A60,"PLX Features"}, - {0x2A5E,"PLX Spot-Check Measurement"}, - {0x2A50,"PnP ID"}, - {0x2A75,"Pollen Concentration"}, - {0x2A2F,"Position 2D"}, - {0x2A30,"Position 3D"}, - {0x2A69,"Position Quality"}, - {0x2A6D,"Pressure"}, - {0x2A4E,"Protocol Mode"}, - {0x2A62,"Pulse Oximetry Control Point"}, - {0x2A60,"Pulse Oximetry Pulsatile Event Characteristic"}, - {0x2A78,"Rainfall"}, - {0x2A03,"Reconnection Address"}, - {0x2A52,"Record Access Control Point"}, - {0x2A14,"Reference Time Information"}, - {0x2A3A,"Removable"}, - {0x2A4D,"Report"}, - {0x2A4B,"Report Map"}, - {0x2AC9,"Resolvable Private Address Only"}, - {0x2A92,"Resting Heart Rate"}, - {0x2A40,"Ringer Control point"}, - {0x2A41,"Ringer Setting"}, - {0x2AD1,"Rower Data"}, - {0x2A54,"RSC Feature"}, - {0x2A53,"RSC Measurement"}, - {0x2A55,"SC Control Point"}, - {0x2A4F,"Scan Interval Window"}, - {0x2A31,"Scan Refresh"}, - {0x2A3C,"Scientific Temperature Celsius"}, - {0x2A10,"Secondary Time Zone"}, - {0x2A5D,"Sensor Location"}, - {0x2A25,"Serial Number String"}, - {0x2A05,"Service Changed"}, - {0x2A3B,"Service Required"}, - {0x2A28,"Software Revision String"}, - {0x2A93,"Sport Type for Aerobic and Anaerobic Thresholds"}, - {0x2AD0,"Stair Climber Data"}, - {0x2ACF,"Step Climber Data"}, - {0x2A3D,"String"}, - {0x2AD7,"Supported Heart Rate Range"}, - {0x2AD5,"Supported Inclination Range"}, - {0x2A47,"Supported New Alert Category"}, - {0x2AD8,"Supported Power Range"}, - {0x2AD6,"Supported Resistance Level Range"}, - {0x2AD4,"Supported Speed Range"}, - {0x2A48,"Supported Unread Alert Category"}, - {0x2A23,"System ID"}, - {0x2ABC,"TDS Control Point"}, - {0x2A6E,"Temperature"}, - {0x2A1F,"Temperature Celsius"}, - {0x2A20,"Temperature Fahrenheit"}, - {0x2A1C,"Temperature Measurement"}, - {0x2A1D,"Temperature Type"}, - {0x2A94,"Three Zone Heart Rate Limits"}, - {0x2A12,"Time Accuracy"}, - {0x2A15,"Time Broadcast"}, - {0x2A13,"Time Source"}, - {0x2A16,"Time Update Control Point"}, - {0x2A17,"Time Update State"}, - {0x2A11,"Time with DST"}, - {0x2A0E,"Time Zone"}, - {0x2AD3,"Training Status"}, - {0x2ACD,"Treadmill Data"}, - {0x2A71,"True Wind Direction"}, - {0x2A70,"True Wind Speed"}, - {0x2A95,"Two Zone Heart Rate Limit"}, - {0x2A07,"Tx Power Level"}, - {0x2AB4,"Uncertainty"}, - {0x2A45,"Unread Alert Status"}, - {0x2AB6,"URI"}, - {0x2A9F,"User Control Point"}, - {0x2A9A,"User Index"}, - {0x2A76,"UV Index"}, - {0x2A96,"VO2 Max"}, - {0x2A97,"Waist Circumference"}, - {0x2A98,"Weight"}, - {0x2A9D,"Weight Measurement"}, - {0x2A9E,"Weight Scale Feature"}, - {0x2A79,"Wind Chill"}, -#endif - {0, ""} -}; - -/** - * @brief Mapping from service ids to names - */ -typedef struct { - const char* name; - const char* type; - uint32_t assignedNumber; -} gattService_t; - - -/** - * Definition of the service ids to names that we know about. - */ -static const gattService_t g_gattServices[] = { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - {"Alert Notification Service", "org.bluetooth.service.alert_notification", 0x1811}, - {"Automation IO", "org.bluetooth.service.automation_io", 0x1815 }, - {"Battery Service","org.bluetooth.service.battery_service", 0x180F}, - {"Blood Pressure", "org.bluetooth.service.blood_pressure", 0x1810}, - {"Body Composition", "org.bluetooth.service.body_composition", 0x181B}, - {"Bond Management", "org.bluetooth.service.bond_management", 0x181E}, - {"Continuous Glucose Monitoring", "org.bluetooth.service.continuous_glucose_monitoring", 0x181F}, - {"Current Time Service", "org.bluetooth.service.current_time", 0x1805}, - {"Cycling Power", "org.bluetooth.service.cycling_power", 0x1818}, - {"Cycling Speed and Cadence", "org.bluetooth.service.cycling_speed_and_cadence", 0x1816}, - {"Device Information", "org.bluetooth.service.device_information", 0x180A}, - {"Environmental Sensing", "org.bluetooth.service.environmental_sensing", 0x181A}, - {"Generic Access", "org.bluetooth.service.generic_access", 0x1800}, - {"Generic Attribute", "org.bluetooth.service.generic_attribute", 0x1801}, - {"Glucose", "org.bluetooth.service.glucose", 0x1808}, - {"Health Thermometer", "org.bluetooth.service.health_thermometer", 0x1809}, - {"Heart Rate", "org.bluetooth.service.heart_rate", 0x180D}, - {"HTTP Proxy", "org.bluetooth.service.http_proxy", 0x1823}, - {"Human Interface Device", "org.bluetooth.service.human_interface_device", 0x1812}, - {"Immediate Alert", "org.bluetooth.service.immediate_alert", 0x1802}, - {"Indoor Positioning", "org.bluetooth.service.indoor_positioning", 0x1821}, - {"Internet Protocol Support", "org.bluetooth.service.internet_protocol_support", 0x1820}, - {"Link Loss", "org.bluetooth.service.link_loss", 0x1803}, - {"Location and Navigation", "org.bluetooth.service.location_and_navigation", 0x1819}, - {"Next DST Change Service", "org.bluetooth.service.next_dst_change", 0x1807}, - {"Object Transfer", "org.bluetooth.service.object_transfer", 0x1825}, - {"Phone Alert Status Service", "org.bluetooth.service.phone_alert_status", 0x180E}, - {"Pulse Oximeter", "org.bluetooth.service.pulse_oximeter", 0x1822}, - {"Reference Time Update Service", "org.bluetooth.service.reference_time_update", 0x1806}, - {"Running Speed and Cadence", "org.bluetooth.service.running_speed_and_cadence", 0x1814}, - {"Scan Parameters", "org.bluetooth.service.scan_parameters", 0x1813}, - {"Transport Discovery", "org.bluetooth.service.transport_discovery", 0x1824}, - {"Tx Power", "org.bluetooth.service.tx_power", 0x1804}, - {"User Data", "org.bluetooth.service.user_data", 0x181C}, - {"Weight Scale", "org.bluetooth.service.weight_scale", 0x181D}, -#endif - {"", "", 0 } -}; - - -/** - * @brief Convert characteristic properties into a string representation. - * @param [in] prop Characteristic properties. - * @return A string representation of characteristic properties. - */ -std::string BLEUtils::characteristicPropertiesToString(esp_gatt_char_prop_t prop) { - std::string res = "broadcast: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_BROADCAST)?"1":"0"); - res += ", read: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_READ)?"1":"0"); - res += ", write_nr: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE_NR)?"1":"0"); - res += ", write: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_WRITE)?"1":"0"); - res += ", notify: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_NOTIFY)?"1":"0"); - res += ", indicate: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_INDICATE)?"1":"0"); - res += ", auth: "; - res += ((prop & ESP_GATT_CHAR_PROP_BIT_AUTH)?"1":"0"); - return res; -} // characteristicPropertiesToString - -/** - * @brief Convert an esp_gatt_id_t to a string. - */ -static std::string gattIdToString(esp_gatt_id_t gattId) { - std::string res = "uuid: " + BLEUUID(gattId.uuid).toString() + ", inst_id: "; - char val[8]; - snprintf(val, sizeof(val), "%d", (int)gattId.inst_id); - res += val; - return res; -} // gattIdToString - - -/** - * @brief Convert an esp_ble_addr_type_t to a string representation. - */ -const char* BLEUtils::addressTypeToString(esp_ble_addr_type_t type) { - switch (type) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case BLE_ADDR_TYPE_PUBLIC: - return "BLE_ADDR_TYPE_PUBLIC"; - case BLE_ADDR_TYPE_RANDOM: - return "BLE_ADDR_TYPE_RANDOM"; - case BLE_ADDR_TYPE_RPA_PUBLIC: - return "BLE_ADDR_TYPE_RPA_PUBLIC"; - case BLE_ADDR_TYPE_RPA_RANDOM: - return "BLE_ADDR_TYPE_RPA_RANDOM"; -#endif - default: - return " esp_ble_addr_type_t"; - } -} // addressTypeToString - - -/** - * @brief Convert the BLE Advertising Data flags to a string. - * @param adFlags The flags to convert - * @return std::string A string representation of the advertising flags. - */ -std::string BLEUtils::adFlagsToString(uint8_t adFlags) { - std::string res; - if (adFlags & (1 << 0)) { - res += "[LE Limited Discoverable Mode] "; - } - if (adFlags & (1 << 1)) { - res += "[LE General Discoverable Mode] "; - } - if (adFlags & (1 << 2)) { - res += "[BR/EDR Not Supported] "; - } - if (adFlags & (1 << 3)) { - res += "[Simultaneous LE and BR/EDR to Same Device Capable (Controller)] "; - } - if (adFlags & (1 << 4)) { - res += "[Simultaneous LE and BR/EDR to Same Device Capable (Host)] "; - } - return res; -} // adFlagsToString - - -/** - * @brief Given an advertising type, return a string representation of the type. - * - * For details see ... - * https://www.bluetooth.com/specifications/assigned-numbers/generic-access-profile - * - * @return A string representation of the type. - */ -const char* BLEUtils::advTypeToString(uint8_t advType) { - switch (advType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_BLE_AD_TYPE_FLAG: // 0x01 - return "ESP_BLE_AD_TYPE_FLAG"; - case ESP_BLE_AD_TYPE_16SRV_PART: // 0x02 - return "ESP_BLE_AD_TYPE_16SRV_PART"; - case ESP_BLE_AD_TYPE_16SRV_CMPL: // 0x03 - return "ESP_BLE_AD_TYPE_16SRV_CMPL"; - case ESP_BLE_AD_TYPE_32SRV_PART: // 0x04 - return "ESP_BLE_AD_TYPE_32SRV_PART"; - case ESP_BLE_AD_TYPE_32SRV_CMPL: // 0x05 - return "ESP_BLE_AD_TYPE_32SRV_CMPL"; - case ESP_BLE_AD_TYPE_128SRV_PART: // 0x06 - return "ESP_BLE_AD_TYPE_128SRV_PART"; - case ESP_BLE_AD_TYPE_128SRV_CMPL: // 0x07 - return "ESP_BLE_AD_TYPE_128SRV_CMPL"; - case ESP_BLE_AD_TYPE_NAME_SHORT: // 0x08 - return "ESP_BLE_AD_TYPE_NAME_SHORT"; - case ESP_BLE_AD_TYPE_NAME_CMPL: // 0x09 - return "ESP_BLE_AD_TYPE_NAME_CMPL"; - case ESP_BLE_AD_TYPE_TX_PWR: // 0x0a - return "ESP_BLE_AD_TYPE_TX_PWR"; - case ESP_BLE_AD_TYPE_DEV_CLASS: // 0x0b - return "ESP_BLE_AD_TYPE_DEV_CLASS"; - case ESP_BLE_AD_TYPE_SM_TK: // 0x10 - return "ESP_BLE_AD_TYPE_SM_TK"; - case ESP_BLE_AD_TYPE_SM_OOB_FLAG: // 0x11 - return "ESP_BLE_AD_TYPE_SM_OOB_FLAG"; - case ESP_BLE_AD_TYPE_INT_RANGE: // 0x12 - return "ESP_BLE_AD_TYPE_INT_RANGE"; - case ESP_BLE_AD_TYPE_SOL_SRV_UUID: // 0x14 - return "ESP_BLE_AD_TYPE_SOL_SRV_UUID"; - case ESP_BLE_AD_TYPE_128SOL_SRV_UUID: // 0x15 - return "ESP_BLE_AD_TYPE_128SOL_SRV_UUID"; - case ESP_BLE_AD_TYPE_SERVICE_DATA: // 0x16 - return "ESP_BLE_AD_TYPE_SERVICE_DATA"; - case ESP_BLE_AD_TYPE_PUBLIC_TARGET: // 0x17 - return "ESP_BLE_AD_TYPE_PUBLIC_TARGET"; - case ESP_BLE_AD_TYPE_RANDOM_TARGET: // 0x18 - return "ESP_BLE_AD_TYPE_RANDOM_TARGET"; - case ESP_BLE_AD_TYPE_APPEARANCE: // 0x19 - return "ESP_BLE_AD_TYPE_APPEARANCE"; - case ESP_BLE_AD_TYPE_ADV_INT: // 0x1a - return "ESP_BLE_AD_TYPE_ADV_INT"; - case ESP_BLE_AD_TYPE_32SOL_SRV_UUID: - return "ESP_BLE_AD_TYPE_32SOL_SRV_UUID"; - case ESP_BLE_AD_TYPE_32SERVICE_DATA: // 0x20 - return "ESP_BLE_AD_TYPE_32SERVICE_DATA"; - case ESP_BLE_AD_TYPE_128SERVICE_DATA: // 0x21 - return "ESP_BLE_AD_TYPE_128SERVICE_DATA"; - case ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE: // 0xff - return "ESP_BLE_AD_MANUFACTURER_SPECIFIC_TYPE"; -#endif - default: - log_v(" adv data type: 0x%x", advType); - return ""; - } // End switch -} // advTypeToString - - -esp_gatt_id_t BLEUtils::buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id) { - esp_gatt_id_t retGattId; - retGattId.uuid = uuid; - retGattId.inst_id = inst_id; - return retGattId; -} - -esp_gatt_srvc_id_t BLEUtils::buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary) { - esp_gatt_srvc_id_t retSrvcId; - retSrvcId.id = gattId; - retSrvcId.is_primary = is_primary; - return retSrvcId; -} - -/** - * @brief Create a hex representation of data. - * - * @param [in] target Where to write the hex string. If this is null, we malloc storage. - * @param [in] source The start of the binary data. - * @param [in] length The length of the data to convert. - * @return A pointer to the formatted buffer. - */ -char* BLEUtils::buildHexData(uint8_t* target, uint8_t* source, uint8_t length) { - // Guard against too much data. - if (length > 100) length = 100; - - if (target == nullptr) { - target = (uint8_t*) malloc(length * 2 + 1); - if (target == nullptr) { - log_e("buildHexData: malloc failed"); - return nullptr; - } - } - char* startOfData = (char*) target; - - for (int i = 0; i < length; i++) { - sprintf((char*) target, "%.2x", (char) *source); - source++; - target += 2; - } - - // Handle the special case where there was no data. - if (length == 0) { - *startOfData = 0; - } - - return startOfData; -} // buildHexData - - -/** - * @brief Build a printable string of memory range. - * Create a string representation of a piece of memory. Only printable characters will be included - * while those that are not printable will be replaced with '.'. - * @param [in] source Start of memory. - * @param [in] length Length of memory. - * @return A string representation of a piece of memory. - */ -std::string BLEUtils::buildPrintData(uint8_t* source, size_t length) { - std::string res; - for (int i = 0; i < length; i++) { - char c = *source; - res += (isprint(c) ? c : '.'); - source++; - } - return res; -} // buildPrintData - - -/** - * @brief Convert a close/disconnect reason to a string. - * @param [in] reason The close reason. - * @return A string representation of the reason. - */ -std::string BLEUtils::gattCloseReasonToString(esp_gatt_conn_reason_t reason) { - switch (reason) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GATT_CONN_UNKNOWN: { - return "ESP_GATT_CONN_UNKNOWN"; - } - case ESP_GATT_CONN_L2C_FAILURE: { - return "ESP_GATT_CONN_L2C_FAILURE"; - } - case ESP_GATT_CONN_TIMEOUT: { - return "ESP_GATT_CONN_TIMEOUT"; - } - case ESP_GATT_CONN_TERMINATE_PEER_USER: { - return "ESP_GATT_CONN_TERMINATE_PEER_USER"; - } - case ESP_GATT_CONN_TERMINATE_LOCAL_HOST: { - return "ESP_GATT_CONN_TERMINATE_LOCAL_HOST"; - } - case ESP_GATT_CONN_FAIL_ESTABLISH: { - return "ESP_GATT_CONN_FAIL_ESTABLISH"; - } - case ESP_GATT_CONN_LMP_TIMEOUT: { - return "ESP_GATT_CONN_LMP_TIMEOUT"; - } - case ESP_GATT_CONN_CONN_CANCEL: { - return "ESP_GATT_CONN_CONN_CANCEL"; - } - case ESP_GATT_CONN_NONE: { - return "ESP_GATT_CONN_NONE"; - } -#endif - default: { - return "Unknown"; - } - } -} // gattCloseReasonToString - - -std::string BLEUtils::gattClientEventTypeToString(esp_gattc_cb_event_t eventType) { - switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GATTC_ACL_EVT: - return "ESP_GATTC_ACL_EVT"; - case ESP_GATTC_ADV_DATA_EVT: - return "ESP_GATTC_ADV_DATA_EVT"; - case ESP_GATTC_ADV_VSC_EVT: - return "ESP_GATTC_ADV_VSC_EVT"; - case ESP_GATTC_BTH_SCAN_CFG_EVT: - return "ESP_GATTC_BTH_SCAN_CFG_EVT"; - case ESP_GATTC_BTH_SCAN_DIS_EVT: - return "ESP_GATTC_BTH_SCAN_DIS_EVT"; - case ESP_GATTC_BTH_SCAN_ENB_EVT: - return "ESP_GATTC_BTH_SCAN_ENB_EVT"; - case ESP_GATTC_BTH_SCAN_PARAM_EVT: - return "ESP_GATTC_BTH_SCAN_PARAM_EVT"; - case ESP_GATTC_BTH_SCAN_RD_EVT: - return "ESP_GATTC_BTH_SCAN_RD_EVT"; - case ESP_GATTC_BTH_SCAN_THR_EVT: - return "ESP_GATTC_BTH_SCAN_THR_EVT"; - case ESP_GATTC_CANCEL_OPEN_EVT: - return "ESP_GATTC_CANCEL_OPEN_EVT"; - case ESP_GATTC_CFG_MTU_EVT: - return "ESP_GATTC_CFG_MTU_EVT"; - case ESP_GATTC_CLOSE_EVT: - return "ESP_GATTC_CLOSE_EVT"; - case ESP_GATTC_CONGEST_EVT: - return "ESP_GATTC_CONGEST_EVT"; - case ESP_GATTC_CONNECT_EVT: - return "ESP_GATTC_CONNECT_EVT"; - case ESP_GATTC_DISCONNECT_EVT: - return "ESP_GATTC_DISCONNECT_EVT"; - case ESP_GATTC_ENC_CMPL_CB_EVT: - return "ESP_GATTC_ENC_CMPL_CB_EVT"; - case ESP_GATTC_EXEC_EVT: - return "ESP_GATTC_EXEC_EVT"; - //case ESP_GATTC_GET_CHAR_EVT: -// return "ESP_GATTC_GET_CHAR_EVT"; - //case ESP_GATTC_GET_DESCR_EVT: -// return "ESP_GATTC_GET_DESCR_EVT"; - //case ESP_GATTC_GET_INCL_SRVC_EVT: -// return "ESP_GATTC_GET_INCL_SRVC_EVT"; - case ESP_GATTC_MULT_ADV_DATA_EVT: - return "ESP_GATTC_MULT_ADV_DATA_EVT"; - case ESP_GATTC_MULT_ADV_DIS_EVT: - return "ESP_GATTC_MULT_ADV_DIS_EVT"; - case ESP_GATTC_MULT_ADV_ENB_EVT: - return "ESP_GATTC_MULT_ADV_ENB_EVT"; - case ESP_GATTC_MULT_ADV_UPD_EVT: - return "ESP_GATTC_MULT_ADV_UPD_EVT"; - case ESP_GATTC_NOTIFY_EVT: - return "ESP_GATTC_NOTIFY_EVT"; - case ESP_GATTC_OPEN_EVT: - return "ESP_GATTC_OPEN_EVT"; - case ESP_GATTC_PREP_WRITE_EVT: - return "ESP_GATTC_PREP_WRITE_EVT"; - case ESP_GATTC_READ_CHAR_EVT: - return "ESP_GATTC_READ_CHAR_EVT"; - case ESP_GATTC_REG_EVT: - return "ESP_GATTC_REG_EVT"; - case ESP_GATTC_REG_FOR_NOTIFY_EVT: - return "ESP_GATTC_REG_FOR_NOTIFY_EVT"; - case ESP_GATTC_SCAN_FLT_CFG_EVT: - return "ESP_GATTC_SCAN_FLT_CFG_EVT"; - case ESP_GATTC_SCAN_FLT_PARAM_EVT: - return "ESP_GATTC_SCAN_FLT_PARAM_EVT"; - case ESP_GATTC_SCAN_FLT_STATUS_EVT: - return "ESP_GATTC_SCAN_FLT_STATUS_EVT"; - case ESP_GATTC_SEARCH_CMPL_EVT: - return "ESP_GATTC_SEARCH_CMPL_EVT"; - case ESP_GATTC_SEARCH_RES_EVT: - return "ESP_GATTC_SEARCH_RES_EVT"; - case ESP_GATTC_SRVC_CHG_EVT: - return "ESP_GATTC_SRVC_CHG_EVT"; - case ESP_GATTC_READ_DESCR_EVT: - return "ESP_GATTC_READ_DESCR_EVT"; - case ESP_GATTC_UNREG_EVT: - return "ESP_GATTC_UNREG_EVT"; - case ESP_GATTC_UNREG_FOR_NOTIFY_EVT: - return "ESP_GATTC_UNREG_FOR_NOTIFY_EVT"; - case ESP_GATTC_WRITE_CHAR_EVT: - return "ESP_GATTC_WRITE_CHAR_EVT"; - case ESP_GATTC_WRITE_DESCR_EVT: - return "ESP_GATTC_WRITE_DESCR_EVT"; -#endif - default: - log_v("Unknown GATT Client event type: %d", eventType); - return "Unknown"; - } -} // gattClientEventTypeToString - - -/** - * @brief Return a string representation of a GATT server event code. - * @param [in] eventType A GATT server event code. - * @return A string representation of the GATT server event code. - */ -std::string BLEUtils::gattServerEventTypeToString(esp_gatts_cb_event_t eventType) { - switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GATTS_REG_EVT: - return "ESP_GATTS_REG_EVT"; - case ESP_GATTS_READ_EVT: - return "ESP_GATTS_READ_EVT"; - case ESP_GATTS_WRITE_EVT: - return "ESP_GATTS_WRITE_EVT"; - case ESP_GATTS_EXEC_WRITE_EVT: - return "ESP_GATTS_EXEC_WRITE_EVT"; - case ESP_GATTS_MTU_EVT: - return "ESP_GATTS_MTU_EVT"; - case ESP_GATTS_CONF_EVT: - return "ESP_GATTS_CONF_EVT"; - case ESP_GATTS_UNREG_EVT: - return "ESP_GATTS_UNREG_EVT"; - case ESP_GATTS_CREATE_EVT: - return "ESP_GATTS_CREATE_EVT"; - case ESP_GATTS_ADD_INCL_SRVC_EVT: - return "ESP_GATTS_ADD_INCL_SRVC_EVT"; - case ESP_GATTS_ADD_CHAR_EVT: - return "ESP_GATTS_ADD_CHAR_EVT"; - case ESP_GATTS_ADD_CHAR_DESCR_EVT: - return "ESP_GATTS_ADD_CHAR_DESCR_EVT"; - case ESP_GATTS_DELETE_EVT: - return "ESP_GATTS_DELETE_EVT"; - case ESP_GATTS_START_EVT: - return "ESP_GATTS_START_EVT"; - case ESP_GATTS_STOP_EVT: - return "ESP_GATTS_STOP_EVT"; - case ESP_GATTS_CONNECT_EVT: - return "ESP_GATTS_CONNECT_EVT"; - case ESP_GATTS_DISCONNECT_EVT: - return "ESP_GATTS_DISCONNECT_EVT"; - case ESP_GATTS_OPEN_EVT: - return "ESP_GATTS_OPEN_EVT"; - case ESP_GATTS_CANCEL_OPEN_EVT: - return "ESP_GATTS_CANCEL_OPEN_EVT"; - case ESP_GATTS_CLOSE_EVT: - return "ESP_GATTS_CLOSE_EVT"; - case ESP_GATTS_LISTEN_EVT: - return "ESP_GATTS_LISTEN_EVT"; - case ESP_GATTS_CONGEST_EVT: - return "ESP_GATTS_CONGEST_EVT"; - case ESP_GATTS_RESPONSE_EVT: - return "ESP_GATTS_RESPONSE_EVT"; - case ESP_GATTS_CREAT_ATTR_TAB_EVT: - return "ESP_GATTS_CREAT_ATTR_TAB_EVT"; - case ESP_GATTS_SET_ATTR_VAL_EVT: - return "ESP_GATTS_SET_ATTR_VAL_EVT"; - case ESP_GATTS_SEND_SERVICE_CHANGE_EVT: - return "ESP_GATTS_SEND_SERVICE_CHANGE_EVT"; -#endif - default: - return "Unknown"; - } -} // gattServerEventTypeToString - - - -/** - * @brief Convert a BLE device type to a string. - * @param [in] type The device type. - */ -const char* BLEUtils::devTypeToString(esp_bt_dev_type_t type) { - switch (type) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_BT_DEVICE_TYPE_BREDR: - return "ESP_BT_DEVICE_TYPE_BREDR"; - case ESP_BT_DEVICE_TYPE_BLE: - return "ESP_BT_DEVICE_TYPE_BLE"; - case ESP_BT_DEVICE_TYPE_DUMO: - return "ESP_BT_DEVICE_TYPE_DUMO"; -#endif - default: - return "Unknown"; - } -} // devTypeToString - - -/** - * @brief Dump the GAP event to the log. - */ -void BLEUtils::dumpGapEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param) { - log_v("Received a GAP event: %s", gapEventToString(event)); - switch (event) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT - // adv_data_cmpl - // - esp_bt_status_t - case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_data_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT - - // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT - // - // adv_data_raw_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_data_raw_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT - - // ESP_GAP_BLE_ADV_START_COMPLETE_EVT - // - // adv_start_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_start_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_START_COMPLETE_EVT - - // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT - // - // adv_stop_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: { - log_v("[status: %d]", param->adv_stop_cmpl.status); - break; - } // ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT - - // ESP_GAP_BLE_AUTH_CMPL_EVT - // - // auth_cmpl - // - esp_bd_addr_t bd_addr - // - bool key_present - // - esp_link_key key - // - bool success - // - uint8_t fail_reason - // - esp_bd_addr_type_t addr_type - // - esp_bt_dev_type_t dev_type - case ESP_GAP_BLE_AUTH_CMPL_EVT: { - log_v("[bd_addr: %s, key_present: %d, key: ***, key_type: %d, success: %d, fail_reason: %d, addr_type: ***, dev_type: %s]", - BLEAddress(param->ble_security.auth_cmpl.bd_addr).toString().c_str(), - param->ble_security.auth_cmpl.key_present, - param->ble_security.auth_cmpl.key_type, - param->ble_security.auth_cmpl.success, - param->ble_security.auth_cmpl.fail_reason, - BLEUtils::devTypeToString(param->ble_security.auth_cmpl.dev_type) - ); - break; - } // ESP_GAP_BLE_AUTH_CMPL_EVT - - // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT - // - // clear_bond_dev_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: { - log_v("[status: %d]", param->clear_bond_dev_cmpl.status); - break; - } // ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT - - // ESP_GAP_BLE_LOCAL_IR_EVT - case ESP_GAP_BLE_LOCAL_IR_EVT: { - break; - } // ESP_GAP_BLE_LOCAL_IR_EVT - - // ESP_GAP_BLE_LOCAL_ER_EVT - case ESP_GAP_BLE_LOCAL_ER_EVT: { - break; - } // ESP_GAP_BLE_LOCAL_ER_EVT - - // ESP_GAP_BLE_NC_REQ_EVT - case ESP_GAP_BLE_NC_REQ_EVT: { - log_v("[bd_addr: %s, passkey: %d]", - BLEAddress(param->ble_security.key_notif.bd_addr).toString().c_str(), - param->ble_security.key_notif.passkey); - break; - } // ESP_GAP_BLE_NC_REQ_EVT - - // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - // - // read_rssi_cmpl - // - esp_bt_status_t status - // - int8_t rssi - // - esp_bd_addr_t remote_addr - case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: { - log_v("[status: %d, rssi: %d, remote_addr: %s]", - param->read_rssi_cmpl.status, - param->read_rssi_cmpl.rssi, - BLEAddress(param->read_rssi_cmpl.remote_addr).toString().c_str() - ); - break; - } // ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT - - // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT - // - // scan_param_cmpl. - // - esp_bt_status_t status - case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_param_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT - - // ESP_GAP_BLE_SCAN_RESULT_EVT - // - // scan_rst: - // - search_evt - // - bda - // - dev_type - // - ble_addr_type - // - ble_evt_type - // - rssi - // - ble_adv - // - flag - // - num_resps - // - adv_data_len - // - scan_rsp_len - case ESP_GAP_BLE_SCAN_RESULT_EVT: { - switch (param->scan_rst.search_evt) { - case ESP_GAP_SEARCH_INQ_RES_EVT: { - log_v("search_evt: %s, bda: %s, dev_type: %s, ble_addr_type: %s, ble_evt_type: %s, rssi: %d, ble_adv: ??, flag: %d (%s), num_resps: %d, adv_data_len: %d, scan_rsp_len: %d", - searchEventTypeToString(param->scan_rst.search_evt), - BLEAddress(param->scan_rst.bda).toString().c_str(), - devTypeToString(param->scan_rst.dev_type), - addressTypeToString(param->scan_rst.ble_addr_type), - eventTypeToString(param->scan_rst.ble_evt_type), - param->scan_rst.rssi, - param->scan_rst.flag, - adFlagsToString(param->scan_rst.flag).c_str(), - param->scan_rst.num_resps, - param->scan_rst.adv_data_len, - param->scan_rst.scan_rsp_len - ); - break; - } // ESP_GAP_SEARCH_INQ_RES_EVT - - default: { - log_v("search_evt: %s",searchEventTypeToString(param->scan_rst.search_evt)); - break; - } - } - break; - } // ESP_GAP_BLE_SCAN_RESULT_EVT - - // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT - // - // scan_rsp_data_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_rsp_data_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT - - // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT - case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_rsp_data_raw_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT - - // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT - // - // scan_start_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_start_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_START_COMPLETE_EVT - - // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT - // - // scan_stop_cmpl - // - esp_bt_status_t status - case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: { - log_v("[status: %d]", param->scan_stop_cmpl.status); - break; - } // ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT - - // ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT - // - // update_conn_params - // - esp_bt_status_t status - // - esp_bd_addr_t bda - // - uint16_t min_int - // - uint16_t max_int - // - uint16_t latency - // - uint16_t conn_int - // - uint16_t timeout - case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: { - log_v("[status: %d, bd_addr: %s, min_int: %d, max_int: %d, latency: %d, conn_int: %d, timeout: %d]", - param->update_conn_params.status, - BLEAddress(param->update_conn_params.bda).toString().c_str(), - param->update_conn_params.min_int, - param->update_conn_params.max_int, - param->update_conn_params.latency, - param->update_conn_params.conn_int, - param->update_conn_params.timeout - ); - break; - } // ESP_GAP_BLE_SCAN_UPDATE_CONN_PARAMS_EVT - - // ESP_GAP_BLE_SEC_REQ_EVT - case ESP_GAP_BLE_SEC_REQ_EVT: { - log_v("[bd_addr: %s]", BLEAddress(param->ble_security.ble_req.bd_addr).toString().c_str()); - break; - } // ESP_GAP_BLE_SEC_REQ_EVT -#endif - default: { - log_v("*** dumpGapEvent: Logger not coded ***"); - break; - } // default - } // switch -} // dumpGapEvent - - -/** - * @brief Decode and dump a GATT client event - * - * @param [in] event The type of event received. - * @param [in] evtParam The data associated with the event. - */ -void BLEUtils::dumpGattClientEvent( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam) { - - //esp_ble_gattc_cb_param_t* evtParam = (esp_ble_gattc_cb_param_t*) param; - log_v("GATT Event: %s", BLEUtils::gattClientEventTypeToString(event).c_str()); - switch (event) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - // ESP_GATTC_CLOSE_EVT - // - // close: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - esp_gatt_conn_reason_t reason - case ESP_GATTC_CLOSE_EVT: { - log_v("[status: %s, reason:%s, conn_id: %d]", - BLEUtils::gattStatusToString(evtParam->close.status).c_str(), - BLEUtils::gattCloseReasonToString(evtParam->close.reason).c_str(), - evtParam->close.conn_id); - break; - } - - // ESP_GATTC_CONNECT_EVT - // - // connect: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_CONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str() - ); - break; - } - - // ESP_GATTC_DISCONNECT_EVT - // - // disconnect: - // - esp_gatt_conn_reason_t reason - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - case ESP_GATTC_DISCONNECT_EVT: { - log_v("[reason: %s, conn_id: %d, remote_bda: %s]", - BLEUtils::gattCloseReasonToString(evtParam->disconnect.reason).c_str(), - evtParam->disconnect.conn_id, - BLEAddress(evtParam->disconnect.remote_bda).toString().c_str() - ); - break; - } // ESP_GATTC_DISCONNECT_EVT - - // ESP_GATTC_GET_CHAR_EVT - // - // get_char: - // - esp_gatt_status_t status - // - uin1t6_t conn_id - // - esp_gatt_srvc_id_t srvc_id - // - esp_gatt_id_t char_id - // - esp_gatt_char_prop_t char_prop - /* - case ESP_GATTC_GET_CHAR_EVT: { - - // If the status of the event shows that we have a value other than ESP_GATT_OK then the - // characteristic fields are not set to a usable value .. so don't try and log them. - if (evtParam->get_char.status == ESP_GATT_OK) { - std::string description = "Unknown"; - if (evtParam->get_char.char_id.uuid.len == ESP_UUID_LEN_16) { - description = BLEUtils::gattCharacteristicUUIDToString(evtParam->get_char.char_id.uuid.uuid.uuid16); - } - log_v("[status: %s, conn_id: %d, srvc_id: %s, char_id: %s [description: %s]\nchar_prop: %s]", - BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), - evtParam->get_char.conn_id, - BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str(), - gattIdToString(evtParam->get_char.char_id).c_str(), - description.c_str(), - BLEUtils::characteristicPropertiesToString(evtParam->get_char.char_prop).c_str() - ); - } else { - log_v("[status: %s, conn_id: %d, srvc_id: %s]", - BLEUtils::gattStatusToString(evtParam->get_char.status).c_str(), - evtParam->get_char.conn_id, - BLEUtils::gattServiceIdToString(evtParam->get_char.srvc_id).c_str() - ); - } - break; - } // ESP_GATTC_GET_CHAR_EVT - */ - - // ESP_GATTC_NOTIFY_EVT - // - // notify - // uint16_t conn_id - // esp_bd_addr_t remote_bda - // handle handle - // uint16_t value_len - // uint8_t* value - // bool is_notify - // - case ESP_GATTC_NOTIFY_EVT: { - log_v("[conn_id: %d, remote_bda: %s, handle: %d 0x%.2x, value_len: %d, is_notify: %d]", - evtParam->notify.conn_id, - BLEAddress(evtParam->notify.remote_bda).toString().c_str(), - evtParam->notify.handle, - evtParam->notify.handle, - evtParam->notify.value_len, - evtParam->notify.is_notify - ); - break; - } - - // ESP_GATTC_OPEN_EVT - // - // open: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - esp_bd_addr_t remote_bda - // - uint16_t mtu - // - case ESP_GATTC_OPEN_EVT: { - log_v("[status: %s, conn_id: %d, remote_bda: %s, mtu: %d]", - BLEUtils::gattStatusToString(evtParam->open.status).c_str(), - evtParam->open.conn_id, - BLEAddress(evtParam->open.remote_bda).toString().c_str(), - evtParam->open.mtu); - break; - } // ESP_GATTC_OPEN_EVT - - // ESP_GATTC_READ_CHAR_EVT - // - // Callback to indicate that requested data that we wanted to read is now available. - // - // read: - // esp_gatt_status_t status - // uint16_t conn_id - // uint16_t handle - // uint8_t* value - // uint16_t value_type - // uint16_t value_len - case ESP_GATTC_READ_CHAR_EVT: { - log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, value_len: %d]", - BLEUtils::gattStatusToString(evtParam->read.status).c_str(), - evtParam->read.conn_id, - evtParam->read.handle, - evtParam->read.handle, - evtParam->read.value_len - ); - if (evtParam->read.status == ESP_GATT_OK) { - GeneralUtils::hexDump(evtParam->read.value, evtParam->read.value_len); - /* - char* pHexData = BLEUtils::buildHexData(nullptr, evtParam->read.value, evtParam->read.value_len); - log_v("value: %s \"%s\"", pHexData, BLEUtils::buildPrintData(evtParam->read.value, evtParam->read.value_len).c_str()); - free(pHexData); - */ - } - break; - } // ESP_GATTC_READ_CHAR_EVT - - // ESP_GATTC_REG_EVT - // - // reg: - // - esp_gatt_status_t status - // - uint16_t app_id - case ESP_GATTC_REG_EVT: { - log_v("[status: %s, app_id: 0x%x]", - BLEUtils::gattStatusToString(evtParam->reg.status).c_str(), - evtParam->reg.app_id); - break; - } // ESP_GATTC_REG_EVT - - // ESP_GATTC_REG_FOR_NOTIFY_EVT - // - // reg_for_notify: - // - esp_gatt_status_t status - // - uint16_t handle - case ESP_GATTC_REG_FOR_NOTIFY_EVT: { - log_v("[status: %s, handle: %d 0x%.2x]", - BLEUtils::gattStatusToString(evtParam->reg_for_notify.status).c_str(), - evtParam->reg_for_notify.handle, - evtParam->reg_for_notify.handle - ); - break; - } // ESP_GATTC_REG_FOR_NOTIFY_EVT - - // ESP_GATTC_SEARCH_CMPL_EVT - // - // search_cmpl: - // - esp_gatt_status_t status - // - uint16_t conn_id - case ESP_GATTC_SEARCH_CMPL_EVT: { - log_v("[status: %s, conn_id: %d]", - BLEUtils::gattStatusToString(evtParam->search_cmpl.status).c_str(), - evtParam->search_cmpl.conn_id); - break; - } // ESP_GATTC_SEARCH_CMPL_EVT - - // ESP_GATTC_SEARCH_RES_EVT - // - // search_res: - // - uint16_t conn_id - // - uint16_t start_handle - // - uint16_t end_handle - // - esp_gatt_id_t srvc_id - case ESP_GATTC_SEARCH_RES_EVT: { - log_v("[conn_id: %d, start_handle: %d 0x%.2x, end_handle: %d 0x%.2x, srvc_id: %s", - evtParam->search_res.conn_id, - evtParam->search_res.start_handle, - evtParam->search_res.start_handle, - evtParam->search_res.end_handle, - evtParam->search_res.end_handle, - gattIdToString(evtParam->search_res.srvc_id).c_str()); - break; - } // ESP_GATTC_SEARCH_RES_EVT - - // ESP_GATTC_WRITE_CHAR_EVT - // - // write: - // - esp_gatt_status_t status - // - uint16_t conn_id - // - uint16_t handle - // - uint16_t offset - case ESP_GATTC_WRITE_CHAR_EVT: { - log_v("[status: %s, conn_id: %d, handle: %d 0x%.2x, offset: %d]", - BLEUtils::gattStatusToString(evtParam->write.status).c_str(), - evtParam->write.conn_id, - evtParam->write.handle, - evtParam->write.handle, - evtParam->write.offset - ); - break; - } // ESP_GATTC_WRITE_CHAR_EVT -#endif - default: - break; - } -} // dumpGattClientEvent - - -/** - * @brief Dump the details of a GATT server event. - * A GATT Server event is a callback received from the BLE subsystem when we are acting as a BLE - * server. The callback indicates the type of event in the `event` field. The `evtParam` is a - * union of structures where we can use the `event` to indicate which of the structures has been - * populated and hence is valid. - * - * @param [in] event The event type that was posted. - * @param [in] evtParam A union of structures only one of which is populated. - */ -void BLEUtils::dumpGattServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* evtParam) { - log_v("GATT ServerEvent: %s", BLEUtils::gattServerEventTypeToString(event).c_str()); - switch (event) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - - case ESP_GATTS_ADD_CHAR_DESCR_EVT: { - log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char_descr.status).c_str(), - evtParam->add_char_descr.attr_handle, - evtParam->add_char_descr.attr_handle, - evtParam->add_char_descr.service_handle, - evtParam->add_char_descr.service_handle, - BLEUUID(evtParam->add_char_descr.descr_uuid).toString().c_str()); - break; - } // ESP_GATTS_ADD_CHAR_DESCR_EVT - - case ESP_GATTS_ADD_CHAR_EVT: { - if (evtParam->add_char.status == ESP_GATT_OK) { - log_v("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char.status).c_str(), - evtParam->add_char.attr_handle, - evtParam->add_char.attr_handle, - evtParam->add_char.service_handle, - evtParam->add_char.service_handle, - BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); - } else { - log_e("[status: %s, attr_handle: %d 0x%.2x, service_handle: %d 0x%.2x, char_uuid: %s]", - gattStatusToString(evtParam->add_char.status).c_str(), - evtParam->add_char.attr_handle, - evtParam->add_char.attr_handle, - evtParam->add_char.service_handle, - evtParam->add_char.service_handle, - BLEUUID(evtParam->add_char.char_uuid).toString().c_str()); - } - break; - } // ESP_GATTS_ADD_CHAR_EVT - - - // ESP_GATTS_CONF_EVT - // - // conf: - // - esp_gatt_status_t status – The status code. - // - uint16_t conn_id – The connection used. - case ESP_GATTS_CONF_EVT: { - log_v("[status: %s, conn_id: 0x%.2x]", - gattStatusToString(evtParam->conf.status).c_str(), - evtParam->conf.conn_id); - break; - } // ESP_GATTS_CONF_EVT - - - case ESP_GATTS_CONGEST_EVT: { - log_v("[conn_id: %d, congested: %d]", - evtParam->congest.conn_id, - evtParam->congest.congested); - break; - } // ESP_GATTS_CONGEST_EVT - - case ESP_GATTS_CONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str()); - break; - } // ESP_GATTS_CONNECT_EVT - - case ESP_GATTS_CREATE_EVT: { - log_v("[status: %s, service_handle: %d 0x%.2x, service_id: [%s]]", - gattStatusToString(evtParam->create.status).c_str(), - evtParam->create.service_handle, - evtParam->create.service_handle, - gattServiceIdToString(evtParam->create.service_id).c_str()); - break; - } // ESP_GATTS_CREATE_EVT - - case ESP_GATTS_DISCONNECT_EVT: { - log_v("[conn_id: %d, remote_bda: %s]", - evtParam->connect.conn_id, - BLEAddress(evtParam->connect.remote_bda).toString().c_str()); - break; - } // ESP_GATTS_DISCONNECT_EVT - - - // ESP_GATTS_EXEC_WRITE_EVT - // exec_write: - // - uint16_t conn_id - // - uint32_t trans_id - // - esp_bd_addr_t bda - // - uint8_t exec_write_flag - case ESP_GATTS_EXEC_WRITE_EVT: { - char* pWriteFlagText; - switch (evtParam->exec_write.exec_write_flag) { - case ESP_GATT_PREP_WRITE_EXEC: { - pWriteFlagText = (char*) "WRITE"; - break; - } - - case ESP_GATT_PREP_WRITE_CANCEL: { - pWriteFlagText = (char*) "CANCEL"; - break; - } - - default: - pWriteFlagText = (char*) ""; - break; - } - - log_v("[conn_id: %d, trans_id: %d, bda: %s, exec_write_flag: 0x%.2x=%s]", - evtParam->exec_write.conn_id, - evtParam->exec_write.trans_id, - BLEAddress(evtParam->exec_write.bda).toString().c_str(), - evtParam->exec_write.exec_write_flag, - pWriteFlagText); - break; - } // ESP_GATTS_DISCONNECT_EVT - - - case ESP_GATTS_MTU_EVT: { - log_v("[conn_id: %d, mtu: %d]", - evtParam->mtu.conn_id, - evtParam->mtu.mtu); - break; - } // ESP_GATTS_MTU_EVT - - case ESP_GATTS_READ_EVT: { - log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, is_long: %d, need_rsp:%d]", - evtParam->read.conn_id, - evtParam->read.trans_id, - BLEAddress(evtParam->read.bda).toString().c_str(), - evtParam->read.handle, - evtParam->read.is_long, - evtParam->read.need_rsp); - break; - } // ESP_GATTS_READ_EVT - - case ESP_GATTS_RESPONSE_EVT: { - log_v("[status: %s, handle: 0x%.2x]", - gattStatusToString(evtParam->rsp.status).c_str(), - evtParam->rsp.handle); - break; - } // ESP_GATTS_RESPONSE_EVT - - case ESP_GATTS_REG_EVT: { - log_v("[status: %s, app_id: %d]", - gattStatusToString(evtParam->reg.status).c_str(), - evtParam->reg.app_id); - break; - } // ESP_GATTS_REG_EVT - - - // ESP_GATTS_START_EVT - // - // start: - // - esp_gatt_status_t status - // - uint16_t service_handle - case ESP_GATTS_START_EVT: { - log_v("[status: %s, service_handle: 0x%.2x]", - gattStatusToString(evtParam->start.status).c_str(), - evtParam->start.service_handle); - break; - } // ESP_GATTS_START_EVT - - - // ESP_GATTS_WRITE_EVT - // - // write: - // - uint16_t conn_id – The connection id. - // - uint16_t trans_id – The transfer id. - // - esp_bd_addr_t bda – The address of the partner. - // - uint16_t handle – The attribute handle. - // - uint16_t offset – The offset of the currently received within the whole value. - // - bool need_rsp – Do we need a response? - // - bool is_prep – Is this a write prepare? If set, then this is to be considered part of the received value and not the whole value. A subsequent ESP_GATTS_EXEC_WRITE will mark the total. - // - uint16_t len – The length of the incoming value part. - // - uint8_t* value – The data for this value part. - case ESP_GATTS_WRITE_EVT: { - log_v("[conn_id: %d, trans_id: %d, bda: %s, handle: 0x%.2x, offset: %d, need_rsp: %d, is_prep: %d, len: %d]", - evtParam->write.conn_id, - evtParam->write.trans_id, - BLEAddress(evtParam->write.bda).toString().c_str(), - evtParam->write.handle, - evtParam->write.offset, - evtParam->write.need_rsp, - evtParam->write.is_prep, - evtParam->write.len); - char* pHex = buildHexData(nullptr, evtParam->write.value, evtParam->write.len); - log_v("[Data: %s]", pHex); - free(pHex); - break; - } // ESP_GATTS_WRITE_EVT -#endif - default: - log_v("dumpGattServerEvent: *** NOT CODED ***"); - break; - } -} // dumpGattServerEvent - - -/** - * @brief Convert a BLE event type to a string. - * @param [in] eventType The event type. - * @return The event type as a string. - */ -const char* BLEUtils::eventTypeToString(esp_ble_evt_type_t eventType) { - switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_BLE_EVT_CONN_ADV: - return "ESP_BLE_EVT_CONN_ADV"; - case ESP_BLE_EVT_CONN_DIR_ADV: - return "ESP_BLE_EVT_CONN_DIR_ADV"; - case ESP_BLE_EVT_DISC_ADV: - return "ESP_BLE_EVT_DISC_ADV"; - case ESP_BLE_EVT_NON_CONN_ADV: - return "ESP_BLE_EVT_NON_CONN_ADV"; - case ESP_BLE_EVT_SCAN_RSP: - return "ESP_BLE_EVT_SCAN_RSP"; -#endif - default: - log_v("Unknown esp_ble_evt_type_t: %d (0x%.2x)", eventType, eventType); - return "*** Unknown ***"; - } -} // eventTypeToString - - - -/** - * @brief Convert a BT GAP event type to a string representation. - * @param [in] eventType The type of event. - * @return A string representation of the event type. - */ -const char* BLEUtils::gapEventToString(uint32_t eventType) { - switch (eventType) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT"; - case ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_DATA_RAW_SET_COMPLETE_EVT"; - case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: - return "ESP_GAP_BLE_ADV_START_COMPLETE_EVT"; - case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: /* !< When stop adv complete, the event comes */ - return "ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT"; - case ESP_GAP_BLE_AUTH_CMPL_EVT: /* Authentication complete indication. */ - return "ESP_GAP_BLE_AUTH_CMPL_EVT"; - case ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_CLEAR_BOND_DEV_COMPLETE_EVT"; - case ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_GET_BOND_DEV_COMPLETE_EVT"; - case ESP_GAP_BLE_KEY_EVT: /* BLE key event for peer device keys */ - return "ESP_GAP_BLE_KEY_EVT"; - case ESP_GAP_BLE_LOCAL_IR_EVT: /* BLE local IR event */ - return "ESP_GAP_BLE_LOCAL_IR_EVT"; - case ESP_GAP_BLE_LOCAL_ER_EVT: /* BLE local ER event */ - return "ESP_GAP_BLE_LOCAL_ER_EVT"; - case ESP_GAP_BLE_NC_REQ_EVT: /* Numeric Comparison request event */ - return "ESP_GAP_BLE_NC_REQ_EVT"; - case ESP_GAP_BLE_OOB_REQ_EVT: /* OOB request event */ - return "ESP_GAP_BLE_OOB_REQ_EVT"; - case ESP_GAP_BLE_PASSKEY_NOTIF_EVT: /* passkey notification event */ - return "ESP_GAP_BLE_PASSKEY_NOTIF_EVT"; - case ESP_GAP_BLE_PASSKEY_REQ_EVT: /* passkey request event */ - return "ESP_GAP_BLE_PASSKEY_REQ_EVT"; - case ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT: - return "ESP_GAP_BLE_READ_RSSI_COMPLETE_EVT"; - case ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT: - return "ESP_GAP_BLE_REMOVE_BOND_DEV_COMPLETE_EVT"; - case ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_PARAM_SET_COMPLETE_EVT"; - case ESP_GAP_BLE_SCAN_RESULT_EVT: - return "ESP_GAP_BLE_SCAN_RESULT_EVT"; - case ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_RSP_DATA_RAW_SET_COMPLETE_EVT"; - case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT"; - case ESP_GAP_BLE_SCAN_START_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_START_COMPLETE_EVT"; - case ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT: - return "ESP_GAP_BLE_SCAN_STOP_COMPLETE_EVT"; - case ESP_GAP_BLE_SEC_REQ_EVT: /* BLE security request */ - return "ESP_GAP_BLE_SEC_REQ_EVT"; - case ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT: - return "ESP_GAP_BLE_SET_LOCAL_PRIVACY_COMPLETE_EVT"; - case ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT: - return "ESP_GAP_BLE_SET_PKT_LENGTH_COMPLETE_EVT"; - case ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT: - return "ESP_GAP_BLE_SET_STATIC_RAND_ADDR_EVT"; - case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: - return "ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT"; -#endif - default: - log_v("gapEventToString: Unknown event type %d 0x%.2x", eventType, eventType); - return "Unknown event type"; - } -} // gapEventToString - - -std::string BLEUtils::gattCharacteristicUUIDToString(uint32_t characteristicUUID) { - const characteristicMap_t* p = g_characteristicsMappings; - while (strlen(p->name) > 0) { - if (p->assignedNumber == characteristicUUID) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} // gattCharacteristicUUIDToString - - -/** - * @brief Given the UUID for a BLE defined descriptor, return its string representation. - * @param [in] descriptorUUID UUID of the descriptor to be returned as a string. - * @return The string representation of a descriptor UUID. - */ -std::string BLEUtils::gattDescriptorUUIDToString(uint32_t descriptorUUID) { - gattdescriptor_t* p = (gattdescriptor_t*) g_descriptor_ids; - while (strlen(p->name) > 0) { - if (p->assignedNumber == descriptorUUID) { - return std::string(p->name); - } - p++; - } - return ""; -} // gattDescriptorUUIDToString - - -/** - * @brief Return a string representation of an esp_gattc_service_elem_t. - * @return A string representation of an esp_gattc_service_elem_t. - */ -std::string BLEUtils::gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement) { - std::string res; - char val[6]; - res += "[uuid: " + BLEUUID(pGATTCServiceElement->uuid).toString() + ", start_handle: "; - snprintf(val, sizeof(val), "%d", pGATTCServiceElement->start_handle); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->start_handle); - res += val; - res += ", end_handle: "; - snprintf(val, sizeof(val), "%d", pGATTCServiceElement->end_handle); - res += val; - res += " 0x"; - snprintf(val, sizeof(val), "%04x", pGATTCServiceElement->end_handle); - res += val; - res += "]"; - return res; -} // gattcServiceElementToString - - -/** - * @brief Convert an esp_gatt_srvc_id_t to a string. - */ -std::string BLEUtils::gattServiceIdToString(esp_gatt_srvc_id_t srvcId) { - return gattIdToString(srvcId.id); -} // gattServiceIdToString - - -std::string BLEUtils::gattServiceToString(uint32_t serviceId) { - gattService_t* p = (gattService_t*) g_gattServices; - while (strlen(p->name) > 0) { - if (p->assignedNumber == serviceId) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} // gattServiceToString - - -/** - * @brief Convert a GATT status to a string. - * - * @param [in] status The status to convert. - * @return A string representation of the status. - */ -std::string BLEUtils::gattStatusToString(esp_gatt_status_t status) { - switch (status) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GATT_OK: - return "ESP_GATT_OK"; - case ESP_GATT_INVALID_HANDLE: - return "ESP_GATT_INVALID_HANDLE"; - case ESP_GATT_READ_NOT_PERMIT: - return "ESP_GATT_READ_NOT_PERMIT"; - case ESP_GATT_WRITE_NOT_PERMIT: - return "ESP_GATT_WRITE_NOT_PERMIT"; - case ESP_GATT_INVALID_PDU: - return "ESP_GATT_INVALID_PDU"; - case ESP_GATT_INSUF_AUTHENTICATION: - return "ESP_GATT_INSUF_AUTHENTICATION"; - case ESP_GATT_REQ_NOT_SUPPORTED: - return "ESP_GATT_REQ_NOT_SUPPORTED"; - case ESP_GATT_INVALID_OFFSET: - return "ESP_GATT_INVALID_OFFSET"; - case ESP_GATT_INSUF_AUTHORIZATION: - return "ESP_GATT_INSUF_AUTHORIZATION"; - case ESP_GATT_PREPARE_Q_FULL: - return "ESP_GATT_PREPARE_Q_FULL"; - case ESP_GATT_NOT_FOUND: - return "ESP_GATT_NOT_FOUND"; - case ESP_GATT_NOT_LONG: - return "ESP_GATT_NOT_LONG"; - case ESP_GATT_INSUF_KEY_SIZE: - return "ESP_GATT_INSUF_KEY_SIZE"; - case ESP_GATT_INVALID_ATTR_LEN: - return "ESP_GATT_INVALID_ATTR_LEN"; - case ESP_GATT_ERR_UNLIKELY: - return "ESP_GATT_ERR_UNLIKELY"; - case ESP_GATT_INSUF_ENCRYPTION: - return "ESP_GATT_INSUF_ENCRYPTION"; - case ESP_GATT_UNSUPPORT_GRP_TYPE: - return "ESP_GATT_UNSUPPORT_GRP_TYPE"; - case ESP_GATT_INSUF_RESOURCE: - return "ESP_GATT_INSUF_RESOURCE"; - case ESP_GATT_NO_RESOURCES: - return "ESP_GATT_NO_RESOURCES"; - case ESP_GATT_INTERNAL_ERROR: - return "ESP_GATT_INTERNAL_ERROR"; - case ESP_GATT_WRONG_STATE: - return "ESP_GATT_WRONG_STATE"; - case ESP_GATT_DB_FULL: - return "ESP_GATT_DB_FULL"; - case ESP_GATT_BUSY: - return "ESP_GATT_BUSY"; - case ESP_GATT_ERROR: - return "ESP_GATT_ERROR"; - case ESP_GATT_CMD_STARTED: - return "ESP_GATT_CMD_STARTED"; - case ESP_GATT_ILLEGAL_PARAMETER: - return "ESP_GATT_ILLEGAL_PARAMETER"; - case ESP_GATT_PENDING: - return "ESP_GATT_PENDING"; - case ESP_GATT_AUTH_FAIL: - return "ESP_GATT_AUTH_FAIL"; - case ESP_GATT_MORE: - return "ESP_GATT_MORE"; - case ESP_GATT_INVALID_CFG: - return "ESP_GATT_INVALID_CFG"; - case ESP_GATT_SERVICE_STARTED: - return "ESP_GATT_SERVICE_STARTED"; - case ESP_GATT_ENCRYPED_NO_MITM: - return "ESP_GATT_ENCRYPED_NO_MITM"; - case ESP_GATT_NOT_ENCRYPTED: - return "ESP_GATT_NOT_ENCRYPTED"; - case ESP_GATT_CONGESTED: - return "ESP_GATT_CONGESTED"; - case ESP_GATT_DUP_REG: - return "ESP_GATT_DUP_REG"; - case ESP_GATT_ALREADY_OPEN: - return "ESP_GATT_ALREADY_OPEN"; - case ESP_GATT_CANCEL: - return "ESP_GATT_CANCEL"; - case ESP_GATT_STACK_RSP: - return "ESP_GATT_STACK_RSP"; - case ESP_GATT_APP_RSP: - return "ESP_GATT_APP_RSP"; - case ESP_GATT_UNKNOWN_ERROR: - return "ESP_GATT_UNKNOWN_ERROR"; - case ESP_GATT_CCC_CFG_ERR: - return "ESP_GATT_CCC_CFG_ERR"; - case ESP_GATT_PRC_IN_PROGRESS: - return "ESP_GATT_PRC_IN_PROGRESS"; - case ESP_GATT_OUT_OF_RANGE: - return "ESP_GATT_OUT_OF_RANGE"; -#endif - default: - return "Unknown"; - } -} // gattStatusToString - - - -std::string BLEUtils::getMember(uint32_t memberId) { - member_t* p = (member_t*) members_ids; - - while (strlen(p->name) > 0) { - if (p->assignedNumber == memberId) { - return std::string(p->name); - } - p++; - } - return "Unknown"; -} - -/** - * @brief convert a GAP search event to a string. - * @param [in] searchEvt - * @return The search event type as a string. - */ -const char* BLEUtils::searchEventTypeToString(esp_gap_search_evt_t searchEvt) { - switch (searchEvt) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_GAP_SEARCH_INQ_RES_EVT: - return "ESP_GAP_SEARCH_INQ_RES_EVT"; - case ESP_GAP_SEARCH_INQ_CMPL_EVT: - return "ESP_GAP_SEARCH_INQ_CMPL_EVT"; - case ESP_GAP_SEARCH_DISC_RES_EVT: - return "ESP_GAP_SEARCH_DISC_RES_EVT"; - case ESP_GAP_SEARCH_DISC_BLE_RES_EVT: - return "ESP_GAP_SEARCH_DISC_BLE_RES_EVT"; - case ESP_GAP_SEARCH_DISC_CMPL_EVT: - return "ESP_GAP_SEARCH_DISC_CMPL_EVT"; - case ESP_GAP_SEARCH_DI_DISC_CMPL_EVT: - return "ESP_GAP_SEARCH_DI_DISC_CMPL_EVT"; - case ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT: - return "ESP_GAP_SEARCH_SEARCH_CANCEL_CMPL_EVT"; -#endif - default: - log_v("Unknown event type: 0x%x", searchEvt); - return "Unknown event type"; - } -} // searchEventTypeToString - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEUtils.h b/libraries/BLE/src/BLEUtils.h deleted file mode 100644 index 580075df..00000000 --- a/libraries/BLE/src/BLEUtils.h +++ /dev/null @@ -1,63 +0,0 @@ -/* - * BLEUtils.h - * - * Created on: Mar 25, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEUTILS_H_ -#define COMPONENTS_CPP_UTILS_BLEUTILS_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include // ESP32 BLE -#include // ESP32 BLE -#include // ESP32 BLE -#include -#include "BLEClient.h" - -/** - * @brief A set of general %BLE utilities. - */ -class BLEUtils { -public: - static const char* addressTypeToString(esp_ble_addr_type_t type); - static std::string adFlagsToString(uint8_t adFlags); - static const char* advTypeToString(uint8_t advType); - static char* buildHexData(uint8_t* target, uint8_t* source, uint8_t length); - static std::string buildPrintData(uint8_t* source, size_t length); - static std::string characteristicPropertiesToString(esp_gatt_char_prop_t prop); - static const char* devTypeToString(esp_bt_dev_type_t type); - static esp_gatt_id_t buildGattId(esp_bt_uuid_t uuid, uint8_t inst_id = 0); - static esp_gatt_srvc_id_t buildGattSrvcId(esp_gatt_id_t gattId, bool is_primary = true); - static void dumpGapEvent( - esp_gap_ble_cb_event_t event, - esp_ble_gap_cb_param_t* param); - static void dumpGattClientEvent( - esp_gattc_cb_event_t event, - esp_gatt_if_t gattc_if, - esp_ble_gattc_cb_param_t* evtParam); - static void dumpGattServerEvent( - esp_gatts_cb_event_t event, - esp_gatt_if_t gatts_if, - esp_ble_gatts_cb_param_t* evtParam); - static const char* eventTypeToString(esp_ble_evt_type_t eventType); - static BLEClient* findByAddress(BLEAddress address); - static BLEClient* findByConnId(uint16_t conn_id); - static const char* gapEventToString(uint32_t eventType); - static std::string gattCharacteristicUUIDToString(uint32_t characteristicUUID); - static std::string gattClientEventTypeToString(esp_gattc_cb_event_t eventType); - static std::string gattCloseReasonToString(esp_gatt_conn_reason_t reason); - static std::string gattcServiceElementToString(esp_gattc_service_elem_t* pGATTCServiceElement); - static std::string gattDescriptorUUIDToString(uint32_t descriptorUUID); - static std::string gattServerEventTypeToString(esp_gatts_cb_event_t eventType); - static std::string gattServiceIdToString(esp_gatt_srvc_id_t srvcId); - static std::string gattServiceToString(uint32_t serviceId); - static std::string gattStatusToString(esp_gatt_status_t status); - static std::string getMember(uint32_t memberId); - static void registerByAddress(BLEAddress address, BLEClient* pDevice); - static void registerByConnId(uint16_t conn_id, BLEClient* pDevice); - static const char* searchEventTypeToString(esp_gap_search_evt_t searchEvt); -}; - -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLEUTILS_H_ */ diff --git a/libraries/BLE/src/BLEValue.cpp b/libraries/BLE/src/BLEValue.cpp deleted file mode 100644 index a42c92d1..00000000 --- a/libraries/BLE/src/BLEValue.cpp +++ /dev/null @@ -1,130 +0,0 @@ -/* - * BLEValue.cpp - * - * Created on: Jul 17, 2017 - * Author: kolban - */ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include "BLEValue.h" -#include "esp32-hal-log.h" - -BLEValue::BLEValue() { - m_accumulation = ""; - m_value = ""; - m_readOffset = 0; -} // BLEValue - - -/** - * @brief Add a message part to the accumulation. - * The accumulation is a growing set of data that is added to until a commit or cancel. - * @param [in] part A message part being added. - */ -void BLEValue::addPart(std::string part) { - log_v(">> addPart: length=%d", part.length()); - m_accumulation += part; -} // addPart - - -/** - * @brief Add a message part to the accumulation. - * The accumulation is a growing set of data that is added to until a commit or cancel. - * @param [in] pData A message part being added. - * @param [in] length The number of bytes being added. - */ -void BLEValue::addPart(uint8_t* pData, size_t length) { - log_v(">> addPart: length=%d", length); - m_accumulation += std::string((char*) pData, length); -} // addPart - - -/** - * @brief Cancel the current accumulation. - */ -void BLEValue::cancel() { - log_v(">> cancel"); - m_accumulation = ""; - m_readOffset = 0; -} // cancel - - -/** - * @brief Commit the current accumulation. - * When writing a value, we may find that we write it in "parts" meaning that the writes come in in pieces - * of the overall message. After the last part has been received, we may perform a commit which means that - * we now have the complete message and commit the change as a unit. - */ -void BLEValue::commit() { - log_v(">> commit"); - // If there is nothing to commit, do nothing. - if (m_accumulation.length() == 0) return; - setValue(m_accumulation); - m_accumulation = ""; - m_readOffset = 0; -} // commit - - -/** - * @brief Get a pointer to the data. - * @return A pointer to the data. - */ -uint8_t* BLEValue::getData() { - return (uint8_t*) m_value.data(); -} - - -/** - * @brief Get the length of the data in bytes. - * @return The length of the data in bytes. - */ -size_t BLEValue::getLength() { - return m_value.length(); -} // getLength - - -/** - * @brief Get the read offset. - * @return The read offset into the read. - */ -uint16_t BLEValue::getReadOffset() { - return m_readOffset; -} // getReadOffset - - -/** - * @brief Get the current value. - */ -std::string BLEValue::getValue() { - return m_value; -} // getValue - - -/** - * @brief Set the read offset - * @param [in] readOffset The offset into the read. - */ -void BLEValue::setReadOffset(uint16_t readOffset) { - m_readOffset = readOffset; -} // setReadOffset - - -/** - * @brief Set the current value. - */ -void BLEValue::setValue(std::string value) { - m_value = value; -} // setValue - - -/** - * @brief Set the current value. - * @param [in] pData The data for the current value. - * @param [in] The length of the new current value. - */ -void BLEValue::setValue(uint8_t* pData, size_t length) { - m_value = std::string((char*) pData, length); -} // setValue - - -#endif // CONFIG_BLUEDROID_ENABLED diff --git a/libraries/BLE/src/BLEValue.h b/libraries/BLE/src/BLEValue.h deleted file mode 100644 index 31734e48..00000000 --- a/libraries/BLE/src/BLEValue.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * BLEValue.h - * - * Created on: Jul 17, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_BLEVALUE_H_ -#define COMPONENTS_CPP_UTILS_BLEVALUE_H_ -#include "sdkconfig.h" -#if defined(CONFIG_BLUEDROID_ENABLED) -#include - -/** - * @brief The model of a %BLE value. - */ -class BLEValue { -public: - BLEValue(); - void addPart(std::string part); - void addPart(uint8_t* pData, size_t length); - void cancel(); - void commit(); - uint8_t* getData(); - size_t getLength(); - uint16_t getReadOffset(); - std::string getValue(); - void setReadOffset(uint16_t readOffset); - void setValue(std::string value); - void setValue(uint8_t* pData, size_t length); - -private: - std::string m_accumulation; - uint16_t m_readOffset; - std::string m_value; - -}; -#endif // CONFIG_BLUEDROID_ENABLED -#endif /* COMPONENTS_CPP_UTILS_BLEVALUE_H_ */ diff --git a/libraries/BLE/src/FreeRTOS.cpp b/libraries/BLE/src/FreeRTOS.cpp deleted file mode 100644 index 115ef272..00000000 --- a/libraries/BLE/src/FreeRTOS.cpp +++ /dev/null @@ -1,306 +0,0 @@ -/* - * FreeRTOS.cpp - * - * Created on: Feb 24, 2017 - * Author: kolban - */ -#include // Include the base FreeRTOS definitions -#include // Include the task definitions -#include // Include the semaphore definitions -#include -#include -#include -#include "RTOS.h" -#include "sdkconfig.h" -#include "esp32-hal-log.h" - -/** - * Sleep for the specified number of milliseconds. - * @param[in] ms The period in milliseconds for which to sleep. - */ -void FreeRTOS::sleep(uint32_t ms) { - ::vTaskDelay(ms / portTICK_PERIOD_MS); -} // sleep - - -/** - * Start a new task. - * @param[in] task The function pointer to the function to be run in the task. - * @param[in] taskName A string identifier for the task. - * @param[in] param An optional parameter to be passed to the started task. - * @param[in] stackSize An optional paremeter supplying the size of the stack in which to run the task. - */ -void FreeRTOS::startTask(void task(void*), std::string taskName, void* param, uint32_t stackSize) { - ::xTaskCreate(task, taskName.data(), stackSize, param, 5, NULL); -} // startTask - - -/** - * Delete the task. - * @param[in] pTask An optional handle to the task to be deleted. If not supplied the calling task will be deleted. - */ -void FreeRTOS::deleteTask(TaskHandle_t pTask) { - ::vTaskDelete(pTask); -} // deleteTask - - -/** - * Get the time in milliseconds since the %FreeRTOS scheduler started. - * @return The time in milliseconds since the %FreeRTOS scheduler started. - */ -uint32_t FreeRTOS::getTimeSinceStart() { - return (uint32_t) (xTaskGetTickCount() * portTICK_PERIOD_MS); -} // getTimeSinceStart - - -/** - * @brief Wait for a semaphore to be released by trying to take it and - * then releasing it again. - * @param [in] owner A debug tag. - * @return The value associated with the semaphore. - */ -uint32_t FreeRTOS::Semaphore::wait(std::string owner) { - log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); - - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - xSemaphoreTake(m_semaphore, portMAX_DELAY); - } - - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } - - log_v("<< wait: Semaphore released: %s", toString().c_str()); - return m_value; -} // wait - -/** - * @brief Wait for a semaphore to be released in a given period of time by trying to take it and - * then releasing it again. The value associated with the semaphore can be taken by value() call after return - * @param [in] owner A debug tag. - * @param [in] timeoutMs timeout to wait in ms. - * @return True if we took the semaphore within timeframe. - */ -bool FreeRTOS::Semaphore::timedWait(std::string owner, uint32_t timeoutMs) { - log_v(">> wait: Semaphore waiting: %s for %s", toString().c_str(), owner.c_str()); - - if (m_usePthreads && timeoutMs != portMAX_DELAY) { - assert(false); // We apparently don't have a timed wait for pthreads. - } - - auto ret = pdTRUE; - - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - ret = xSemaphoreTake(m_semaphore, timeoutMs); - } - - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } - - log_v("<< wait: Semaphore %s released: %d", toString().c_str(), ret); - return ret; -} // wait - - -FreeRTOS::Semaphore::Semaphore(std::string name) { - m_usePthreads = false; // Are we using pThreads or FreeRTOS? - if (m_usePthreads) { - pthread_mutex_init(&m_pthread_mutex, nullptr); - } else { - m_semaphore = xSemaphoreCreateBinary(); - xSemaphoreGive(m_semaphore); - } - - m_name = name; - m_owner = std::string(""); - m_value = 0; -} - - -FreeRTOS::Semaphore::~Semaphore() { - if (m_usePthreads) { - pthread_mutex_destroy(&m_pthread_mutex); - } else { - vSemaphoreDelete(m_semaphore); - } -} - - -/** - * @brief Give a semaphore. - * The Semaphore is given. - */ -void FreeRTOS::Semaphore::give() { - log_v("Semaphore giving: %s", toString().c_str()); - m_owner = std::string(""); - - if (m_usePthreads) { - pthread_mutex_unlock(&m_pthread_mutex); - } else { - xSemaphoreGive(m_semaphore); - } -// #ifdef ARDUINO_ARCH_ESP32 -// FreeRTOS::sleep(10); -// #endif - -} // Semaphore::give - - -/** - * @brief Give a semaphore. - * The Semaphore is given with an associated value. - * @param [in] value The value to associate with the semaphore. - */ -void FreeRTOS::Semaphore::give(uint32_t value) { - m_value = value; - give(); -} // give - - -/** - * @brief Give a semaphore from an ISR. - */ -void FreeRTOS::Semaphore::giveFromISR() { - BaseType_t higherPriorityTaskWoken; - if (m_usePthreads) { - assert(false); - } else { - xSemaphoreGiveFromISR(m_semaphore, &higherPriorityTaskWoken); - } -} // giveFromISR - - -/** - * @brief Take a semaphore. - * Take a semaphore and wait indefinitely. - * @param [in] owner The new owner (for debugging) - * @return True if we took the semaphore. - */ -bool FreeRTOS::Semaphore::take(std::string owner) { - log_v("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); - bool rc = false; - if (m_usePthreads) { - pthread_mutex_lock(&m_pthread_mutex); - } else { - rc = ::xSemaphoreTake(m_semaphore, portMAX_DELAY) == pdTRUE; - } - if (rc) { - m_owner = owner; - log_v("Semaphore taken: %s", toString().c_str()); - } else { - log_e("Semaphore NOT taken: %s", toString().c_str()); - } - return rc; -} // Semaphore::take - - -/** - * @brief Take a semaphore. - * Take a semaphore but return if we haven't obtained it in the given period of milliseconds. - * @param [in] timeoutMs Timeout in milliseconds. - * @param [in] owner The new owner (for debugging) - * @return True if we took the semaphore. - */ -bool FreeRTOS::Semaphore::take(uint32_t timeoutMs, std::string owner) { - log_v("Semaphore taking: %s for %s", toString().c_str(), owner.c_str()); - bool rc = false; - if (m_usePthreads) { - assert(false); // We apparently don't have a timed wait for pthreads. - } else { - rc = ::xSemaphoreTake(m_semaphore, timeoutMs / portTICK_PERIOD_MS) == pdTRUE; - } - if (rc) { - m_owner = owner; - log_v("Semaphore taken: %s", toString().c_str()); - } else { - log_e("Semaphore NOT taken: %s", toString().c_str()); - } - return rc; -} // Semaphore::take - - - -/** - * @brief Create a string representation of the semaphore. - * @return A string representation of the semaphore. - */ -std::string FreeRTOS::Semaphore::toString() { - char hex[9]; - std::string res = "name: " + m_name + " (0x"; - snprintf(hex, sizeof(hex), "%08x", (uint32_t)m_semaphore); - res += hex; - res += "), owner: " + m_owner; - return res; -} // toString - - -/** - * @brief Set the name of the semaphore. - * @param [in] name The name of the semaphore. - */ -void FreeRTOS::Semaphore::setName(std::string name) { - m_name = name; -} // setName - - -/** - * @brief Create a ring buffer. - * @param [in] length The amount of storage to allocate for the ring buffer. - * @param [in] type The type of buffer. One of RINGBUF_TYPE_NOSPLIT, RINGBUF_TYPE_ALLOWSPLIT, RINGBUF_TYPE_BYTEBUF. - */ -#ifdef ESP_IDF_VERSION_MAJOR -Ringbuffer::Ringbuffer(size_t length, RingbufferType_t type) -#else -Ringbuffer::Ringbuffer(size_t length, ringbuf_type_t type) -#endif -{ - m_handle = ::xRingbufferCreate(length, type); -} // Ringbuffer - - -Ringbuffer::~Ringbuffer() { - ::vRingbufferDelete(m_handle); -} // ~Ringbuffer - - -/** - * @brief Receive data from the buffer. - * @param [out] size On return, the size of data returned. - * @param [in] wait How long to wait. - * @return A pointer to the storage retrieved. - */ -void* Ringbuffer::receive(size_t* size, TickType_t wait) { - return ::xRingbufferReceive(m_handle, size, wait); -} // receive - - -/** - * @brief Return an item. - * @param [in] item The item to be returned/released. - */ -void Ringbuffer::returnItem(void* item) { - ::vRingbufferReturnItem(m_handle, item); -} // returnItem - - -/** - * @brief Send data to the buffer. - * @param [in] data The data to place into the buffer. - * @param [in] length The length of data to place into the buffer. - * @param [in] wait How long to wait before giving up. The default is to wait indefinitely. - * @return - */ -bool Ringbuffer::send(void* data, size_t length, TickType_t wait) { - return ::xRingbufferSend(m_handle, data, length, wait) == pdTRUE; -} // send - - diff --git a/libraries/BLE/src/GeneralUtils.cpp b/libraries/BLE/src/GeneralUtils.cpp deleted file mode 100644 index 4f1de12b..00000000 --- a/libraries/BLE/src/GeneralUtils.cpp +++ /dev/null @@ -1,541 +0,0 @@ -/* - * GeneralUtils.cpp - * - * Created on: May 20, 2017 - * Author: kolban - */ - -#include "GeneralUtils.h" -#include -#include -#include -#include -#include -#include -#include "RTOS.h" -#include -#include -#include -#include -#include -#include "esp32-hal-log.h" - -static const char kBase64Alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" - "abcdefghijklmnopqrstuvwxyz" - "0123456789+/"; - -static int base64EncodedLength(size_t length) { - return (length + 2 - ((length + 2) % 3)) / 3 * 4; -} // base64EncodedLength - - -static int base64EncodedLength(const std::string& in) { - return base64EncodedLength(in.length()); -} // base64EncodedLength - - -static void a3_to_a4(unsigned char* a4, unsigned char* a3) { - a4[0] = (a3[0] & 0xfc) >> 2; - a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4); - a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6); - a4[3] = (a3[2] & 0x3f); -} // a3_to_a4 - - -static void a4_to_a3(unsigned char* a3, unsigned char* a4) { - a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4); - a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2); - a3[2] = ((a4[2] & 0x3) << 6) + a4[3]; -} // a4_to_a3 - - -/** - * @brief Encode a string into base 64. - * @param [in] in - * @param [out] out - */ -bool GeneralUtils::base64Encode(const std::string& in, std::string* out) { - int i = 0, j = 0; - size_t enc_len = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - out->resize(base64EncodedLength(in)); - - int input_len = in.size(); - std::string::const_iterator input = in.begin(); - - while (input_len--) { - a3[i++] = *(input++); - if (i == 3) { - a3_to_a4(a4, a3); - - for (i = 0; i < 4; i++) { - (*out)[enc_len++] = kBase64Alphabet[a4[i]]; - } - - i = 0; - } - } - - if (i) { - for (j = i; j < 3; j++) { - a3[j] = '\0'; - } - - a3_to_a4(a4, a3); - - for (j = 0; j < i + 1; j++) { - (*out)[enc_len++] = kBase64Alphabet[a4[j]]; - } - - while ((i++ < 3)) { - (*out)[enc_len++] = '='; - } - } - - return (enc_len == out->size()); -} // base64Encode - - -/** - * @brief Dump general info to the log. - * Data includes: - * * Amount of free RAM - */ -void GeneralUtils::dumpInfo() { - esp_chip_info_t chipInfo; - esp_chip_info(&chipInfo); - log_v("--- dumpInfo ---"); - log_v("Free heap: %d", heap_caps_get_free_size(MALLOC_CAP_8BIT)); - log_v("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model, chipInfo.cores, chipInfo.revision); - log_v("ESP-IDF version: %s", esp_get_idf_version()); - log_v("---"); -} // dumpInfo - - -/** - * @brief Does the string end with a specific character? - * @param [in] str The string to examine. - * @param [in] c The character to look form. - * @return True if the string ends with the given character. - */ -bool GeneralUtils::endsWith(std::string str, char c) { - if (str.empty()) { - return false; - } - if (str.at(str.length() - 1) == c) { - return true; - } - return false; -} // endsWidth - - -static int DecodedLength(const std::string& in) { - int numEq = 0; - int n = (int) in.size(); - - for (std::string::const_reverse_iterator it = in.rbegin(); *it == '='; ++it) { - ++numEq; - } - return ((6 * n) / 8) - numEq; -} // DecodedLength - - -static unsigned char b64_lookup(unsigned char c) { - if(c >='A' && c <='Z') return c - 'A'; - if(c >='a' && c <='z') return c - 71; - if(c >='0' && c <='9') return c + 4; - if(c == '+') return 62; - if(c == '/') return 63; - return 255; -}; // b64_lookup - - -/** - * @brief Decode a chunk of data that is base64 encoded. - * @param [in] in The string to be decoded. - * @param [out] out The resulting data. - */ -bool GeneralUtils::base64Decode(const std::string& in, std::string* out) { - int i = 0, j = 0; - size_t dec_len = 0; - unsigned char a3[3]; - unsigned char a4[4]; - - int input_len = in.size(); - std::string::const_iterator input = in.begin(); - - out->resize(DecodedLength(in)); - - while (input_len--) { - if (*input == '=') { - break; - } - - a4[i++] = *(input++); - if (i == 4) { - for (i = 0; i <4; i++) { - a4[i] = b64_lookup(a4[i]); - } - - a4_to_a3(a3,a4); - - for (i = 0; i < 3; i++) { - (*out)[dec_len++] = a3[i]; - } - - i = 0; - } - } - - if (i) { - for (j = i; j < 4; j++) { - a4[j] = '\0'; - } - - for (j = 0; j < 4; j++) { - a4[j] = b64_lookup(a4[j]); - } - - a4_to_a3(a3,a4); - - for (j = 0; j < i - 1; j++) { - (*out)[dec_len++] = a3[j]; - } - } - - return (dec_len == out->size()); - } // base64Decode - -/* -void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { - uint32_t index=0; - std::stringstream ascii; - std::stringstream hex; - char asciiBuf[80]; - char hexBuf[80]; - hex.str(""); - ascii.str(""); - while(index < length) { - hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; - if (std::isprint(pData[index])) { - ascii << pData[index]; - } else { - ascii << '.'; - } - index++; - if (index % 16 == 0) { - strcpy(hexBuf, hex.str().c_str()); - strcpy(asciiBuf, ascii.str().c_str()); - log_v("%s %s", hexBuf, asciiBuf); - hex.str(""); - ascii.str(""); - } - } - if (index %16 != 0) { - while(index % 16 != 0) { - hex << " "; - index++; - } - strcpy(hexBuf, hex.str().c_str()); - strcpy(asciiBuf, ascii.str().c_str()); - log_v("%s %s", hexBuf, asciiBuf); - //log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); - } - FreeRTOS::sleep(1000); -} -*/ - -/* -void GeneralUtils::hexDump(uint8_t* pData, uint32_t length) { - uint32_t index=0; - static std::stringstream ascii; - static std::stringstream hex; - hex.str(""); - ascii.str(""); - while(index < length) { - hex << std::setfill('0') << std::setw(2) << std::hex << (int)pData[index] << ' '; - if (std::isprint(pData[index])) { - ascii << pData[index]; - } else { - ascii << '.'; - } - index++; - if (index % 16 == 0) { - log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); - hex.str(""); - ascii.str(""); - } - } - if (index %16 != 0) { - while(index % 16 != 0) { - hex << " "; - index++; - } - log_v("%s %s", hex.str().c_str(), ascii.str().c_str()); - } - FreeRTOS::sleep(1000); -} -*/ - - -/** - * @brief Dump a representation of binary data to the console. - * - * @param [in] pData Pointer to the start of data to be logged. - * @param [in] length Length of the data (in bytes) to be logged. - * @return N/A. - */ -void GeneralUtils::hexDump(const uint8_t* pData, uint32_t length) { - char ascii[80]; - char hex[80]; - char tempBuf[80]; - uint32_t lineNumber = 0; - - log_v(" 00 01 02 03 04 05 06 07 08 09 0a 0b 0c 0d 0e 0f"); - log_v(" -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --"); - strcpy(ascii, ""); - strcpy(hex, ""); - uint32_t index = 0; - while (index < length) { - sprintf(tempBuf, "%.2x ", pData[index]); - strcat(hex, tempBuf); - if (isprint(pData[index])) { - sprintf(tempBuf, "%c", pData[index]); - } else { - sprintf(tempBuf, "."); - } - strcat(ascii, tempBuf); - index++; - if (index % 16 == 0) { - log_v("%.4x %s %s", lineNumber * 16, hex, ascii); - strcpy(ascii, ""); - strcpy(hex, ""); - lineNumber++; - } - } - if (index %16 != 0) { - while (index % 16 != 0) { - strcat(hex, " "); - index++; - } - log_v("%.4x %s %s", lineNumber * 16, hex, ascii); - } -} // hexDump - - -/** - * @brief Convert an IP address to string. - * @param ip The 4 byte IP address. - * @return A string representation of the IP address. - */ -std::string GeneralUtils::ipToString(uint8_t *ip) { - auto size = 16; - char *val = (char*)malloc(size); - snprintf(val, size, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]); - std::string res(val); - free(val); - return res; -} // ipToString - - -/** - * @brief Split a string into parts based on a delimiter. - * @param [in] source The source string to split. - * @param [in] delimiter The delimiter characters. - * @return A vector of strings that are the split of the input. - */ -std::vector GeneralUtils::split(std::string source, char delimiter) { - // See also: https://stackoverflow.com/questions/5167625/splitting-a-c-stdstring-using-tokens-e-g - std::vector strings; - std::size_t current, previous = 0; - current = source.find(delimiter); - while (current != std::string::npos) { - strings.push_back(trim(source.substr(previous, current - previous))); - previous = current + 1; - current = source.find(delimiter, previous); - } - strings.push_back(trim(source.substr(previous, current - previous))); - return strings; -} // split - - -/** - * @brief Convert an ESP error code to a string. - * @param [in] errCode The errCode to be converted. - * @return A string representation of the error code. - */ -const char* GeneralUtils::errorToString(esp_err_t errCode) { - switch (errCode) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case ESP_OK: - return "ESP_OK"; - case ESP_FAIL: - return "ESP_FAIL"; - case ESP_ERR_NO_MEM: - return "ESP_ERR_NO_MEM"; - case ESP_ERR_INVALID_ARG: - return "ESP_ERR_INVALID_ARG"; - case ESP_ERR_INVALID_SIZE: - return "ESP_ERR_INVALID_SIZE"; - case ESP_ERR_INVALID_STATE: - return "ESP_ERR_INVALID_STATE"; - case ESP_ERR_NOT_FOUND: - return "ESP_ERR_NOT_FOUND"; - case ESP_ERR_NOT_SUPPORTED: - return "ESP_ERR_NOT_SUPPORTED"; - case ESP_ERR_TIMEOUT: - return "ESP_ERR_TIMEOUT"; - case ESP_ERR_NVS_NOT_INITIALIZED: - return "ESP_ERR_NVS_NOT_INITIALIZED"; - case ESP_ERR_NVS_NOT_FOUND: - return "ESP_ERR_NVS_NOT_FOUND"; - case ESP_ERR_NVS_TYPE_MISMATCH: - return "ESP_ERR_NVS_TYPE_MISMATCH"; - case ESP_ERR_NVS_READ_ONLY: - return "ESP_ERR_NVS_READ_ONLY"; - case ESP_ERR_NVS_NOT_ENOUGH_SPACE: - return "ESP_ERR_NVS_NOT_ENOUGH_SPACE"; - case ESP_ERR_NVS_INVALID_NAME: - return "ESP_ERR_NVS_INVALID_NAME"; - case ESP_ERR_NVS_INVALID_HANDLE: - return "ESP_ERR_NVS_INVALID_HANDLE"; - case ESP_ERR_NVS_REMOVE_FAILED: - return "ESP_ERR_NVS_REMOVE_FAILED"; - case ESP_ERR_NVS_KEY_TOO_LONG: - return "ESP_ERR_NVS_KEY_TOO_LONG"; - case ESP_ERR_NVS_PAGE_FULL: - return "ESP_ERR_NVS_PAGE_FULL"; - case ESP_ERR_NVS_INVALID_STATE: - return "ESP_ERR_NVS_INVALID_STATE"; - case ESP_ERR_NVS_INVALID_LENGTH: - return "ESP_ERR_NVS_INVALID_LENGTH"; - case ESP_ERR_WIFI_NOT_INIT: - return "ESP_ERR_WIFI_NOT_INIT"; - //case ESP_ERR_WIFI_NOT_START: - // return "ESP_ERR_WIFI_NOT_START"; - case ESP_ERR_WIFI_IF: - return "ESP_ERR_WIFI_IF"; - case ESP_ERR_WIFI_MODE: - return "ESP_ERR_WIFI_MODE"; - case ESP_ERR_WIFI_STATE: - return "ESP_ERR_WIFI_STATE"; - case ESP_ERR_WIFI_CONN: - return "ESP_ERR_WIFI_CONN"; - case ESP_ERR_WIFI_NVS: - return "ESP_ERR_WIFI_NVS"; - case ESP_ERR_WIFI_MAC: - return "ESP_ERR_WIFI_MAC"; - case ESP_ERR_WIFI_SSID: - return "ESP_ERR_WIFI_SSID"; - case ESP_ERR_WIFI_PASSWORD: - return "ESP_ERR_WIFI_PASSWORD"; - case ESP_ERR_WIFI_TIMEOUT: - return "ESP_ERR_WIFI_TIMEOUT"; - case ESP_ERR_WIFI_WAKE_FAIL: - return "ESP_ERR_WIFI_WAKE_FAIL"; -#endif - default: - return "Unknown ESP_ERR error"; - } -} // errorToString - -/** - * @brief Convert a wifi_err_reason_t code to a string. - * @param [in] errCode The errCode to be converted. - * @return A string representation of the error code. - * - * @note: wifi_err_reason_t values as of April 2018 are: (1-24, 200-204) and are defined in ~/esp-idf/components/esp32/include/esp_wifi_types.h. - */ -const char* GeneralUtils::wifiErrorToString(uint8_t errCode) { - if (errCode == ESP_OK) return "ESP_OK (received SYSTEM_EVENT_STA_GOT_IP event)"; - if (errCode == UINT8_MAX) return "Not Connected (default value)"; - - switch ((wifi_err_reason_t) errCode) { -#if CONFIG_LOG_DEFAULT_LEVEL > 4 - case WIFI_REASON_UNSPECIFIED: - return "WIFI_REASON_UNSPECIFIED"; - case WIFI_REASON_AUTH_EXPIRE: - return "WIFI_REASON_AUTH_EXPIRE"; - case WIFI_REASON_AUTH_LEAVE: - return "WIFI_REASON_AUTH_LEAVE"; - case WIFI_REASON_ASSOC_EXPIRE: - return "WIFI_REASON_ASSOC_EXPIRE"; - case WIFI_REASON_ASSOC_TOOMANY: - return "WIFI_REASON_ASSOC_TOOMANY"; - case WIFI_REASON_NOT_AUTHED: - return "WIFI_REASON_NOT_AUTHED"; - case WIFI_REASON_NOT_ASSOCED: - return "WIFI_REASON_NOT_ASSOCED"; - case WIFI_REASON_ASSOC_LEAVE: - return "WIFI_REASON_ASSOC_LEAVE"; - case WIFI_REASON_ASSOC_NOT_AUTHED: - return "WIFI_REASON_ASSOC_NOT_AUTHED"; - case WIFI_REASON_DISASSOC_PWRCAP_BAD: - return "WIFI_REASON_DISASSOC_PWRCAP_BAD"; - case WIFI_REASON_DISASSOC_SUPCHAN_BAD: - return "WIFI_REASON_DISASSOC_SUPCHAN_BAD"; - case WIFI_REASON_IE_INVALID: - return "WIFI_REASON_IE_INVALID"; - case WIFI_REASON_MIC_FAILURE: - return "WIFI_REASON_MIC_FAILURE"; - case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: - return "WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT"; - case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT: - return "WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT"; - case WIFI_REASON_IE_IN_4WAY_DIFFERS: - return "WIFI_REASON_IE_IN_4WAY_DIFFERS"; - case WIFI_REASON_GROUP_CIPHER_INVALID: - return "WIFI_REASON_GROUP_CIPHER_INVALID"; - case WIFI_REASON_PAIRWISE_CIPHER_INVALID: - return "WIFI_REASON_PAIRWISE_CIPHER_INVALID"; - case WIFI_REASON_AKMP_INVALID: - return "WIFI_REASON_AKMP_INVALID"; - case WIFI_REASON_UNSUPP_RSN_IE_VERSION: - return "WIFI_REASON_UNSUPP_RSN_IE_VERSION"; - case WIFI_REASON_INVALID_RSN_IE_CAP: - return "WIFI_REASON_INVALID_RSN_IE_CAP"; - case WIFI_REASON_802_1X_AUTH_FAILED: - return "WIFI_REASON_802_1X_AUTH_FAILED"; - case WIFI_REASON_CIPHER_SUITE_REJECTED: - return "WIFI_REASON_CIPHER_SUITE_REJECTED"; - case WIFI_REASON_BEACON_TIMEOUT: - return "WIFI_REASON_BEACON_TIMEOUT"; - case WIFI_REASON_NO_AP_FOUND: - return "WIFI_REASON_NO_AP_FOUND"; - case WIFI_REASON_AUTH_FAIL: - return "WIFI_REASON_AUTH_FAIL"; - case WIFI_REASON_ASSOC_FAIL: - return "WIFI_REASON_ASSOC_FAIL"; - case WIFI_REASON_HANDSHAKE_TIMEOUT: - return "WIFI_REASON_HANDSHAKE_TIMEOUT"; -#endif - default: - return "Unknown ESP_ERR error"; - } -} // wifiErrorToString - - -/** - * @brief Convert a string to lower case. - * @param [in] value The string to convert to lower case. - * @return A lower case representation of the string. - */ -std::string GeneralUtils::toLower(std::string& value) { - // Question: Could this be improved with a signature of: - // std::string& GeneralUtils::toLower(std::string& value) - std::transform(value.begin(), value.end(), value.begin(), ::tolower); - return value; -} // toLower - - -/** - * @brief Remove white space from a string. - */ -std::string GeneralUtils::trim(const std::string& str) { - size_t first = str.find_first_not_of(' '); - if (std::string::npos == first) return str; - size_t last = str.find_last_not_of(' '); - return str.substr(first, (last - first + 1)); -} // trim diff --git a/libraries/BLE/src/GeneralUtils.h b/libraries/BLE/src/GeneralUtils.h deleted file mode 100644 index 8eecbd4d..00000000 --- a/libraries/BLE/src/GeneralUtils.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * GeneralUtils.h - * - * Created on: May 20, 2017 - * Author: kolban - */ - -#ifndef COMPONENTS_CPP_UTILS_GENERALUTILS_H_ -#define COMPONENTS_CPP_UTILS_GENERALUTILS_H_ -#include -#include -#include -#include -#include - -/** - * @brief General utilities. - */ -class GeneralUtils { -public: - static bool base64Decode(const std::string& in, std::string* out); - static bool base64Encode(const std::string& in, std::string* out); - static void dumpInfo(); - static bool endsWith(std::string str, char c); - static const char* errorToString(esp_err_t errCode); - static const char* wifiErrorToString(uint8_t value); - static void hexDump(const uint8_t* pData, uint32_t length); - static std::string ipToString(uint8_t* ip); - static std::vector split(std::string source, char delimiter); - static std::string toLower(std::string& value); - static std::string trim(const std::string& str); - -}; - -#endif /* COMPONENTS_CPP_UTILS_GENERALUTILS_H_ */ diff --git a/libraries/BLE/src/HIDKeyboardTypes.h b/libraries/BLE/src/HIDKeyboardTypes.h deleted file mode 100644 index 4e221d57..00000000 --- a/libraries/BLE/src/HIDKeyboardTypes.h +++ /dev/null @@ -1,402 +0,0 @@ -/* Copyright (c) 2015 mbed.org, MIT License - * - * Permission is hereby granted, free of charge, to any person obtaining a copy of this software - * and associated documentation files (the "Software"), to deal in the Software without - * restriction, including without limitation the rights to use, copy, modify, merge, publish, - * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the - * Software is furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in all copies or - * substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING - * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND - * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, - * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - * - * Note: this file was pulled from different parts of the USBHID library, in mbed SDK - */ - -#ifndef KEYBOARD_DEFS_H -#define KEYBOARD_DEFS_H - -#define REPORT_ID_KEYBOARD 1 -#define REPORT_ID_VOLUME 3 - -/* Modifiers */ -enum MODIFIER_KEY { - KEY_CTRL = 1, - KEY_SHIFT = 2, - KEY_ALT = 4, -}; - - -enum MEDIA_KEY { - KEY_NEXT_TRACK, /*!< next Track Button */ - KEY_PREVIOUS_TRACK, /*!< Previous track Button */ - KEY_STOP, /*!< Stop Button */ - KEY_PLAY_PAUSE, /*!< Play/Pause Button */ - KEY_MUTE, /*!< Mute Button */ - KEY_VOLUME_UP, /*!< Volume Up Button */ - KEY_VOLUME_DOWN, /*!< Volume Down Button */ -}; - -enum FUNCTION_KEY { - KEY_F1 = 128, /* F1 key */ - KEY_F2, /* F2 key */ - KEY_F3, /* F3 key */ - KEY_F4, /* F4 key */ - KEY_F5, /* F5 key */ - KEY_F6, /* F6 key */ - KEY_F7, /* F7 key */ - KEY_F8, /* F8 key */ - KEY_F9, /* F9 key */ - KEY_F10, /* F10 key */ - KEY_F11, /* F11 key */ - KEY_F12, /* F12 key */ - - KEY_PRINT_SCREEN, /* Print Screen key */ - KEY_SCROLL_LOCK, /* Scroll lock */ - KEY_CAPS_LOCK, /* caps lock */ - KEY_NUM_LOCK, /* num lock */ - KEY_INSERT, /* Insert key */ - KEY_HOME, /* Home key */ - KEY_PAGE_UP, /* Page Up key */ - KEY_PAGE_DOWN, /* Page Down key */ - - RIGHT_ARROW, /* Right arrow */ - LEFT_ARROW, /* Left arrow */ - DOWN_ARROW, /* Down arrow */ - UP_ARROW, /* Up arrow */ -}; - -typedef struct { - unsigned char usage; - unsigned char modifier; -} KEYMAP; - -#ifdef US_KEYBOARD -/* US keyboard (as HID standard) */ -#define KEYMAP_SIZE (152) -const KEYMAP keymap[KEYMAP_SIZE] = { - {0, 0}, /* NUL */ - {0, 0}, /* SOH */ - {0, 0}, /* STX */ - {0, 0}, /* ETX */ - {0, 0}, /* EOT */ - {0, 0}, /* ENQ */ - {0, 0}, /* ACK */ - {0, 0}, /* BEL */ - {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ - {0x2b, 0}, /* TAB */ /* Keyboard Tab */ - {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ - {0, 0}, /* VT */ - {0, 0}, /* FF */ - {0, 0}, /* CR */ - {0, 0}, /* SO */ - {0, 0}, /* SI */ - {0, 0}, /* DEL */ - {0, 0}, /* DC1 */ - {0, 0}, /* DC2 */ - {0, 0}, /* DC3 */ - {0, 0}, /* DC4 */ - {0, 0}, /* NAK */ - {0, 0}, /* SYN */ - {0, 0}, /* ETB */ - {0, 0}, /* CAN */ - {0, 0}, /* EM */ - {0, 0}, /* SUB */ - {0, 0}, /* ESC */ - {0, 0}, /* FS */ - {0, 0}, /* GS */ - {0, 0}, /* RS */ - {0, 0}, /* US */ - {0x2c, 0}, /* */ - {0x1e, KEY_SHIFT}, /* ! */ - {0x34, KEY_SHIFT}, /* " */ - {0x20, KEY_SHIFT}, /* # */ - {0x21, KEY_SHIFT}, /* $ */ - {0x22, KEY_SHIFT}, /* % */ - {0x24, KEY_SHIFT}, /* & */ - {0x34, 0}, /* ' */ - {0x26, KEY_SHIFT}, /* ( */ - {0x27, KEY_SHIFT}, /* ) */ - {0x25, KEY_SHIFT}, /* * */ - {0x2e, KEY_SHIFT}, /* + */ - {0x36, 0}, /* , */ - {0x2d, 0}, /* - */ - {0x37, 0}, /* . */ - {0x38, 0}, /* / */ - {0x27, 0}, /* 0 */ - {0x1e, 0}, /* 1 */ - {0x1f, 0}, /* 2 */ - {0x20, 0}, /* 3 */ - {0x21, 0}, /* 4 */ - {0x22, 0}, /* 5 */ - {0x23, 0}, /* 6 */ - {0x24, 0}, /* 7 */ - {0x25, 0}, /* 8 */ - {0x26, 0}, /* 9 */ - {0x33, KEY_SHIFT}, /* : */ - {0x33, 0}, /* ; */ - {0x36, KEY_SHIFT}, /* < */ - {0x2e, 0}, /* = */ - {0x37, KEY_SHIFT}, /* > */ - {0x38, KEY_SHIFT}, /* ? */ - {0x1f, KEY_SHIFT}, /* @ */ - {0x04, KEY_SHIFT}, /* A */ - {0x05, KEY_SHIFT}, /* B */ - {0x06, KEY_SHIFT}, /* C */ - {0x07, KEY_SHIFT}, /* D */ - {0x08, KEY_SHIFT}, /* E */ - {0x09, KEY_SHIFT}, /* F */ - {0x0a, KEY_SHIFT}, /* G */ - {0x0b, KEY_SHIFT}, /* H */ - {0x0c, KEY_SHIFT}, /* I */ - {0x0d, KEY_SHIFT}, /* J */ - {0x0e, KEY_SHIFT}, /* K */ - {0x0f, KEY_SHIFT}, /* L */ - {0x10, KEY_SHIFT}, /* M */ - {0x11, KEY_SHIFT}, /* N */ - {0x12, KEY_SHIFT}, /* O */ - {0x13, KEY_SHIFT}, /* P */ - {0x14, KEY_SHIFT}, /* Q */ - {0x15, KEY_SHIFT}, /* R */ - {0x16, KEY_SHIFT}, /* S */ - {0x17, KEY_SHIFT}, /* T */ - {0x18, KEY_SHIFT}, /* U */ - {0x19, KEY_SHIFT}, /* V */ - {0x1a, KEY_SHIFT}, /* W */ - {0x1b, KEY_SHIFT}, /* X */ - {0x1c, KEY_SHIFT}, /* Y */ - {0x1d, KEY_SHIFT}, /* Z */ - {0x2f, 0}, /* [ */ - {0x31, 0}, /* \ */ - {0x30, 0}, /* ] */ - {0x23, KEY_SHIFT}, /* ^ */ - {0x2d, KEY_SHIFT}, /* _ */ - {0x35, 0}, /* ` */ - {0x04, 0}, /* a */ - {0x05, 0}, /* b */ - {0x06, 0}, /* c */ - {0x07, 0}, /* d */ - {0x08, 0}, /* e */ - {0x09, 0}, /* f */ - {0x0a, 0}, /* g */ - {0x0b, 0}, /* h */ - {0x0c, 0}, /* i */ - {0x0d, 0}, /* j */ - {0x0e, 0}, /* k */ - {0x0f, 0}, /* l */ - {0x10, 0}, /* m */ - {0x11, 0}, /* n */ - {0x12, 0}, /* o */ - {0x13, 0}, /* p */ - {0x14, 0}, /* q */ - {0x15, 0}, /* r */ - {0x16, 0}, /* s */ - {0x17, 0}, /* t */ - {0x18, 0}, /* u */ - {0x19, 0}, /* v */ - {0x1a, 0}, /* w */ - {0x1b, 0}, /* x */ - {0x1c, 0}, /* y */ - {0x1d, 0}, /* z */ - {0x2f, KEY_SHIFT}, /* { */ - {0x31, KEY_SHIFT}, /* | */ - {0x30, KEY_SHIFT}, /* } */ - {0x35, KEY_SHIFT}, /* ~ */ - {0,0}, /* DEL */ - - {0x3a, 0}, /* F1 */ - {0x3b, 0}, /* F2 */ - {0x3c, 0}, /* F3 */ - {0x3d, 0}, /* F4 */ - {0x3e, 0}, /* F5 */ - {0x3f, 0}, /* F6 */ - {0x40, 0}, /* F7 */ - {0x41, 0}, /* F8 */ - {0x42, 0}, /* F9 */ - {0x43, 0}, /* F10 */ - {0x44, 0}, /* F11 */ - {0x45, 0}, /* F12 */ - - {0x46, 0}, /* PRINT_SCREEN */ - {0x47, 0}, /* SCROLL_LOCK */ - {0x39, 0}, /* CAPS_LOCK */ - {0x53, 0}, /* NUM_LOCK */ - {0x49, 0}, /* INSERT */ - {0x4a, 0}, /* HOME */ - {0x4b, 0}, /* PAGE_UP */ - {0x4e, 0}, /* PAGE_DOWN */ - - {0x4f, 0}, /* RIGHT_ARROW */ - {0x50, 0}, /* LEFT_ARROW */ - {0x51, 0}, /* DOWN_ARROW */ - {0x52, 0}, /* UP_ARROW */ -}; - -#else -/* UK keyboard */ -#define KEYMAP_SIZE (152) -const KEYMAP keymap[KEYMAP_SIZE] = { - {0, 0}, /* NUL */ - {0, 0}, /* SOH */ - {0, 0}, /* STX */ - {0, 0}, /* ETX */ - {0, 0}, /* EOT */ - {0, 0}, /* ENQ */ - {0, 0}, /* ACK */ - {0, 0}, /* BEL */ - {0x2a, 0}, /* BS */ /* Keyboard Delete (Backspace) */ - {0x2b, 0}, /* TAB */ /* Keyboard Tab */ - {0x28, 0}, /* LF */ /* Keyboard Return (Enter) */ - {0, 0}, /* VT */ - {0, 0}, /* FF */ - {0, 0}, /* CR */ - {0, 0}, /* SO */ - {0, 0}, /* SI */ - {0, 0}, /* DEL */ - {0, 0}, /* DC1 */ - {0, 0}, /* DC2 */ - {0, 0}, /* DC3 */ - {0, 0}, /* DC4 */ - {0, 0}, /* NAK */ - {0, 0}, /* SYN */ - {0, 0}, /* ETB */ - {0, 0}, /* CAN */ - {0, 0}, /* EM */ - {0, 0}, /* SUB */ - {0, 0}, /* ESC */ - {0, 0}, /* FS */ - {0, 0}, /* GS */ - {0, 0}, /* RS */ - {0, 0}, /* US */ - {0x2c, 0}, /* */ - {0x1e, KEY_SHIFT}, /* ! */ - {0x1f, KEY_SHIFT}, /* " */ - {0x32, 0}, /* # */ - {0x21, KEY_SHIFT}, /* $ */ - {0x22, KEY_SHIFT}, /* % */ - {0x24, KEY_SHIFT}, /* & */ - {0x34, 0}, /* ' */ - {0x26, KEY_SHIFT}, /* ( */ - {0x27, KEY_SHIFT}, /* ) */ - {0x25, KEY_SHIFT}, /* * */ - {0x2e, KEY_SHIFT}, /* + */ - {0x36, 0}, /* , */ - {0x2d, 0}, /* - */ - {0x37, 0}, /* . */ - {0x38, 0}, /* / */ - {0x27, 0}, /* 0 */ - {0x1e, 0}, /* 1 */ - {0x1f, 0}, /* 2 */ - {0x20, 0}, /* 3 */ - {0x21, 0}, /* 4 */ - {0x22, 0}, /* 5 */ - {0x23, 0}, /* 6 */ - {0x24, 0}, /* 7 */ - {0x25, 0}, /* 8 */ - {0x26, 0}, /* 9 */ - {0x33, KEY_SHIFT}, /* : */ - {0x33, 0}, /* ; */ - {0x36, KEY_SHIFT}, /* < */ - {0x2e, 0}, /* = */ - {0x37, KEY_SHIFT}, /* > */ - {0x38, KEY_SHIFT}, /* ? */ - {0x34, KEY_SHIFT}, /* @ */ - {0x04, KEY_SHIFT}, /* A */ - {0x05, KEY_SHIFT}, /* B */ - {0x06, KEY_SHIFT}, /* C */ - {0x07, KEY_SHIFT}, /* D */ - {0x08, KEY_SHIFT}, /* E */ - {0x09, KEY_SHIFT}, /* F */ - {0x0a, KEY_SHIFT}, /* G */ - {0x0b, KEY_SHIFT}, /* H */ - {0x0c, KEY_SHIFT}, /* I */ - {0x0d, KEY_SHIFT}, /* J */ - {0x0e, KEY_SHIFT}, /* K */ - {0x0f, KEY_SHIFT}, /* L */ - {0x10, KEY_SHIFT}, /* M */ - {0x11, KEY_SHIFT}, /* N */ - {0x12, KEY_SHIFT}, /* O */ - {0x13, KEY_SHIFT}, /* P */ - {0x14, KEY_SHIFT}, /* Q */ - {0x15, KEY_SHIFT}, /* R */ - {0x16, KEY_SHIFT}, /* S */ - {0x17, KEY_SHIFT}, /* T */ - {0x18, KEY_SHIFT}, /* U */ - {0x19, KEY_SHIFT}, /* V */ - {0x1a, KEY_SHIFT}, /* W */ - {0x1b, KEY_SHIFT}, /* X */ - {0x1c, KEY_SHIFT}, /* Y */ - {0x1d, KEY_SHIFT}, /* Z */ - {0x2f, 0}, /* [ */ - {0x64, 0}, /* \ */ - {0x30, 0}, /* ] */ - {0x23, KEY_SHIFT}, /* ^ */ - {0x2d, KEY_SHIFT}, /* _ */ - {0x35, 0}, /* ` */ - {0x04, 0}, /* a */ - {0x05, 0}, /* b */ - {0x06, 0}, /* c */ - {0x07, 0}, /* d */ - {0x08, 0}, /* e */ - {0x09, 0}, /* f */ - {0x0a, 0}, /* g */ - {0x0b, 0}, /* h */ - {0x0c, 0}, /* i */ - {0x0d, 0}, /* j */ - {0x0e, 0}, /* k */ - {0x0f, 0}, /* l */ - {0x10, 0}, /* m */ - {0x11, 0}, /* n */ - {0x12, 0}, /* o */ - {0x13, 0}, /* p */ - {0x14, 0}, /* q */ - {0x15, 0}, /* r */ - {0x16, 0}, /* s */ - {0x17, 0}, /* t */ - {0x18, 0}, /* u */ - {0x19, 0}, /* v */ - {0x1a, 0}, /* w */ - {0x1b, 0}, /* x */ - {0x1c, 0}, /* y */ - {0x1d, 0}, /* z */ - {0x2f, KEY_SHIFT}, /* { */ - {0x64, KEY_SHIFT}, /* | */ - {0x30, KEY_SHIFT}, /* } */ - {0x32, KEY_SHIFT}, /* ~ */ - {0,0}, /* DEL */ - - {0x3a, 0}, /* F1 */ - {0x3b, 0}, /* F2 */ - {0x3c, 0}, /* F3 */ - {0x3d, 0}, /* F4 */ - {0x3e, 0}, /* F5 */ - {0x3f, 0}, /* F6 */ - {0x40, 0}, /* F7 */ - {0x41, 0}, /* F8 */ - {0x42, 0}, /* F9 */ - {0x43, 0}, /* F10 */ - {0x44, 0}, /* F11 */ - {0x45, 0}, /* F12 */ - - {0x46, 0}, /* PRINT_SCREEN */ - {0x47, 0}, /* SCROLL_LOCK */ - {0x39, 0}, /* CAPS_LOCK */ - {0x53, 0}, /* NUM_LOCK */ - {0x49, 0}, /* INSERT */ - {0x4a, 0}, /* HOME */ - {0x4b, 0}, /* PAGE_UP */ - {0x4e, 0}, /* PAGE_DOWN */ - - {0x4f, 0}, /* RIGHT_ARROW */ - {0x50, 0}, /* LEFT_ARROW */ - {0x51, 0}, /* DOWN_ARROW */ - {0x52, 0}, /* UP_ARROW */ -}; -#endif - -#endif diff --git a/libraries/BLE/src/HIDTypes.h b/libraries/BLE/src/HIDTypes.h deleted file mode 100644 index 64850ef8..00000000 --- a/libraries/BLE/src/HIDTypes.h +++ /dev/null @@ -1,96 +0,0 @@ -/* Copyright (c) 2010-2011 mbed.org, MIT License -* -* Permission is hereby granted, free of charge, to any person obtaining a copy of this software -* and associated documentation files (the "Software"), to deal in the Software without -* restriction, including without limitation the rights to use, copy, modify, merge, publish, -* distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the -* Software is furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in all copies or -* substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING -* BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -*/ - -#ifndef USBCLASS_HID_TYPES -#define USBCLASS_HID_TYPES - -#include - -/* */ -#define HID_VERSION_1_11 (0x0111) - -/* HID Class */ -#define HID_CLASS (3) -#define HID_SUBCLASS_NONE (0) -#define HID_PROTOCOL_NONE (0) - -/* Descriptors */ -#define HID_DESCRIPTOR (33) -#define HID_DESCRIPTOR_LENGTH (0x09) -#define REPORT_DESCRIPTOR (34) - -/* Class requests */ -#define GET_REPORT (0x1) -#define GET_IDLE (0x2) -#define SET_REPORT (0x9) -#define SET_IDLE (0xa) - -/* HID Class Report Descriptor */ -/* Short items: size is 0, 1, 2 or 3 specifying 0, 1, 2 or 4 (four) bytes */ -/* of data as per HID Class standard */ - -/* Main items */ -#ifdef ARDUINO_ARCH_ESP32 -#define HIDINPUT(size) (0x80 | size) -#define HIDOUTPUT(size) (0x90 | size) -#else -#define INPUT(size) (0x80 | size) -#define OUTPUT(size) (0x90 | size) -#endif -#define FEATURE(size) (0xb0 | size) -#define COLLECTION(size) (0xa0 | size) -#define END_COLLECTION(size) (0xc0 | size) - -/* Global items */ -#define USAGE_PAGE(size) (0x04 | size) -#define LOGICAL_MINIMUM(size) (0x14 | size) -#define LOGICAL_MAXIMUM(size) (0x24 | size) -#define PHYSICAL_MINIMUM(size) (0x34 | size) -#define PHYSICAL_MAXIMUM(size) (0x44 | size) -#define UNIT_EXPONENT(size) (0x54 | size) -#define UNIT(size) (0x64 | size) -#define REPORT_SIZE(size) (0x74 | size) //bits -#define REPORT_ID(size) (0x84 | size) -#define REPORT_COUNT(size) (0x94 | size) //bytes -#define PUSH(size) (0xa4 | size) -#define POP(size) (0xb4 | size) - -/* Local items */ -#define USAGE(size) (0x08 | size) -#define USAGE_MINIMUM(size) (0x18 | size) -#define USAGE_MAXIMUM(size) (0x28 | size) -#define DESIGNATOR_INDEX(size) (0x38 | size) -#define DESIGNATOR_MINIMUM(size) (0x48 | size) -#define DESIGNATOR_MAXIMUM(size) (0x58 | size) -#define STRING_INDEX(size) (0x78 | size) -#define STRING_MINIMUM(size) (0x88 | size) -#define STRING_MAXIMUM(size) (0x98 | size) -#define DELIMITER(size) (0xa8 | size) - -/* HID Report */ -/* Where report IDs are used the first byte of 'data' will be the */ -/* report ID and 'length' will include this report ID byte. */ - -#define MAX_HID_REPORT_SIZE (64) - -typedef struct { - uint32_t length; - uint8_t data[MAX_HID_REPORT_SIZE]; -} HID_REPORT; - -#endif diff --git a/libraries/BLE/src/RTOS.h b/libraries/BLE/src/RTOS.h deleted file mode 100644 index d2065a73..00000000 --- a/libraries/BLE/src/RTOS.h +++ /dev/null @@ -1,81 +0,0 @@ -/* - * FreeRTOS.h - * - * Created on: Feb 24, 2017 - * Author: kolban - */ - -#ifdef __cplusplus -#ifndef MAIN_FREERTOS_H_ -#define MAIN_FREERTOS_H_ -#include -#include -#include - -#include // Include the base FreeRTOS definitions. -#include // Include the task definitions. -#include // Include the semaphore definitions. -#include // Include the ringbuffer definitions. - - -/** - * @brief Interface to %FreeRTOS functions. - */ -class FreeRTOS { -public: - static void sleep(uint32_t ms); - static void startTask(void task(void*), std::string taskName, void* param = nullptr, uint32_t stackSize = 2048); - static void deleteTask(TaskHandle_t pTask = nullptr); - - static uint32_t getTimeSinceStart(); - - class Semaphore { - public: - Semaphore(std::string owner = ""); - ~Semaphore(); - void give(); - void give(uint32_t value); - void giveFromISR(); - void setName(std::string name); - bool take(std::string owner = ""); - bool take(uint32_t timeoutMs, std::string owner = ""); - std::string toString(); - uint32_t wait(std::string owner = ""); - bool timedWait(std::string owner = "", uint32_t timeoutMs = portMAX_DELAY); - uint32_t value(){ return m_value; }; - - private: - SemaphoreHandle_t m_semaphore; - pthread_mutex_t m_pthread_mutex; - std::string m_name; - std::string m_owner; - uint32_t m_value; - bool m_usePthreads; - - }; -}; - - -/** - * @brief Ringbuffer. - */ -class Ringbuffer { -public: -#ifdef ESP_IDF_VERSION_MAJOR - Ringbuffer(size_t length, RingbufferType_t type = RINGBUF_TYPE_NOSPLIT); -#else - Ringbuffer(size_t length, ringbuf_type_t type = RINGBUF_TYPE_NOSPLIT); -#endif - ~Ringbuffer(); - - void* receive(size_t* size, TickType_t wait = portMAX_DELAY); - void returnItem(void* item); - bool send(void* data, size_t length, TickType_t wait = portMAX_DELAY); -private: - RingbufHandle_t m_handle; -}; - -#endif /* MAIN_FREERTOS_H_ */ -#else -#include "freertos/FreeRTOS.h" -#endif diff --git a/libraries/BluetoothSerial/README.md b/libraries/BluetoothSerial/README.md deleted file mode 100644 index 9d25dbca..00000000 --- a/libraries/BluetoothSerial/README.md +++ /dev/null @@ -1,19 +0,0 @@ -### Bluetooth Serial Library - -A simple Serial compatible library using ESP32 classical bluetooth (SPP) - - - -#### How to use it? - -- Download one bluetooth terminal app in your smartphone
-For Android: https://play.google.com/store/apps/details?id=de.kai_morich.serial_bluetooth_terminal
-For iOS: https://itunes.apple.com/us/app/hm10-bluetooth-serial-lite/id1030454675 - -- Flash an example sketch to your ESP32 - -- Scan and pair the device in your smartphone - -- Open the bluetooth terminal app - -- Enjoy diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBT/.skip.esp32s2 b/libraries/BluetoothSerial/examples/SerialToSerialBT/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino b/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino deleted file mode 100644 index d779c6d3..00000000 --- a/libraries/BluetoothSerial/examples/SerialToSerialBT/SerialToSerialBT.ino +++ /dev/null @@ -1,29 +0,0 @@ -//This example code is in the Public Domain (or CC0 licensed, at your option.) -//By Evandro Copercini - 2018 -// -//This example creates a bridge between Serial and Classical Bluetooth (SPP) -//and also demonstrate that SerialBT have the same functionalities of a normal Serial - -#include "BluetoothSerial.h" - -#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) -#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it -#endif - -BluetoothSerial SerialBT; - -void setup() { - Serial.begin(115200); - SerialBT.begin("ESP32test"); //Bluetooth device name - Serial.println("The device started, now you can pair it with bluetooth!"); -} - -void loop() { - if (Serial.available()) { - SerialBT.write(Serial.read()); - } - if (SerialBT.available()) { - Serial.write(SerialBT.read()); - } - delay(20); -} diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBTM/.skip.esp32s2 b/libraries/BluetoothSerial/examples/SerialToSerialBTM/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino b/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino deleted file mode 100644 index 3d17fb90..00000000 --- a/libraries/BluetoothSerial/examples/SerialToSerialBTM/SerialToSerialBTM.ino +++ /dev/null @@ -1,56 +0,0 @@ -//This example code is in the Public Domain (or CC0 licensed, at your option.) -//By Victor Tchistiak - 2019 -// -//This example demostrates master mode bluetooth connection and pin -//it creates a bridge between Serial and Classical Bluetooth (SPP) -//this is an extention of the SerialToSerialBT example by Evandro Copercini - 2018 -// - -#include "BluetoothSerial.h" - -BluetoothSerial SerialBT; - -String MACadd = "AA:BB:CC:11:22:33"; -uint8_t address[6] = {0xAA, 0xBB, 0xCC, 0x11, 0x22, 0x33}; -//uint8_t address[6] = {0x00, 0x1D, 0xA5, 0x02, 0xC3, 0x22}; -String name = "OBDII"; -const char *pin = "1234"; //<- standard pin would be provided by default -bool connected; - -void setup() { - Serial.begin(115200); - //SerialBT.setPin(pin); - SerialBT.begin("ESP32test", true); - //SerialBT.setPin(pin); - Serial.println("The device started in master mode, make sure remote BT device is on!"); - - // connect(address) is fast (upto 10 secs max), connect(name) is slow (upto 30 secs max) as it needs - // to resolve name to address first, but it allows to connect to different devices with the same name. - // Set CoreDebugLevel to Info to view devices bluetooth address and device names - connected = SerialBT.connect(name); - //connected = SerialBT.connect(address); - - if(connected) { - Serial.println("Connected Succesfully!"); - } else { - while(!SerialBT.connected(10000)) { - Serial.println("Failed to connect. Make sure remote device is available and in range, then restart app."); - } - } - // disconnect() may take upto 10 secs max - if (SerialBT.disconnect()) { - Serial.println("Disconnected Succesfully!"); - } - // this would reconnect to the name(will use address, if resolved) or address used with connect(name/address). - SerialBT.connect(); -} - -void loop() { - if (Serial.available()) { - SerialBT.write(Serial.read()); - } - if (SerialBT.available()) { - Serial.write(SerialBT.read()); - } - delay(20); -} diff --git a/libraries/BluetoothSerial/examples/bt_remove_paired_devices/.skip.esp32s2 b/libraries/BluetoothSerial/examples/bt_remove_paired_devices/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino b/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino deleted file mode 100755 index c316a73b..00000000 --- a/libraries/BluetoothSerial/examples/bt_remove_paired_devices/bt_remove_paired_devices.ino +++ /dev/null @@ -1,87 +0,0 @@ -//This example code is in the Public Domain (or CC0 licensed, at your option.) -//By Victor Tchistiak - 2019 -// -//This example demonstrates reading and removing paired devices stored on the ESP32 flash memory -//Sometimes you may find your ESP32 device could not connect to the remote device despite -//many successful connections earlier. This is most likely a result of client replacing your paired -//device info with new one from other device. The BT clients store connection info for paired devices, -//but it is limited to a few devices only. When new device pairs and number of stored devices is exceeded, -//one of the previously paired devices would be replaced with new one. -//The only remedy is to delete this saved bound device from your device flash memory -//and pair with the other device again. -// -#include "esp_bt_main.h" -#include "esp_bt_device.h" -#include"esp_gap_bt_api.h" -#include "esp_err.h" - -#define REMOVE_BONDED_DEVICES 0 // <- Set to 0 to view all bonded devices addresses, set to 1 to remove - -#define PAIR_MAX_DEVICES 20 -uint8_t pairedDeviceBtAddr[PAIR_MAX_DEVICES][6]; -char bda_str[18]; - -bool initBluetooth() -{ - if(!btStart()) { - Serial.println("Failed to initialize controller"); - return false; - } - - if(esp_bluedroid_init() != ESP_OK) { - Serial.println("Failed to initialize bluedroid"); - return false; - } - - if(esp_bluedroid_enable() != ESP_OK) { - Serial.println("Failed to enable bluedroid"); - return false; - } - return true; -} - -char *bda2str(const uint8_t* bda, char *str, size_t size) -{ - if (bda == NULL || str == NULL || size < 18) { - return NULL; - } - sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", - bda[0], bda[1], bda[2], bda[3], bda[4], bda[5]); - return str; -} - -void setup() { - Serial.begin(115200); - - initBluetooth(); - Serial.print("ESP32 bluetooth address: "); Serial.println(bda2str(esp_bt_dev_get_address(), bda_str, 18)); - // Get the numbers of bonded/paired devices in the BT module - int count = esp_bt_gap_get_bond_device_num(); - if(!count) { - Serial.println("No bonded device found."); - } else { - Serial.print("Bonded device count: "); Serial.println(count); - if(PAIR_MAX_DEVICES < count) { - count = PAIR_MAX_DEVICES; - Serial.print("Reset bonded device count: "); Serial.println(count); - } - esp_err_t tError = esp_bt_gap_get_bond_device_list(&count, pairedDeviceBtAddr); - if(ESP_OK == tError) { - for(int i = 0; i < count; i++) { - Serial.print("Found bonded device # "); Serial.print(i); Serial.print(" -> "); - Serial.println(bda2str(pairedDeviceBtAddr[i], bda_str, 18)); - if(REMOVE_BONDED_DEVICES) { - esp_err_t tError = esp_bt_gap_remove_bond_device(pairedDeviceBtAddr[i]); - if(ESP_OK == tError) { - Serial.print("Removed bonded device # "); - } else { - Serial.print("Failed to remove bonded device # "); - } - Serial.println(i); - } - } - } - } -} - -void loop() {} diff --git a/libraries/BluetoothSerial/keywords.txt b/libraries/BluetoothSerial/keywords.txt deleted file mode 100644 index 563e35d7..00000000 --- a/libraries/BluetoothSerial/keywords.txt +++ /dev/null @@ -1,26 +0,0 @@ -####################################### -# Syntax Coloring Map For BluetoothSerial -####################################### - -####################################### -# Library (KEYWORD3) -####################################### - -BluetoothSerial KEYWORD3 - -####################################### -# Datatypes (KEYWORD1) -####################################### - -BluetoothSerial KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -SerialBT KEYWORD2 -hasClient KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/libraries/BluetoothSerial/library.properties b/libraries/BluetoothSerial/library.properties deleted file mode 100644 index 20adb66c..00000000 --- a/libraries/BluetoothSerial/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=BluetoothSerial -version=1.0 -author=Evandro Copercini -maintainer=Evandro Copercini -sentence=Simple UART to Classical Bluetooth bridge for ESP32 -paragraph= -category=Communication -url= -architectures=esp32 diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.cpp b/libraries/BluetoothSerial/src/BluetoothSerial.cpp deleted file mode 100755 index eb522e46..00000000 --- a/libraries/BluetoothSerial/src/BluetoothSerial.cpp +++ /dev/null @@ -1,823 +0,0 @@ -// Copyright 2018 Evandro Luis Copercini -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "sdkconfig.h" -#include -#include -#include -#include -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" - - -#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) - -#ifdef ARDUINO_ARCH_ESP32 -#include "esp32-hal-log.h" -#endif - -#include "BluetoothSerial.h" - -#include "esp_bt.h" -#include "esp_bt_main.h" -#include "esp_gap_bt_api.h" -#include "esp_bt_device.h" -#include "esp_spp_api.h" -#include - -#include "esp32-hal-log.h" - -const char * _spp_server_name = "ESP32SPP"; - -#define RX_QUEUE_SIZE 512 -#define TX_QUEUE_SIZE 32 -static uint32_t _spp_client = 0; -static xQueueHandle _spp_rx_queue = NULL; -static xQueueHandle _spp_tx_queue = NULL; -static SemaphoreHandle_t _spp_tx_done = NULL; -static TaskHandle_t _spp_task_handle = NULL; -static EventGroupHandle_t _spp_event_group = NULL; -static boolean secondConnectionAttempt; -static esp_spp_cb_t * custom_spp_callback = NULL; -static BluetoothSerialDataCb custom_data_callback = NULL; - -#define INQ_LEN 0x10 -#define INQ_NUM_RSPS 20 -#define READY_TIMEOUT (10 * 1000) -#define SCAN_TIMEOUT (INQ_LEN * 2 * 1000) -static esp_bd_addr_t _peer_bd_addr; -static char _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; -static bool _isRemoteAddressSet; -static bool _isMaster; -static esp_bt_pin_code_t _pin_code; -static int _pin_len; -static bool _isPinSet; -static bool _enableSSP; - -#define SPP_RUNNING 0x01 -#define SPP_CONNECTED 0x02 -#define SPP_CONGESTED 0x04 -#define SPP_DISCONNECTED 0x08 - -typedef struct { - size_t len; - uint8_t data[]; -} spp_packet_t; - -#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) -static char *bda2str(esp_bd_addr_t bda, char *str, size_t size) -{ - if (bda == NULL || str == NULL || size < 18) { - return NULL; - } - - uint8_t *p = bda; - sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x", - p[0], p[1], p[2], p[3], p[4], p[5]); - return str; -} -#endif - -static bool get_name_from_eir(uint8_t *eir, char *bdname, uint8_t *bdname_len) -{ - if (!eir || !bdname || !bdname_len) { - return false; - } - - uint8_t *rmt_bdname, rmt_bdname_len; - *bdname = *bdname_len = rmt_bdname_len = 0; - - rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_CMPL_LOCAL_NAME, &rmt_bdname_len); - if (!rmt_bdname) { - rmt_bdname = esp_bt_gap_resolve_eir_data(eir, ESP_BT_EIR_TYPE_SHORT_LOCAL_NAME, &rmt_bdname_len); - } - if (rmt_bdname) { - rmt_bdname_len = rmt_bdname_len > ESP_BT_GAP_MAX_BDNAME_LEN ? ESP_BT_GAP_MAX_BDNAME_LEN : rmt_bdname_len; - memcpy(bdname, rmt_bdname, rmt_bdname_len); - bdname[rmt_bdname_len] = 0; - *bdname_len = rmt_bdname_len; - return true; - } - return false; -} - -static bool btSetPin() { - esp_bt_pin_type_t pin_type; - if (_isPinSet) { - if (_pin_len) { - log_i("pin set"); - pin_type = ESP_BT_PIN_TYPE_FIXED; - } else { - _isPinSet = false; - log_i("pin reset"); - pin_type = ESP_BT_PIN_TYPE_VARIABLE; // pin_code would be ignored (default) - } - return (esp_bt_gap_set_pin(pin_type, _pin_len, _pin_code) == ESP_OK); - } - return false; -} - -static esp_err_t _spp_queue_packet(uint8_t *data, size_t len){ - if(!data || !len){ - log_w("No data provided"); - return ESP_OK; - } - spp_packet_t * packet = (spp_packet_t*)malloc(sizeof(spp_packet_t) + len); - if(!packet){ - log_e("SPP TX Packet Malloc Failed!"); - return ESP_FAIL; - } - packet->len = len; - memcpy(packet->data, data, len); - if (xQueueSend(_spp_tx_queue, &packet, portMAX_DELAY) != pdPASS) { - log_e("SPP TX Queue Send Failed!"); - free(packet); - return ESP_FAIL; - } - return ESP_OK; -} - -const uint16_t SPP_TX_MAX = 330; -static uint8_t _spp_tx_buffer[SPP_TX_MAX]; -static uint16_t _spp_tx_buffer_len = 0; - -static bool _spp_send_buffer(){ - if((xEventGroupWaitBits(_spp_event_group, SPP_CONGESTED, pdFALSE, pdTRUE, portMAX_DELAY) & SPP_CONGESTED) != 0){ - esp_err_t err = esp_spp_write(_spp_client, _spp_tx_buffer_len, _spp_tx_buffer); - if(err != ESP_OK){ - log_e("SPP Write Failed! [0x%X]", err); - return false; - } - _spp_tx_buffer_len = 0; - if(xSemaphoreTake(_spp_tx_done, portMAX_DELAY) != pdTRUE){ - log_e("SPP Ack Failed!"); - return false; - } - return true; - } - return false; -} - -static void _spp_tx_task(void * arg){ - spp_packet_t *packet = NULL; - size_t len = 0, to_send = 0; - uint8_t * data = NULL; - for (;;) { - if(_spp_tx_queue && xQueueReceive(_spp_tx_queue, &packet, portMAX_DELAY) == pdTRUE && packet){ - if(packet->len <= (SPP_TX_MAX - _spp_tx_buffer_len)){ - memcpy(_spp_tx_buffer+_spp_tx_buffer_len, packet->data, packet->len); - _spp_tx_buffer_len+=packet->len; - free(packet); - packet = NULL; - if(SPP_TX_MAX == _spp_tx_buffer_len || uxQueueMessagesWaiting(_spp_tx_queue) == 0){ - _spp_send_buffer(); - } - } else { - len = packet->len; - data = packet->data; - to_send = SPP_TX_MAX - _spp_tx_buffer_len; - memcpy(_spp_tx_buffer+_spp_tx_buffer_len, data, to_send); - _spp_tx_buffer_len = SPP_TX_MAX; - data += to_send; - len -= to_send; - _spp_send_buffer(); - while(len >= SPP_TX_MAX){ - memcpy(_spp_tx_buffer, data, SPP_TX_MAX); - _spp_tx_buffer_len = SPP_TX_MAX; - data += SPP_TX_MAX; - len -= SPP_TX_MAX; - _spp_send_buffer(); - } - if(len){ - memcpy(_spp_tx_buffer, data, len); - _spp_tx_buffer_len += len; - if(uxQueueMessagesWaiting(_spp_tx_queue) == 0){ - _spp_send_buffer(); - } - } - free(packet); - packet = NULL; - } - } else { - log_e("Something went horribly wrong"); - } - } - vTaskDelete(NULL); - _spp_task_handle = NULL; -} - -static void esp_spp_cb(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) -{ - switch (event) - { - case ESP_SPP_INIT_EVT: - log_i("ESP_SPP_INIT_EVT"); -#ifdef ESP_IDF_VERSION_MAJOR - esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE); -#else - esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); -#endif - if (!_isMaster) { - log_i("ESP_SPP_INIT_EVT: slave: start"); - esp_spp_start_srv(ESP_SPP_SEC_NONE, ESP_SPP_ROLE_SLAVE, 0, _spp_server_name); - } - xEventGroupSetBits(_spp_event_group, SPP_RUNNING); - break; - - case ESP_SPP_SRV_OPEN_EVT://Server connection open - log_i("ESP_SPP_SRV_OPEN_EVT"); - if (!_spp_client){ - _spp_client = param->open.handle; - } else { - secondConnectionAttempt = true; - esp_spp_disconnect(param->open.handle); - } - xEventGroupClearBits(_spp_event_group, SPP_DISCONNECTED); - xEventGroupSetBits(_spp_event_group, SPP_CONNECTED); - break; - - case ESP_SPP_CLOSE_EVT://Client connection closed - log_i("ESP_SPP_CLOSE_EVT"); - if(secondConnectionAttempt) { - secondConnectionAttempt = false; - } else { - _spp_client = 0; - xEventGroupSetBits(_spp_event_group, SPP_DISCONNECTED); - } - xEventGroupClearBits(_spp_event_group, SPP_CONNECTED); - break; - - case ESP_SPP_CONG_EVT://connection congestion status changed - if(param->cong.cong){ - xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); - } else { - xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); - } - log_v("ESP_SPP_CONG_EVT: %s", param->cong.cong?"CONGESTED":"FREE"); - break; - - case ESP_SPP_WRITE_EVT://write operation completed - if(param->write.cong){ - xEventGroupClearBits(_spp_event_group, SPP_CONGESTED); - } - xSemaphoreGive(_spp_tx_done);//we can try to send another packet - log_v("ESP_SPP_WRITE_EVT: %u %s", param->write.len, param->write.cong?"CONGESTED":"FREE"); - break; - - case ESP_SPP_DATA_IND_EVT://connection received data - log_v("ESP_SPP_DATA_IND_EVT len=%d handle=%d", param->data_ind.len, param->data_ind.handle); - //esp_log_buffer_hex("",param->data_ind.data,param->data_ind.len); //for low level debug - //ets_printf("r:%u\n", param->data_ind.len); - - if(custom_data_callback){ - custom_data_callback(param->data_ind.data, param->data_ind.len); - } else if (_spp_rx_queue != NULL){ - for (int i = 0; i < param->data_ind.len; i++){ - if(xQueueSend(_spp_rx_queue, param->data_ind.data + i, (TickType_t)0) != pdTRUE){ - log_e("RX Full! Discarding %u bytes", param->data_ind.len - i); - break; - } - } - } - break; - - case ESP_SPP_DISCOVERY_COMP_EVT://discovery complete - log_i("ESP_SPP_DISCOVERY_COMP_EVT"); - if (param->disc_comp.status == ESP_SPP_SUCCESS) { - log_i("ESP_SPP_DISCOVERY_COMP_EVT: spp connect to remote"); - esp_spp_connect(ESP_SPP_SEC_AUTHENTICATE, ESP_SPP_ROLE_MASTER, param->disc_comp.scn[0], _peer_bd_addr); - } - break; - - case ESP_SPP_OPEN_EVT://Client connection open - log_i("ESP_SPP_OPEN_EVT"); - if (!_spp_client){ - _spp_client = param->open.handle; - } else { - secondConnectionAttempt = true; - esp_spp_disconnect(param->open.handle); - } - xEventGroupClearBits(_spp_event_group, SPP_DISCONNECTED); - xEventGroupSetBits(_spp_event_group, SPP_CONNECTED); - break; - - case ESP_SPP_START_EVT://server started - log_i("ESP_SPP_START_EVT"); - break; - - case ESP_SPP_CL_INIT_EVT://client initiated a connection - log_i("ESP_SPP_CL_INIT_EVT"); - break; - - default: - break; - } - if(custom_spp_callback)(*custom_spp_callback)(event, param); -} - -void BluetoothSerial::onData(BluetoothSerialDataCb cb){ - custom_data_callback = cb; -} - -static void esp_bt_gap_cb(esp_bt_gap_cb_event_t event, esp_bt_gap_cb_param_t *param) -{ - switch(event){ - case ESP_BT_GAP_DISC_RES_EVT: - log_i("ESP_BT_GAP_DISC_RES_EVT"); -#if (ARDUHAL_LOG_LEVEL >= ARDUHAL_LOG_LEVEL_INFO) - char bda_str[18]; - log_i("Scanned device: %s", bda2str(param->disc_res.bda, bda_str, 18)); -#endif - for (int i = 0; i < param->disc_res.num_prop; i++) { - uint8_t peer_bdname_len; - char peer_bdname[ESP_BT_GAP_MAX_BDNAME_LEN + 1]; - switch(param->disc_res.prop[i].type) { - case ESP_BT_GAP_DEV_PROP_EIR: - if (get_name_from_eir((uint8_t*)param->disc_res.prop[i].val, peer_bdname, &peer_bdname_len)) { - log_i("ESP_BT_GAP_DISC_RES_EVT : EIR : %s : %d", peer_bdname, peer_bdname_len); - if (strlen(_remote_name) == peer_bdname_len - && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { - log_v("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_EIR : %s", peer_bdname, peer_bdname_len); - _isRemoteAddressSet = true; - memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); - esp_bt_gap_cancel_discovery(); - esp_spp_start_discovery(_peer_bd_addr); - } - } - break; - - case ESP_BT_GAP_DEV_PROP_BDNAME: - peer_bdname_len = param->disc_res.prop[i].len; - memcpy(peer_bdname, param->disc_res.prop[i].val, peer_bdname_len); - peer_bdname_len--; // len includes 0 terminator - log_v("ESP_BT_GAP_DISC_RES_EVT : BDNAME : %s : %d", peer_bdname, peer_bdname_len); - if (strlen(_remote_name) == peer_bdname_len - && strncmp(peer_bdname, _remote_name, peer_bdname_len) == 0) { - log_i("ESP_BT_GAP_DISC_RES_EVT : SPP_START_DISCOVERY_BDNAME : %s", peer_bdname); - _isRemoteAddressSet = true; - memcpy(_peer_bd_addr, param->disc_res.bda, ESP_BD_ADDR_LEN); - esp_bt_gap_cancel_discovery(); - esp_spp_start_discovery(_peer_bd_addr); - } - break; - - case ESP_BT_GAP_DEV_PROP_COD: - log_d("ESP_BT_GAP_DEV_PROP_COD"); - break; - - case ESP_BT_GAP_DEV_PROP_RSSI: - log_d("ESP_BT_GAP_DEV_PROP_RSSI"); - break; - - default: - break; - } - if (_isRemoteAddressSet) - break; - } - break; - case ESP_BT_GAP_DISC_STATE_CHANGED_EVT: - log_i("ESP_BT_GAP_DISC_STATE_CHANGED_EVT"); - break; - - case ESP_BT_GAP_RMT_SRVCS_EVT: - log_i( "ESP_BT_GAP_RMT_SRVCS_EVT"); - break; - - case ESP_BT_GAP_RMT_SRVC_REC_EVT: - log_i("ESP_BT_GAP_RMT_SRVC_REC_EVT"); - break; - - case ESP_BT_GAP_AUTH_CMPL_EVT: - if (param->auth_cmpl.stat == ESP_BT_STATUS_SUCCESS) { - log_v("authentication success: %s", param->auth_cmpl.device_name); - } else { - log_e("authentication failed, status:%d", param->auth_cmpl.stat); - } - break; - - case ESP_BT_GAP_PIN_REQ_EVT: - // default pairing pins - log_i("ESP_BT_GAP_PIN_REQ_EVT min_16_digit:%d", param->pin_req.min_16_digit); - if (param->pin_req.min_16_digit) { - log_i("Input pin code: 0000 0000 0000 0000"); - esp_bt_pin_code_t pin_code; - memset(pin_code, '0', ESP_BT_PIN_CODE_LEN); - esp_bt_gap_pin_reply(param->pin_req.bda, true, 16, pin_code); - } else { - log_i("Input pin code: 1234"); - esp_bt_pin_code_t pin_code; - memcpy(pin_code, "1234", 4); - esp_bt_gap_pin_reply(param->pin_req.bda, true, 4, pin_code); - } - break; - - case ESP_BT_GAP_CFM_REQ_EVT: - log_i("ESP_BT_GAP_CFM_REQ_EVT Please compare the numeric value: %d", param->cfm_req.num_val); - esp_bt_gap_ssp_confirm_reply(param->cfm_req.bda, true); - break; - - case ESP_BT_GAP_KEY_NOTIF_EVT: - log_i("ESP_BT_GAP_KEY_NOTIF_EVT passkey:%d", param->key_notif.passkey); - break; - - case ESP_BT_GAP_KEY_REQ_EVT: - log_i("ESP_BT_GAP_KEY_REQ_EVT Please enter passkey!"); - break; - - default: - break; - } -} - -static bool _init_bt(const char *deviceName) -{ - if(!_spp_event_group){ - _spp_event_group = xEventGroupCreate(); - if(!_spp_event_group){ - log_e("SPP Event Group Create Failed!"); - return false; - } - xEventGroupClearBits(_spp_event_group, 0xFFFFFF); - xEventGroupSetBits(_spp_event_group, SPP_CONGESTED); - xEventGroupSetBits(_spp_event_group, SPP_DISCONNECTED); - } - if (_spp_rx_queue == NULL){ - _spp_rx_queue = xQueueCreate(RX_QUEUE_SIZE, sizeof(uint8_t)); //initialize the queue - if (_spp_rx_queue == NULL){ - log_e("RX Queue Create Failed"); - return false; - } - } - if (_spp_tx_queue == NULL){ - _spp_tx_queue = xQueueCreate(TX_QUEUE_SIZE, sizeof(spp_packet_t*)); //initialize the queue - if (_spp_tx_queue == NULL){ - log_e("TX Queue Create Failed"); - return false; - } - } - if(_spp_tx_done == NULL){ - _spp_tx_done = xSemaphoreCreateBinary(); - if (_spp_tx_done == NULL){ - log_e("TX Semaphore Create Failed"); - return false; - } - xSemaphoreTake(_spp_tx_done, 0); - } - - if(!_spp_task_handle){ - xTaskCreatePinnedToCore(_spp_tx_task, "spp_tx", 4096, NULL, 10, &_spp_task_handle, 0); - if(!_spp_task_handle){ - log_e("Network Event Task Start Failed!"); - return false; - } - } - - if (!btStarted() && !btStart()){ - log_e("initialize controller failed"); - return false; - } - - esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); - if (bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ - if (esp_bluedroid_init()) { - log_e("initialize bluedroid failed"); - return false; - } - } - - if (bt_state != ESP_BLUEDROID_STATUS_ENABLED){ - if (esp_bluedroid_enable()) { - log_e("enable bluedroid failed"); - return false; - } - } - - if (_isMaster && esp_bt_gap_register_callback(esp_bt_gap_cb) != ESP_OK) { - log_e("gap register failed"); - return false; - } - - if (esp_spp_register_callback(esp_spp_cb) != ESP_OK){ - log_e("spp register failed"); - return false; - } - - if (esp_spp_init(ESP_SPP_MODE_CB) != ESP_OK){ - log_e("spp init failed"); - return false; - } - - if (esp_bt_sleep_disable() != ESP_OK){ - log_e("esp_bt_sleep_disable failed"); - } - - log_i("device name set"); - esp_bt_dev_set_device_name(deviceName); - - if (_isPinSet) { - btSetPin(); - } - - if (_enableSSP) { - log_i("Simple Secure Pairing"); - esp_bt_sp_param_t param_type = ESP_BT_SP_IOCAP_MODE; - esp_bt_io_cap_t iocap = ESP_BT_IO_CAP_IO; - esp_bt_gap_set_security_param(param_type, &iocap, sizeof(uint8_t)); - } - - // the default BTA_DM_COD_LOUDSPEAKER does not work with the macOS BT stack - esp_bt_cod_t cod; - cod.major = 0b00001; - cod.minor = 0b000100; - cod.service = 0b00000010110; - if (esp_bt_gap_set_cod(cod, ESP_BT_INIT_COD) != ESP_OK) { - log_e("set cod failed"); - return false; - } - return true; -} - -static bool _stop_bt() -{ - if (btStarted()){ - if(_spp_client) - esp_spp_disconnect(_spp_client); - esp_spp_deinit(); - esp_bluedroid_disable(); - esp_bluedroid_deinit(); - btStop(); - } - _spp_client = 0; - if(_spp_task_handle){ - vTaskDelete(_spp_task_handle); - _spp_task_handle = NULL; - } - if(_spp_event_group){ - vEventGroupDelete(_spp_event_group); - _spp_event_group = NULL; - } - if(_spp_rx_queue){ - vQueueDelete(_spp_rx_queue); - //ToDo: clear RX queue when in packet mode - _spp_rx_queue = NULL; - } - if(_spp_tx_queue){ - spp_packet_t *packet = NULL; - while(xQueueReceive(_spp_tx_queue, &packet, 0) == pdTRUE){ - free(packet); - } - vQueueDelete(_spp_tx_queue); - _spp_tx_queue = NULL; - } - if (_spp_tx_done) { - vSemaphoreDelete(_spp_tx_done); - _spp_tx_done = NULL; - } - return true; -} - -static bool waitForConnect(int timeout) { - TickType_t xTicksToWait = timeout / portTICK_PERIOD_MS; - return (xEventGroupWaitBits(_spp_event_group, SPP_CONNECTED, pdFALSE, pdTRUE, xTicksToWait) & SPP_CONNECTED) != 0; -} - -/* - * Serial Bluetooth Arduino - * - * */ - -BluetoothSerial::BluetoothSerial() -{ - local_name = "ESP32"; //default bluetooth name -} - -BluetoothSerial::~BluetoothSerial(void) -{ - _stop_bt(); -} - -bool BluetoothSerial::begin(String localName, bool isMaster) -{ - _isMaster = isMaster; - if (localName.length()){ - local_name = localName; - } - return _init_bt(local_name.c_str()); -} - -int BluetoothSerial::available(void) -{ - if (_spp_rx_queue == NULL){ - return 0; - } - return uxQueueMessagesWaiting(_spp_rx_queue); -} - -int BluetoothSerial::peek(void) -{ - uint8_t c; - if (_spp_rx_queue && xQueuePeek(_spp_rx_queue, &c, 0)){ - return c; - } - return -1; -} - -bool BluetoothSerial::hasClient(void) -{ - return _spp_client > 0; -} - -int BluetoothSerial::read(void) -{ - - uint8_t c = 0; - if (_spp_rx_queue && xQueueReceive(_spp_rx_queue, &c, 0)){ - return c; - } - return -1; -} - -size_t BluetoothSerial::write(uint8_t c) -{ - return write(&c, 1); -} - -size_t BluetoothSerial::write(const uint8_t *buffer, size_t size) -{ - if (!_spp_client){ - return 0; - } - return (_spp_queue_packet((uint8_t *)buffer, size) == ESP_OK) ? size : 0; -} - -void BluetoothSerial::flush() -{ - if (_spp_tx_queue != NULL){ - while(uxQueueMessagesWaiting(_spp_tx_queue) > 0){ - delay(5); - } - } -} - -void BluetoothSerial::end() -{ - _stop_bt(); -} - -esp_err_t BluetoothSerial::register_callback(esp_spp_cb_t * callback) -{ - custom_spp_callback = callback; - return ESP_OK; -} - -//Simple Secure Pairing -void BluetoothSerial::enableSSP() { - _enableSSP = true; -} -/* - * Set default parameters for Legacy Pairing - * Use fixed pin code -*/ -bool BluetoothSerial::setPin(const char *pin) { - bool isEmpty = !(pin && *pin); - if (isEmpty && !_isPinSet) { - return true; // nothing to do - } else if (!isEmpty){ - _pin_len = strlen(pin); - memcpy(_pin_code, pin, _pin_len); - } else { - _pin_len = 0; // resetting pin to none (default) - } - _pin_code[_pin_len] = 0; - _isPinSet = true; - if (isReady(false, READY_TIMEOUT)) { - btSetPin(); - } - return true; -} - -bool BluetoothSerial::connect(String remoteName) -{ - if (!isReady(true, READY_TIMEOUT)) return false; - if (remoteName && remoteName.length() < 1) { - log_e("No remote name is provided"); - return false; - } - disconnect(); - _isRemoteAddressSet = false; - strncpy(_remote_name, remoteName.c_str(), ESP_BT_GAP_MAX_BDNAME_LEN); - _remote_name[ESP_BT_GAP_MAX_BDNAME_LEN] = 0; - log_i("master : remoteName"); - // will first resolve name to address -#ifdef ESP_IDF_VERSION_MAJOR - esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE); -#else - esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); -#endif - if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { - return waitForConnect(SCAN_TIMEOUT); - } - return false; -} - -bool BluetoothSerial::connect(uint8_t remoteAddress[]) -{ - if (!isReady(true, READY_TIMEOUT)) return false; - if (!remoteAddress) { - log_e("No remote address is provided"); - return false; - } - disconnect(); - _remote_name[0] = 0; - _isRemoteAddressSet = true; - memcpy(_peer_bd_addr, remoteAddress, ESP_BD_ADDR_LEN); - log_i("master : remoteAddress"); - if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { - return waitForConnect(READY_TIMEOUT); - } - return false; -} - -bool BluetoothSerial::connect() -{ - if (!isReady(true, READY_TIMEOUT)) return false; - if (_isRemoteAddressSet){ - disconnect(); - // use resolved or set address first - log_i("master : remoteAddress"); - if (esp_spp_start_discovery(_peer_bd_addr) == ESP_OK) { - return waitForConnect(READY_TIMEOUT); - } - return false; - } else if (_remote_name[0]) { - disconnect(); - log_i("master : remoteName"); - // will resolve name to address first - it may take a while -#ifdef ESP_IDF_VERSION_MAJOR - esp_bt_gap_set_scan_mode(ESP_BT_CONNECTABLE, ESP_BT_GENERAL_DISCOVERABLE); -#else - esp_bt_gap_set_scan_mode(ESP_BT_SCAN_MODE_CONNECTABLE_DISCOVERABLE); -#endif - if (esp_bt_gap_start_discovery(ESP_BT_INQ_MODE_GENERAL_INQUIRY, INQ_LEN, INQ_NUM_RSPS) == ESP_OK) { - return waitForConnect(SCAN_TIMEOUT); - } - return false; - } - log_e("Neither Remote name nor address was provided"); - return false; -} - -bool BluetoothSerial::disconnect() { - if (_spp_client) { - flush(); - log_i("disconnecting"); - if (esp_spp_disconnect(_spp_client) == ESP_OK) { - TickType_t xTicksToWait = READY_TIMEOUT / portTICK_PERIOD_MS; - return (xEventGroupWaitBits(_spp_event_group, SPP_DISCONNECTED, pdFALSE, pdTRUE, xTicksToWait) & SPP_DISCONNECTED) != 0; - } - } - return false; -} - -bool BluetoothSerial::unpairDevice(uint8_t remoteAddress[]) { - if (isReady(false, READY_TIMEOUT)) { - log_i("removing bonded device"); - return (esp_bt_gap_remove_bond_device(remoteAddress) == ESP_OK); - } - return false; -} - -bool BluetoothSerial::connected(int timeout) { - return waitForConnect(timeout); -} - -bool BluetoothSerial::isReady(bool checkMaster, int timeout) { - if (checkMaster && !_isMaster) { - log_e("Master mode is not active. Call begin(localName, true) to enable Master mode"); - return false; - } - if (!btStarted()) { - log_e("BT is not initialized. Call begin() first"); - return false; - } - TickType_t xTicksToWait = timeout / portTICK_PERIOD_MS; - return (xEventGroupWaitBits(_spp_event_group, SPP_RUNNING, pdFALSE, pdTRUE, xTicksToWait) & SPP_RUNNING) != 0; -} - -BluetoothSerial::operator bool() const -{ - return true; -} -#endif diff --git a/libraries/BluetoothSerial/src/BluetoothSerial.h b/libraries/BluetoothSerial/src/BluetoothSerial.h deleted file mode 100755 index 407b4456..00000000 --- a/libraries/BluetoothSerial/src/BluetoothSerial.h +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2018 Evandro Luis Copercini -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _BLUETOOTH_SERIAL_H_ -#define _BLUETOOTH_SERIAL_H_ - -#include "sdkconfig.h" - -#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) - -#include "Arduino.h" -#include "Stream.h" -#include -#include - -typedef std::function BluetoothSerialDataCb; - -class BluetoothSerial: public Stream -{ - public: - - BluetoothSerial(void); - ~BluetoothSerial(void); - - bool begin(String localName=String(), bool isMaster=false); - bool begin(unsigned long baud){//compatibility - return begin(); - } - int available(void); - int peek(void); - bool hasClient(void); - int read(void); - size_t write(uint8_t c); - size_t write(const uint8_t *buffer, size_t size); - void flush(); - void end(void); - void onData(BluetoothSerialDataCb cb); - esp_err_t register_callback(esp_spp_cb_t * callback); - - void enableSSP(); - bool setPin(const char *pin); - bool connect(String remoteName); - bool connect(uint8_t remoteAddress[]); - bool connect(); - bool connected(int timeout=0); - bool isReady(bool checkMaster=false, int timeout=0); - bool disconnect(); - bool unpairDevice(uint8_t remoteAddress[]); - - operator bool() const; - private: - String local_name; - -}; - -#endif - -#endif diff --git a/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino b/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino deleted file mode 100644 index 9221af1e..00000000 --- a/libraries/DNSServer/examples/CaptivePortal/CaptivePortal.ino +++ /dev/null @@ -1,52 +0,0 @@ -#include -#include - -const byte DNS_PORT = 53; -IPAddress apIP(8,8,4,4); // The default android DNS -DNSServer dnsServer; -WiFiServer server(80); - -String responseHTML = "" - "CaptivePortal" - "

Hello World!

This is a captive portal example. All requests will " - "be redirected here.

"; - -void setup() { - WiFi.mode(WIFI_AP); - WiFi.softAP("ESP32-DNSServer"); - WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); - - // if DNSServer is started with "*" for domain name, it will reply with - // provided IP to all DNS request - dnsServer.start(DNS_PORT, "*", apIP); - - server.begin(); -} - -void loop() { - dnsServer.processNextRequest(); - WiFiClient client = server.available(); // listen for incoming clients - - if (client) { - String currentLine = ""; - while (client.connected()) { - if (client.available()) { - char c = client.read(); - if (c == '\n') { - if (currentLine.length() == 0) { - client.println("HTTP/1.1 200 OK"); - client.println("Content-type:text/html"); - client.println(); - client.print(responseHTML); - break; - } else { - currentLine = ""; - } - } else if (c != '\r') { - currentLine += c; - } - } - } - client.stop(); - } -} diff --git a/libraries/DNSServer/library.properties b/libraries/DNSServer/library.properties deleted file mode 100644 index 8da8e6b3..00000000 --- a/libraries/DNSServer/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=DNSServer -version=1.1.0 -author=Kristijan Novoselić -maintainer=Kristijan Novoselić, -sentence=A simple DNS server for ESP32. -paragraph=This library implements a simple DNS server. -category=Communication -url= -architectures=esp32 diff --git a/libraries/DNSServer/src/DNSServer.cpp b/libraries/DNSServer/src/DNSServer.cpp deleted file mode 100644 index a7f0d15e..00000000 --- a/libraries/DNSServer/src/DNSServer.cpp +++ /dev/null @@ -1,210 +0,0 @@ -#include "DNSServer.h" -#include -#include - -// #define DEBUG_ESP_DNS -#ifdef DEBUG_ESP_PORT -#define DEBUG_OUTPUT DEBUG_ESP_PORT -#else -#define DEBUG_OUTPUT Serial -#endif - -DNSServer::DNSServer() -{ - _ttl = htonl(DNS_DEFAULT_TTL); - _errorReplyCode = DNSReplyCode::NonExistentDomain; - _dnsHeader = (DNSHeader*) malloc( sizeof(DNSHeader) ) ; - _dnsQuestion = (DNSQuestion*) malloc( sizeof(DNSQuestion) ) ; - _buffer = NULL; - _currentPacketSize = 0; - _port = 0; -} - -bool DNSServer::start(const uint16_t &port, const String &domainName, - const IPAddress &resolvedIP) -{ - _port = port; - _buffer = NULL; - _domainName = domainName; - _resolvedIP[0] = resolvedIP[0]; - _resolvedIP[1] = resolvedIP[1]; - _resolvedIP[2] = resolvedIP[2]; - _resolvedIP[3] = resolvedIP[3]; - downcaseAndRemoveWwwPrefix(_domainName); - return _udp.begin(_port) == 1; -} - -void DNSServer::setErrorReplyCode(const DNSReplyCode &replyCode) -{ - _errorReplyCode = replyCode; -} - -void DNSServer::setTTL(const uint32_t &ttl) -{ - _ttl = htonl(ttl); -} - -void DNSServer::stop() -{ - _udp.stop(); - free(_buffer); - _buffer = NULL; -} - -void DNSServer::downcaseAndRemoveWwwPrefix(String &domainName) -{ - domainName.toLowerCase(); - domainName.replace("www.", ""); -} - -void DNSServer::processNextRequest() -{ - _currentPacketSize = _udp.parsePacket(); - if (_currentPacketSize) - { - // Allocate buffer for the DNS query - if (_buffer != NULL) - free(_buffer); - _buffer = (unsigned char*)malloc(_currentPacketSize * sizeof(char)); - if (_buffer == NULL) - return; - - // Put the packet received in the buffer and get DNS header (beginning of message) - // and the question - _udp.read(_buffer, _currentPacketSize); - memcpy( _dnsHeader, _buffer, DNS_HEADER_SIZE ) ; - if ( requestIncludesOnlyOneQuestion() ) - { - // The QName has a variable length, maximum 255 bytes and is comprised of multiple labels. - // Each label contains a byte to describe its length and the label itself. The list of - // labels terminates with a zero-valued byte. In "github.com", we have two labels "github" & "com" - // Iterate through the labels and copy them as they come into a single buffer (for simplicity's sake) - _dnsQuestion->QNameLength = 0 ; - while ( _buffer[ DNS_HEADER_SIZE + _dnsQuestion->QNameLength ] != 0 ) - { - memcpy( (void*) &_dnsQuestion->QName[_dnsQuestion->QNameLength], (void*) &_buffer[DNS_HEADER_SIZE + _dnsQuestion->QNameLength], _buffer[DNS_HEADER_SIZE + _dnsQuestion->QNameLength] + 1 ) ; - _dnsQuestion->QNameLength += _buffer[DNS_HEADER_SIZE + _dnsQuestion->QNameLength] + 1 ; - } - _dnsQuestion->QName[_dnsQuestion->QNameLength] = 0 ; - _dnsQuestion->QNameLength++ ; - - // Copy the QType and QClass - memcpy( &_dnsQuestion->QType, (void*) &_buffer[DNS_HEADER_SIZE + _dnsQuestion->QNameLength], sizeof(_dnsQuestion->QType) ) ; - memcpy( &_dnsQuestion->QClass, (void*) &_buffer[DNS_HEADER_SIZE + _dnsQuestion->QNameLength + sizeof(_dnsQuestion->QType)], sizeof(_dnsQuestion->QClass) ) ; - } - - - if (_dnsHeader->QR == DNS_QR_QUERY && - _dnsHeader->OPCode == DNS_OPCODE_QUERY && - requestIncludesOnlyOneQuestion() && - (_domainName == "*" || getDomainNameWithoutWwwPrefix() == _domainName) - ) - { - replyWithIP(); - } - else if (_dnsHeader->QR == DNS_QR_QUERY) - { - replyWithCustomCode(); - } - - free(_buffer); - _buffer = NULL; - } -} - -bool DNSServer::requestIncludesOnlyOneQuestion() -{ - return ntohs(_dnsHeader->QDCount) == 1 && - _dnsHeader->ANCount == 0 && - _dnsHeader->NSCount == 0 && - _dnsHeader->ARCount == 0; -} - - -String DNSServer::getDomainNameWithoutWwwPrefix() -{ - // Error checking : if the buffer containing the DNS request is a null pointer, return an empty domain - String parsedDomainName = ""; - if (_buffer == NULL) - return parsedDomainName; - - // Set the start of the domain just after the header (12 bytes). If equal to null character, return an empty domain - unsigned char *start = _buffer + DNS_OFFSET_DOMAIN_NAME; - if (*start == 0) - { - return parsedDomainName; - } - - int pos = 0; - while(true) - { - unsigned char labelLength = *(start + pos); - for(int i = 0; i < labelLength; i++) - { - pos++; - parsedDomainName += (char)*(start + pos); - } - pos++; - if (*(start + pos) == 0) - { - downcaseAndRemoveWwwPrefix(parsedDomainName); - return parsedDomainName; - } - else - { - parsedDomainName += "."; - } - } -} - -void DNSServer::replyWithIP() -{ - if (_buffer == NULL) return; - - _udp.beginPacket(_udp.remoteIP(), _udp.remotePort()); - - // Change the type of message to a response and set the number of answers equal to - // the number of questions in the header - _dnsHeader->QR = DNS_QR_RESPONSE; - _dnsHeader->ANCount = _dnsHeader->QDCount; - _udp.write( (unsigned char*) _dnsHeader, DNS_HEADER_SIZE ) ; - - // Write the question - _udp.write(_dnsQuestion->QName, _dnsQuestion->QNameLength) ; - _udp.write( (unsigned char*) &_dnsQuestion->QType, 2 ) ; - _udp.write( (unsigned char*) &_dnsQuestion->QClass, 2 ) ; - - // Write the answer - // Use DNS name compression : instead of repeating the name in this RNAME occurence, - // set the two MSB of the byte corresponding normally to the length to 1. The following - // 14 bits must be used to specify the offset of the domain name in the message - // (<255 here so the first byte has the 6 LSB at 0) - _udp.write((uint8_t) 0xC0); - _udp.write((uint8_t) DNS_OFFSET_DOMAIN_NAME); - - // DNS type A : host address, DNS class IN for INternet, returning an IPv4 address - uint16_t answerType = htons(DNS_TYPE_A), answerClass = htons(DNS_CLASS_IN), answerIPv4 = htons(DNS_RDLENGTH_IPV4) ; - _udp.write((unsigned char*) &answerType, 2 ); - _udp.write((unsigned char*) &answerClass, 2 ); - _udp.write((unsigned char*) &_ttl, 4); // DNS Time To Live - _udp.write((unsigned char*) &answerIPv4, 2 ); - _udp.write(_resolvedIP, sizeof(_resolvedIP)); // The IP address to return - _udp.endPacket(); - - #ifdef DEBUG_ESP_DNS - DEBUG_OUTPUT.printf("DNS responds: %s for %s\n", - IPAddress(_resolvedIP).toString().c_str(), getDomainNameWithoutWwwPrefix().c_str() ); - #endif -} - -void DNSServer::replyWithCustomCode() -{ - if (_buffer == NULL) return; - _dnsHeader->QR = DNS_QR_RESPONSE; - _dnsHeader->RCode = (unsigned char)_errorReplyCode; - _dnsHeader->QDCount = 0; - - _udp.beginPacket(_udp.remoteIP(), _udp.remotePort()); - _udp.write(_buffer, sizeof(DNSHeader)); - _udp.endPacket(); -} diff --git a/libraries/DNSServer/src/DNSServer.h b/libraries/DNSServer/src/DNSServer.h deleted file mode 100644 index a10ef9ea..00000000 --- a/libraries/DNSServer/src/DNSServer.h +++ /dev/null @@ -1,109 +0,0 @@ -#ifndef DNSServer_h -#define DNSServer_h -#include - -#define DNS_QR_QUERY 0 -#define DNS_QR_RESPONSE 1 -#define DNS_OPCODE_QUERY 0 -#define DNS_DEFAULT_TTL 60 // Default Time To Live : time interval in seconds that the resource record should be cached before being discarded -#define DNS_OFFSET_DOMAIN_NAME 12 // Offset in bytes to reach the domain name in the DNS message -#define DNS_HEADER_SIZE 12 - -enum class DNSReplyCode -{ - NoError = 0, - FormError = 1, - ServerFailure = 2, - NonExistentDomain = 3, - NotImplemented = 4, - Refused = 5, - YXDomain = 6, - YXRRSet = 7, - NXRRSet = 8 -}; - -enum DNSType -{ - DNS_TYPE_A = 1, // Host Address - DNS_TYPE_AAAA = 28, // IPv6 Address - DNS_TYPE_SOA = 6, // Start Of a zone of Authority - DNS_TYPE_PTR = 12, // Domain name PoinTeR - DNS_TYPE_DNAME = 39 // Delegation Name -} ; - -enum DNSClass -{ - DNS_CLASS_IN = 1, // INternet - DNS_CLASS_CH = 3 // CHaos -} ; - -enum DNSRDLength -{ - DNS_RDLENGTH_IPV4 = 4 // 4 bytes for an IPv4 address -} ; - -struct DNSHeader -{ - uint16_t ID; // identification number - union { - struct { - uint16_t RD : 1; // recursion desired - uint16_t TC : 1; // truncated message - uint16_t AA : 1; // authoritive answer - uint16_t OPCode : 4; // message_type - uint16_t QR : 1; // query/response flag - uint16_t RCode : 4; // response code - uint16_t Z : 3; // its z! reserved - uint16_t RA : 1; // recursion available - }; - uint16_t Flags; - }; - uint16_t QDCount; // number of question entries - uint16_t ANCount; // number of answer entries - uint16_t NSCount; // number of authority entries - uint16_t ARCount; // number of resource entries -}; - -struct DNSQuestion -{ - uint8_t QName[255] ; - int8_t QNameLength ; - uint16_t QType ; - uint16_t QClass ; -} ; - -class DNSServer -{ - public: - DNSServer(); - void processNextRequest(); - void setErrorReplyCode(const DNSReplyCode &replyCode); - void setTTL(const uint32_t &ttl); - - // Returns true if successful, false if there are no sockets available - bool start(const uint16_t &port, - const String &domainName, - const IPAddress &resolvedIP); - // stops the DNS server - void stop(); - - private: - WiFiUDP _udp; - uint16_t _port; - String _domainName; - unsigned char _resolvedIP[4]; - int _currentPacketSize; - unsigned char* _buffer; - DNSHeader* _dnsHeader; - uint32_t _ttl; - DNSReplyCode _errorReplyCode; - DNSQuestion* _dnsQuestion ; - - - void downcaseAndRemoveWwwPrefix(String &domainName); - String getDomainNameWithoutWwwPrefix(); - bool requestIncludesOnlyOneQuestion(); - void replyWithIP(); - void replyWithCustomCode(); -}; -#endif \ No newline at end of file diff --git a/libraries/EEPROM/README.md b/libraries/EEPROM/README.md deleted file mode 100644 index 896ca5b3..00000000 --- a/libraries/EEPROM/README.md +++ /dev/null @@ -1,4 +0,0 @@ -## EEPROM - -EEPROM is deprecated. For new applications on ESP32, use Preferences. EEPROM is provided for backwards compatibility with existing Arduino applications. -EEPROM is implemented using a single blob within NVS, so it is a container within a container. As such, it is not going to be a high performance storage method. Preferences will directly use nvs, and store each entry as a single object therein. diff --git a/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino b/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino deleted file mode 100644 index 18a191c5..00000000 --- a/libraries/EEPROM/examples/eeprom_class/eeprom_class.ino +++ /dev/null @@ -1,77 +0,0 @@ -/* - ESP32 eeprom_class example with EEPROM library - This simple example demonstrates using EEPROM library to store different data in - ESP32 Flash memory in a multiple user-defined EEPROM class objects. - - Created for arduino-esp32 on 25 Dec, 2017 - by Elochukwu Ifediora (fedy0) - converted to nvs by lbernstone - 06/22/2019 -*/ - -#include "EEPROM.h" - -// Instantiate eeprom objects with parameter/argument names and sizes -EEPROMClass NAMES("eeprom0", 0x500); -EEPROMClass HEIGHT("eeprom1", 0x200); -EEPROMClass AGE("eeprom2", 0x100); - -void setup() { - Serial.begin(115200); - delay(1000); - Serial.println("Testing EEPROMClass\n"); - if (!NAMES.begin(NAMES.length())) { - Serial.println("Failed to initialise NAMES"); - Serial.println("Restarting..."); - delay(1000); - ESP.restart(); - } - if (!HEIGHT.begin(HEIGHT.length())) { - Serial.println("Failed to initialise HEIGHT"); - Serial.println("Restarting..."); - delay(1000); - ESP.restart(); - } - if (!AGE.begin(AGE.length())) { - Serial.println("Failed to initialise AGE"); - Serial.println("Restarting..."); - delay(1000); - ESP.restart(); - } - - const char* name = "Teo Swee Ann"; - char rname[32]; - double height = 5.8; - uint32_t age = 47; - - // Write: Variables ---> EEPROM stores - NAMES.writeString(0, name); - HEIGHT.put(0, height); - AGE.put(0, age); - Serial.print("name: "); Serial.println(name); - Serial.print("height: "); Serial.println(height); - Serial.print("age: "); Serial.println(age); - Serial.println("------------------------------------\n"); - - // Clear variables - rname[0] = '\0'; - height = 0; - age = 0; - Serial.print("name: "); Serial.println(rname); - Serial.print("height: "); Serial.println(height); - Serial.print("age: "); Serial.println(age); - Serial.println("------------------------------------\n"); - - // Read: Variables <--- EEPROM stores - NAMES.get(0, rname); - HEIGHT.get(0, height); - AGE.get(0, age); - Serial.print("name: "); Serial.println(rname); - Serial.print("height: "); Serial.println(height); - Serial.print("age: "); Serial.println(age); - - Serial.println("Done!"); -} - -void loop() { - delay(0xFFFFFFFF); -} diff --git a/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino b/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino deleted file mode 100644 index 5ae01fb2..00000000 --- a/libraries/EEPROM/examples/eeprom_extra/eeprom_extra.ino +++ /dev/null @@ -1,139 +0,0 @@ -/* - ESP32 eeprom_extra example with EEPROM library - - This simple example demonstrates using other EEPROM library resources - - Created for arduino-esp32 on 25 Dec, 2017 - by Elochukwu Ifediora (fedy0) -*/ - -#include "EEPROM.h" - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\nTesting EEPROM Library\n"); - if (!EEPROM.begin(1000)) { - Serial.println("Failed to initialise EEPROM"); - Serial.println("Restarting..."); - delay(1000); - ESP.restart(); - } - - int address = 0; - - EEPROM.writeByte(address, -128); // -2^7 - address += sizeof(byte); - - EEPROM.writeChar(address, 'A'); // Same as writyByte and readByte - address += sizeof(char); - - EEPROM.writeUChar(address, 255); // 2^8 - 1 - address += sizeof(unsigned char); - - EEPROM.writeShort(address, -32768); // -2^15 - address += sizeof(short); - - EEPROM.writeUShort(address, 65535); // 2^16 - 1 - address += sizeof(unsigned short); - - EEPROM.writeInt(address, -2147483648); // -2^31 - address += sizeof(int); - - EEPROM.writeUInt(address, 4294967295); // 2^32 - 1 - address += sizeof(unsigned int); - - EEPROM.writeLong(address, -2147483648); // Same as writeInt and readInt - address += sizeof(long); - - EEPROM.writeULong(address, 4294967295); // Same as writeUInt and readUInt - address += sizeof(unsigned long); - - int64_t value = -1223372036854775808LL; // -2^63 - EEPROM.writeLong64(address, value); - address += sizeof(int64_t); - - uint64_t Value = 18446744073709551615ULL; // 2^64 - 1 - EEPROM.writeULong64(address, Value); - address += sizeof(uint64_t); - - EEPROM.writeFloat(address, 1234.1234); - address += sizeof(float); - - EEPROM.writeDouble(address, 123456789.123456789); - address += sizeof(double); - - EEPROM.writeBool(address, true); - address += sizeof(bool); - - String sentence = "I love ESP32."; - EEPROM.writeString(address, sentence); - address += sentence.length() + 1; - - char gratitude[21] = "Thank You Espressif!"; - EEPROM.writeString(address, gratitude); - address += 21; - - // See also the general purpose writeBytes() and readBytes() for BLOB in EEPROM library - EEPROM.commit(); - address = 0; - - Serial.println(EEPROM.readByte(address)); - address += sizeof(byte); - - Serial.println((char)EEPROM.readChar(address)); - address += sizeof(char); - - Serial.println(EEPROM.readUChar(address)); - address += sizeof(unsigned char); - - Serial.println(EEPROM.readShort(address)); - address += sizeof(short); - - Serial.println(EEPROM.readUShort(address)); - address += sizeof(unsigned short); - - Serial.println(EEPROM.readInt(address)); - address += sizeof(int); - - Serial.println(EEPROM.readUInt(address)); - address += sizeof(unsigned int); - - Serial.println(EEPROM.readLong(address)); - address += sizeof(long); - - Serial.println(EEPROM.readULong(address)); - address += sizeof(unsigned long); - - value = 0; - value = EEPROM.readLong64(value); - Serial.printf("0x%08X", (uint32_t)(value >> 32)); // Print High 4 bytes in HEX - Serial.printf("%08X\n", (uint32_t)value); // Print Low 4 bytes in HEX - address += sizeof(int64_t); - - Value = 0; // Clear Value - Value = EEPROM.readULong64(Value); - Serial.printf("0x%08X", (uint32_t)(Value >> 32)); // Print High 4 bytes in HEX - Serial.printf("%08X\n", (uint32_t)Value); // Print Low 4 bytes in HEX - address += sizeof(uint64_t); - - Serial.println(EEPROM.readFloat(address), 4); - address += sizeof(float); - - Serial.println(EEPROM.readDouble(address), 8); - address += sizeof(double); - - Serial.println(EEPROM.readBool(address)); - address += sizeof(bool); - - Serial.println(EEPROM.readString(address)); - address += sentence.length() + 1; - - Serial.println(EEPROM.readString(address)); - address += 21; -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino b/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino deleted file mode 100644 index a4dbb8c3..00000000 --- a/libraries/EEPROM/examples/eeprom_write/eeprom_write.ino +++ /dev/null @@ -1,63 +0,0 @@ -/* - EEPROM Write - - Stores random values into the EEPROM. - These values will stay in the EEPROM when the board is - turned off and may be retrieved later by another sketch. -*/ - -#include "EEPROM.h" - -// the current address in the EEPROM (i.e. which byte -// we're going to write to next) -int addr = 0; -#define EEPROM_SIZE 64 -void setup() -{ - Serial.begin(115200); - Serial.println("start..."); - if (!EEPROM.begin(EEPROM_SIZE)) - { - Serial.println("failed to initialise EEPROM"); delay(1000000); - } - Serial.println(" bytes read from Flash . Values are:"); - for (int i = 0; i < EEPROM_SIZE; i++) - { - Serial.print(byte(EEPROM.read(i))); Serial.print(" "); - } - Serial.println(); - Serial.println("writing random n. in memory"); -} - -void loop() -{ - // need to divide by 4 because analog inputs range from - // 0 to 1023 and each byte of the EEPROM can only hold a - // value from 0 to 255. - // int val = analogRead(10) / 4; - int val = byte(random(10020)); - // write the value to the appropriate byte of the EEPROM. - // these values will remain there when the board is - // turned off. - EEPROM.write(addr, val); - Serial.print(val); Serial.print(" "); - // advance to the next address. there are 512 bytes in - // the EEPROM, so go back to 0 when we hit 512. - // save all changes to the flash. - addr = addr + 1; - if (addr == EEPROM_SIZE) - { - Serial.println(); - addr = 0; - EEPROM.commit(); - Serial.print(EEPROM_SIZE); - Serial.println(" bytes written on Flash . Values are:"); - for (int i = 0; i < EEPROM_SIZE; i++) - { - Serial.print(byte(EEPROM.read(i))); Serial.print(" "); - } - Serial.println(); Serial.println("----------------------------------"); - } - - delay(100); -} diff --git a/libraries/EEPROM/keywords.txt b/libraries/EEPROM/keywords.txt deleted file mode 100644 index 0e2552e1..00000000 --- a/libraries/EEPROM/keywords.txt +++ /dev/null @@ -1,19 +0,0 @@ -####################################### -# Syntax Coloring Map For Ultrasound -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -EEPROM KEYWORD1 -EEPROMClass KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/EEPROM/library.properties b/libraries/EEPROM/library.properties deleted file mode 100644 index e6552058..00000000 --- a/libraries/EEPROM/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=EEPROM -version=1.0.3 -author=Ivan Grokhotkov -maintainer=Paolo Becchi -sentence=Enables reading and writing data a sequential, addressable FLASH storage -paragraph= -category=Data Storage -url=http://arduino.cc/en/Reference/EEPROM -architectures=esp32 diff --git a/libraries/EEPROM/src/EEPROM.cpp b/libraries/EEPROM/src/EEPROM.cpp deleted file mode 100644 index 7f4ab090..00000000 --- a/libraries/EEPROM/src/EEPROM.cpp +++ /dev/null @@ -1,557 +0,0 @@ -/* - EEPROM.h -ported by Paolo Becchi to Esp32 from esp8266 EEPROM - -Modified by Elochukwu Ifediora - -Converted to nvs lbernstone@gmail.com - - Uses a nvs byte array to emulate EEPROM - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "EEPROM.h" -#include -#include -#include - -EEPROMClass::EEPROMClass(void) - : _handle(0) - , _data(0) - , _size(0) - , _dirty(false) - , _name("eeprom") - , _user_defined_size(0) -{ -} - -EEPROMClass::EEPROMClass(uint32_t sector) -// Only for compatiility, no sectors in nvs! - : _handle(0) - , _data(0) - , _size(0) - , _dirty(false) - , _name("eeprom") - , _user_defined_size(0) -{ -} - -EEPROMClass::EEPROMClass(const char* name, uint32_t user_defined_size) - : _handle(0) - , _data(0) - , _size(0) - , _dirty(false) - , _name(name) - , _user_defined_size(user_defined_size) -{ -} - -EEPROMClass::~EEPROMClass() { - end(); -} - -bool EEPROMClass::begin(size_t size) { - if (!size) { - return false; - } - - esp_err_t res = nvs_open(_name, NVS_READWRITE, &_handle); - if (res != ESP_OK) { - log_e("Unable to open NVS namespace: %d", res); - return false; - } - - size_t key_size = 0; - res = nvs_get_blob(_handle, _name, NULL, &key_size); - if(res != ESP_OK && res != ESP_ERR_NVS_NOT_FOUND) { - log_e("Unable to read NVS key: %d", res); - return false; - } - if (size < key_size) { // truncate - log_w("truncating EEPROM from %d to %d", key_size, size); - uint8_t* key_data = (uint8_t*) malloc(key_size); - if(!key_data) { - log_e("Not enough memory to truncate EEPROM!"); - return false; - } - nvs_get_blob(_handle, _name, key_data, &key_size); - nvs_set_blob(_handle, _name, key_data, size); - nvs_commit(_handle); - free(key_data); - } - else if (size > key_size) { // expand or new - size_t expand_size = size - key_size; - uint8_t* expand_key = (uint8_t*) malloc(expand_size); - if(!expand_key) { - log_e("Not enough memory to expand EEPROM!"); - return false; - } - // check for adequate free space - if(nvs_set_blob(_handle, "expand", expand_key, expand_size)) { - log_e("Not enough space to expand EEPROM from %d to %d", key_size, size); - free(expand_key); - return false; - } - free(expand_key); - nvs_erase_key(_handle, "expand"); - uint8_t* key_data = (uint8_t*) malloc(size); - if(!key_data) { - log_e("Not enough memory to expand EEPROM!"); - return false; - } - memset(key_data, 0xFF, size); - if(key_size) { - log_i("Expanding EEPROM from %d to %d", key_size, size); - // hold data while key is deleted - nvs_get_blob(_handle, _name, key_data, &key_size); - nvs_erase_key(_handle, _name); - } else { - log_i("New EEPROM of %d bytes", size); - } - nvs_commit(_handle); - nvs_set_blob(_handle, _name, key_data, size); - free(key_data); - nvs_commit(_handle); - } - - if (_data) { - delete[] _data; - } - - _data = (uint8_t*) malloc(size); - if(!_data) { - log_e("Not enough memory for %d bytes in EEPROM"); - return false; - } - _size = size; - nvs_get_blob(_handle, _name, _data, &_size); - return true; -} - -void EEPROMClass::end() { - if (!_size) { - return; - } - - commit(); - if (_data) { - delete[] _data; - } - _data = 0; - _size = 0; - - nvs_close(_handle); - _handle = 0; -} - -uint8_t EEPROMClass::read(int address) { - if (address < 0 || (size_t)address >= _size) { - return 0; - } - if (!_data) { - return 0; - } - - return _data[address]; -} - -void EEPROMClass::write(int address, uint8_t value) { - if (address < 0 || (size_t)address >= _size) - return; - if (!_data) - return; - - // Optimise _dirty. Only flagged if data written is different. - uint8_t* pData = &_data[address]; - if (*pData != value) - { - *pData = value; - _dirty = true; - } -} - -bool EEPROMClass::commit() { - bool ret = false; - if (!_size) { - return false; - } - if (!_data) { - return false; - } - if (!_dirty) { - return true; - } - - if (ESP_OK != nvs_set_blob(_handle, _name, _data, _size)) { - log_e( "error in write"); - } else { - _dirty = false; - ret = true; - } - - return ret; -} - -uint8_t * EEPROMClass::getDataPtr() { - _dirty = true; - return &_data[0]; -} - -/* - Get EEPROM total size in byte defined by the user -*/ -uint16_t EEPROMClass::length () -{ - return _user_defined_size; -} - -/* - Convert EEPROM partition into nvs blob - Call convert before you call begin -*/ -uint16_t EEPROMClass::convert (bool clear, const char* EEPROMname, const char* nvsname) -{ - uint16_t result = 0; - const esp_partition_t* mypart = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_ANY, EEPROMname); - if (mypart == NULL) { - log_i("EEPROM partition not found for conversion"); - return result; - } - - size_t size = mypart->size; - uint8_t* data = (uint8_t*) malloc(size); - if (!data) { - log_e("Not enough memory to convert EEPROM!"); - goto exit; - } - - if (esp_partition_read (mypart, 0, (void *) data, size) != ESP_OK) { - log_e("Unable to read EEPROM partition"); - goto exit; - } - - bool empty; - empty = true; - for (int x=0; x _size) - return 0; - - uint16_t len; - for (len = 0; len <= _size; len++) - if (_data[address + len] == 0) - break; - - if (address + len > _size) - return 0; - - memcpy((uint8_t*) value, _data + address, len); - value[len] = 0; - return len; -} - -String EEPROMClass::readString (int address) -{ - if (address < 0 || address > _size) - return String(); - - uint16_t len; - for (len = 0; len <= _size; len++) - if (_data[address + len] == 0) - break; - - if (address + len > _size) - return String(); - - char value[len]; - memcpy((uint8_t*) value, _data + address, len); - value[len] = 0; - return String(value); -} - -size_t EEPROMClass::readBytes (int address, void* value, size_t maxLen) -{ - if (!value || !maxLen) - return 0; - - if (address < 0 || address + maxLen > _size) - return 0; - - memcpy((void*) value, _data + address, maxLen); - return maxLen; -} - -template T EEPROMClass::readAll (int address, T &value) -{ - if (address < 0 || address + sizeof(T) > _size) - return value; - - memcpy((uint8_t*) &value, _data + address, sizeof(T)); - return value; -} - -/* - Write 'value' to 'address' -*/ -size_t EEPROMClass::writeByte (int address, uint8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeChar (int address, int8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUChar (int address, uint8_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeShort (int address, int16_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUShort (int address, uint16_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeInt (int address, int32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeUInt (int address, uint32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeLong (int address, int32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeULong (int address, uint32_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeLong64 (int address, int64_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeULong64 (int address, uint64_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeFloat (int address, float_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeDouble (int address, double_t value) -{ - return EEPROMClass::writeAll (address, value); -} - -size_t EEPROMClass::writeBool (int address, bool value) -{ - int8_t Bool; - value ? Bool = 1 : Bool = 0; - return EEPROMClass::writeAll (address, Bool); -} - -size_t EEPROMClass::writeString (int address, const char* value) -{ - if (!value) - return 0; - - if (address < 0 || address > _size) - return 0; - - uint16_t len; - for (len = 0; len <= _size; len++) - if (value[len] == 0) - break; - - if (address + len > _size) - return 0; - - memcpy(_data + address, (const uint8_t*) value, len + 1); - _dirty = true; - return strlen(value); -} - -size_t EEPROMClass::writeString (int address, String value) -{ - return EEPROMClass::writeString (address, value.c_str()); -} - -size_t EEPROMClass::writeBytes (int address, const void* value, size_t len) -{ - if (!value || !len) - return 0; - - if (address < 0 || address + len > _size) - return 0; - - memcpy(_data + address, (const void*) value, len); - _dirty = true; - return len; -} - -template T EEPROMClass::writeAll (int address, const T &value) -{ - if (address < 0 || address + sizeof(T) > _size) - return value; - - memcpy(_data + address, (const uint8_t*) &value, sizeof(T)); - _dirty = true; - - return sizeof (value); -} - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) -EEPROMClass EEPROM; -#endif diff --git a/libraries/EEPROM/src/EEPROM.h b/libraries/EEPROM/src/EEPROM.h deleted file mode 100644 index 032e1f65..00000000 --- a/libraries/EEPROM/src/EEPROM.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - EEPROM.h -ported by Paolo Becchi to Esp32 from esp8266 EEPROM - -Modified by Elochukwu Ifediora - -Converted to nvs lbernstone@gmail.com - - Uses a nvs byte array to emulate EEPROM - - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - This file is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef EEPROM_h -#define EEPROM_h -#ifndef EEPROM_FLASH_PARTITION_NAME -#define EEPROM_FLASH_PARTITION_NAME "eeprom" -#endif -#include - -typedef uint32_t nvs_handle; - -class EEPROMClass { - public: - EEPROMClass(uint32_t sector); - EEPROMClass(const char* name, uint32_t user_defined_size); - EEPROMClass(void); - ~EEPROMClass(void); - - bool begin(size_t size); - uint8_t read(int address); - void write(int address, uint8_t val); - uint16_t length(); - bool commit(); - void end(); - - uint8_t * getDataPtr(); - uint16_t convert(bool clear, const char* EEPROMname = "eeprom", const char* nvsname = "eeprom"); - - template - T &get(int address, T &t) { - if (address < 0 || address + sizeof(T) > _size) - return t; - - memcpy((uint8_t*) &t, _data + address, sizeof(T)); - return t; - } - - template - const T &put(int address, const T &t) { - if (address < 0 || address + sizeof(T) > _size) - return t; - - memcpy(_data + address, (const uint8_t*) &t, sizeof(T)); - _dirty = true; - return t; - } - - uint8_t readByte(int address); - int8_t readChar(int address); - uint8_t readUChar(int address); - int16_t readShort(int address); - uint16_t readUShort(int address); - int32_t readInt(int address); - uint32_t readUInt(int address); - int32_t readLong(int address); - uint32_t readULong(int address); - int64_t readLong64(int address); - uint64_t readULong64(int address); - float_t readFloat(int address); - double_t readDouble(int address); - bool readBool(int address); - size_t readString(int address, char* value, size_t maxLen); - String readString(int address); - size_t readBytes(int address, void * value, size_t maxLen); - template T readAll (int address, T &); - - size_t writeByte(int address, uint8_t value); - size_t writeChar(int address, int8_t value); - size_t writeUChar(int address, uint8_t value); - size_t writeShort(int address, int16_t value); - size_t writeUShort(int address, uint16_t value); - size_t writeInt(int address, int32_t value); - size_t writeUInt(int address, uint32_t value); - size_t writeLong(int address, int32_t value); - size_t writeULong(int address, uint32_t value); - size_t writeLong64(int address, int64_t value); - size_t writeULong64(int address, uint64_t value); - size_t writeFloat(int address, float_t value); - size_t writeDouble(int address, double_t value); - size_t writeBool(int address, bool value); - size_t writeString(int address, const char* value); - size_t writeString(int address, String value); - size_t writeBytes(int address, const void* value, size_t len); - template T writeAll (int address, const T &); - - protected: - nvs_handle _handle; - uint8_t* _data; - size_t _size; - bool _dirty; - const char* _name; - uint32_t _user_defined_size; -}; - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_EEPROM) -extern EEPROMClass EEPROM; -#endif - -#endif diff --git a/libraries/ESPmDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino b/libraries/ESPmDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino deleted file mode 100644 index 6f2dfddf..00000000 --- a/libraries/ESPmDNS/examples/mDNS-SD_Extended/mDNS-SD_Extended.ino +++ /dev/null @@ -1,80 +0,0 @@ -/* - ESP8266 mDNS-SD responder and query sample - - This is an example of announcing and finding services. - - Instructions: - - Update WiFi SSID and password as necessary. - - Flash the sketch to two ESP8266 boards - - The last one powered on should now find the other. - */ - -#include -#include - -const char* ssid = "..."; -const char* password = "..."; - -void setup() { - Serial.begin(115200); - WiFi.begin(ssid, password); - while (WiFi.status() != WL_CONNECTED) { - delay(250); - Serial.print("."); - } - Serial.println(""); - Serial.print("Connected to "); - Serial.println(ssid); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - if (!MDNS.begin("ESP32_Browser")) { - Serial.println("Error setting up MDNS responder!"); - while(1){ - delay(1000); - } - } -} - -void loop() { - browseService("http", "tcp"); - delay(1000); - browseService("arduino", "tcp"); - delay(1000); - browseService("workstation", "tcp"); - delay(1000); - browseService("smb", "tcp"); - delay(1000); - browseService("afpovertcp", "tcp"); - delay(1000); - browseService("ftp", "tcp"); - delay(1000); - browseService("ipp", "tcp"); - delay(1000); - browseService("printer", "tcp"); - delay(10000); -} - -void browseService(const char * service, const char * proto){ - Serial.printf("Browsing for service _%s._%s.local. ... ", service, proto); - int n = MDNS.queryService(service, proto); - if (n == 0) { - Serial.println("no services found"); - } else { - Serial.print(n); - Serial.println(" service(s) found"); - for (int i = 0; i < n; ++i) { - // Print details for each service found - Serial.print(" "); - Serial.print(i + 1); - Serial.print(": "); - Serial.print(MDNS.hostname(i)); - Serial.print(" ("); - Serial.print(MDNS.IP(i)); - Serial.print(":"); - Serial.print(MDNS.port(i)); - Serial.println(")"); - } - } - Serial.println(); -} diff --git a/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino b/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino deleted file mode 100644 index 946f51aa..00000000 --- a/libraries/ESPmDNS/examples/mDNS_Web_Server/mDNS_Web_Server.ino +++ /dev/null @@ -1,120 +0,0 @@ -/* - ESP32 mDNS responder sample - - This is an example of an HTTP server that is accessible - via http://esp32.local URL thanks to mDNS responder. - - Instructions: - - Update WiFi SSID and password as necessary. - - Flash the sketch to the ESP32 board - - Install host software: - - For Linux, install Avahi (http://avahi.org/). - - For Windows, install Bonjour (http://www.apple.com/support/bonjour/). - - For Mac OSX and iOS support is built in through Bonjour already. - - Point your browser to http://esp32.local, you should see a response. - - */ - - -#include -#include -#include - -const char* ssid = "............"; -const char* password = ".............."; - -// TCP server at port 80 will respond to HTTP requests -WiFiServer server(80); - -void setup(void) -{ - Serial.begin(115200); - - // Connect to WiFi network - WiFi.begin(ssid, password); - Serial.println(""); - - // Wait for connection - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println(""); - Serial.print("Connected to "); - Serial.println(ssid); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - // Set up mDNS responder: - // - first argument is the domain name, in this example - // the fully-qualified domain name is "esp32.local" - // - second argument is the IP address to advertise - // we send our IP address on the WiFi network - if (!MDNS.begin("esp32")) { - Serial.println("Error setting up MDNS responder!"); - while(1) { - delay(1000); - } - } - Serial.println("mDNS responder started"); - - // Start TCP (HTTP) server - server.begin(); - Serial.println("TCP server started"); - - // Add service to MDNS-SD - MDNS.addService("http", "tcp", 80); -} - -void loop(void) -{ - // Check if a client has connected - WiFiClient client = server.available(); - if (!client) { - return; - } - Serial.println(""); - Serial.println("New client"); - - // Wait for data from client to become available - while(client.connected() && !client.available()){ - delay(1); - } - - // Read the first line of HTTP request - String req = client.readStringUntil('\r'); - - // First line of HTTP request looks like "GET /path HTTP/1.1" - // Retrieve the "/path" part by finding the spaces - int addr_start = req.indexOf(' '); - int addr_end = req.indexOf(' ', addr_start + 1); - if (addr_start == -1 || addr_end == -1) { - Serial.print("Invalid request: "); - Serial.println(req); - return; - } - req = req.substring(addr_start + 1, addr_end); - Serial.print("Request: "); - Serial.println(req); - - String s; - if (req == "/") - { - IPAddress ip = WiFi.localIP(); - String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]); - s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\nHello from ESP32 at "; - s += ipStr; - s += "\r\n\r\n"; - Serial.println("Sending 200"); - } - else - { - s = "HTTP/1.1 404 Not Found\r\n\r\n"; - Serial.println("Sending 404"); - } - client.print(s); - - client.stop(); - Serial.println("Done with client"); -} - diff --git a/libraries/ESPmDNS/keywords.txt b/libraries/ESPmDNS/keywords.txt deleted file mode 100644 index c012cb59..00000000 --- a/libraries/ESPmDNS/keywords.txt +++ /dev/null @@ -1,25 +0,0 @@ -####################################### -# Syntax Coloring Map For Ultrasound -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ESPmDNS KEYWORD1 -MDNS KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -end KEYWORD2 -addService KEYWORD2 -enableArduino KEYWORD2 -disableArduino KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/ESPmDNS/library.properties b/libraries/ESPmDNS/library.properties deleted file mode 100644 index 4f956196..00000000 --- a/libraries/ESPmDNS/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=ESPmDNS -version=1.0 -author=Hristo Gochkov, Ivan Grokhtkov -maintainer=Hristo Gochkov -sentence=ESP32 mDNS Library -paragraph= -category=Communication -url= -architectures=esp32 diff --git a/libraries/ESPmDNS/src/ESPmDNS.cpp b/libraries/ESPmDNS/src/ESPmDNS.cpp deleted file mode 100644 index 3fe3403f..00000000 --- a/libraries/ESPmDNS/src/ESPmDNS.cpp +++ /dev/null @@ -1,345 +0,0 @@ -/* - -ESP8266 Multicast DNS (port of CC3000 Multicast DNS library) -Version 1.1 -Copyright (c) 2013 Tony DiCola (tony@tonydicola.com) -ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com) -MDNS-SD Suport 2015 Hristo Gochkov (hristo@espressif.com) -Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com) - - -License (MIT license): - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - */ - -// Important RFC's for reference: -// - DNS request and response: http://www.ietf.org/rfc/rfc1035.txt -// - Multicast DNS: http://www.ietf.org/rfc/rfc6762.txt -// - MDNS-SD: https://tools.ietf.org/html/rfc6763 - -#ifndef LWIP_OPEN_SRC -#define LWIP_OPEN_SRC -#endif - -#include "ESPmDNS.h" -#include "WiFi.h" -#include -#include "esp_wifi.h" - -// Add quotes around defined value -#ifdef __IN_ECLIPSE__ -#define STR_EXPAND(tok) #tok -#define STR(tok) STR_EXPAND(tok) -#else -#define STR(tok) tok -#endif - -// static void _on_sys_event(arduino_event_t *event){ -// mdns_handle_system_event(NULL, event); -// } - -MDNSResponder::MDNSResponder() :results(NULL) {} -MDNSResponder::~MDNSResponder() { - end(); -} - -bool MDNSResponder::begin(const char* hostName){ - if(mdns_init()){ - log_e("Failed starting MDNS"); - return false; - } - //WiFi.onEvent(_on_sys_event); - _hostname = hostName; - _hostname.toLowerCase(); - if(mdns_hostname_set(hostName)) { - log_e("Failed setting MDNS hostname"); - return false; - } - return true; -} - -void MDNSResponder::end() { - mdns_free(); -} - -void MDNSResponder::setInstanceName(String name) { - if (name.length() > 63) return; - if(mdns_instance_name_set(name.c_str())){ - log_e("Failed setting MDNS instance"); - return; - } -} - - -void MDNSResponder::enableArduino(uint16_t port, bool auth){ - mdns_txt_item_t arduTxtData[4] = { - {(char*)"board" ,(char*)STR(ARDUINO_VARIANT)}, - {(char*)"tcp_check" ,(char*)"no"}, - {(char*)"ssh_upload" ,(char*)"no"}, - {(char*)"auth_upload" ,(char*)"no"} - }; - - if(mdns_service_add(NULL, "_arduino", "_tcp", port, arduTxtData, 4)) { - log_e("Failed adding Arduino service"); - } - - if(auth && mdns_service_txt_item_set("_arduino", "_tcp", "auth_upload", "yes")){ - log_e("Failed setting Arduino txt item"); - } -} - -void MDNSResponder::disableArduino(){ - if(mdns_service_remove("_arduino", "_tcp")) { - log_w("Failed removing Arduino service"); - } -} - -void MDNSResponder::enableWorkstation(wifi_interface_t interface){ - char winstance[21+_hostname.length()]; - uint8_t mac[6]; - esp_wifi_get_mac(interface, mac); - sprintf(winstance, "%s [%02x:%02x:%02x:%02x:%02x:%02x]", _hostname.c_str(), mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); - - if(mdns_service_add(NULL, "_workstation", "_tcp", 9, NULL, 0)) { - log_e("Failed adding Workstation service"); - } else if(mdns_service_instance_name_set("_workstation", "_tcp", winstance)) { - log_e("Failed setting Workstation service instance name"); - } -} - -void MDNSResponder::disableWorkstation(){ - if(mdns_service_remove("_workstation", "_tcp")) { - log_w("Failed removing Workstation service"); - } -} - -bool MDNSResponder::addService(char *name, char *proto, uint16_t port){ - char _name[strlen(name)+2]; - char _proto[strlen(proto)+2]; - if (name[0] == '_') { - sprintf(_name, "%s", name); - } else { - sprintf(_name, "_%s", name); - } - if (proto[0] == '_') { - sprintf(_proto, "%s", proto); - } else { - sprintf(_proto, "_%s", proto); - } - - if(mdns_service_add(NULL, _name, _proto, port, NULL, 0)) { - log_e("Failed adding service %s.%s.\n", name, proto); - return false; - } - return true; -} - -bool MDNSResponder::addServiceTxt(char *name, char *proto, char *key, char *value){ - char _name[strlen(name)+2]; - char _proto[strlen(proto)+2]; - if (name[0] == '_') { - sprintf(_name, "%s", name); - } else { - sprintf(_name, "_%s", name); - } - if (proto[0] == '_') { - sprintf(_proto, "%s", proto); - } else { - sprintf(_proto, "_%s", proto); - } - - if(mdns_service_txt_item_set(_name, _proto, key, value)) { - log_e("Failed setting service TXT"); - return false; - } - return true; -} - -IPAddress MDNSResponder::queryHost(char *host, uint32_t timeout){ - esp_ip4_addr_t addr; - addr.addr = 0; - - esp_err_t err = mdns_query_a(host, timeout, &addr); - if(err){ - if(err == ESP_ERR_NOT_FOUND){ - log_w("Host was not found!"); - return IPAddress(); - } - log_e("Query Failed"); - return IPAddress(); - } - return IPAddress(addr.addr); -} - - -int MDNSResponder::queryService(char *service, char *proto) { - if(!service || !service[0] || !proto || !proto[0]){ - log_e("Bad Parameters"); - return 0; - } - - if(results){ - mdns_query_results_free(results); - results = NULL; - } - - char srv[strlen(service)+2]; - char prt[strlen(proto)+2]; - if (service[0] == '_') { - sprintf(srv, "%s", service); - } else { - sprintf(srv, "_%s", service); - } - if (proto[0] == '_') { - sprintf(prt, "%s", proto); - } else { - sprintf(prt, "_%s", proto); - } - - esp_err_t err = mdns_query_ptr(srv, prt, 3000, 20, &results); - if(err){ - log_e("Query Failed"); - return 0; - } - if(!results){ - log_w("No results found!"); - return 0; - } - - mdns_result_t * r = results; - int i = 0; - while(r){ - i++; - r = r->next; - } - return i; -} - -mdns_result_t * MDNSResponder::_getResult(int idx){ - mdns_result_t * result = results; - int i = 0; - while(result){ - if(i == idx){ - break; - } - i++; - result = result->next; - } - return result; -} - -String MDNSResponder::hostname(int idx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return String(); - } - return String(result->hostname); -} - -IPAddress MDNSResponder::IP(int idx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return IPAddress(); - } - mdns_ip_addr_t * addr = result->addr; - while(addr){ - if(addr->addr.type == MDNS_IP_PROTOCOL_V4){ - return IPAddress(addr->addr.u_addr.ip4.addr); - } - addr = addr->next; - } - return IPAddress(); -} - -IPv6Address MDNSResponder::IPv6(int idx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return IPv6Address(); - } - mdns_ip_addr_t * addr = result->addr; - while(addr){ - if(addr->addr.type == MDNS_IP_PROTOCOL_V6){ - return IPv6Address(addr->addr.u_addr.ip6.addr); - } - addr = addr->next; - } - return IPv6Address(); -} - -uint16_t MDNSResponder::port(int idx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return 0; - } - return result->port; -} - -int MDNSResponder::numTxt(int idx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return 0; - } - return result->txt_count; -} - -bool MDNSResponder::hasTxt(int idx, const char * key) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return false; - } - int i = 0; - while(i < result->txt_count) { - if (strcmp(result->txt[i].key, key) == 0) return true; - i++; - } - return false; -} - -String MDNSResponder::txt(int idx, const char * key) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return ""; - } - int i = 0; - while(i < result->txt_count) { - if (strcmp(result->txt[i].key, key) == 0) return result->txt[i].value; - i++; - } - return ""; -} - -String MDNSResponder::txt(int idx, int txtIdx) { - mdns_result_t * result = _getResult(idx); - if(!result){ - log_e("Result %d not found", idx); - return ""; - } - if (txtIdx >= result->txt_count) return ""; - return result->txt[txtIdx].value; -} - -MDNSResponder MDNS; diff --git a/libraries/ESPmDNS/src/ESPmDNS.h b/libraries/ESPmDNS/src/ESPmDNS.h deleted file mode 100644 index b4823d59..00000000 --- a/libraries/ESPmDNS/src/ESPmDNS.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -ESP8266 Multicast DNS (port of CC3000 Multicast DNS library) -Version 1.1 -Copyright (c) 2013 Tony DiCola (tony@tonydicola.com) -ESP8266 port (c) 2015 Ivan Grokhotkov (ivan@esp8266.com) -MDNS-SD Suport 2015 Hristo Gochkov (hristo@espressif.com) -Extended MDNS-SD support 2016 Lars Englund (lars.englund@gmail.com) -Rewritten for ESP32 by Hristo Gochkov (hristo@espressif.com) - -This is a simple implementation of multicast DNS query support for an Arduino -running on ESP32 chip. - -Usage: -- Include the ESP32 Multicast DNS library in the sketch. -- Call the begin method in the sketch's setup and provide a domain name (without - the '.local' suffix, i.e. just provide 'foo' to resolve 'foo.local'), and the - Adafruit CC3000 class instance. Optionally provide a time to live (in seconds) - for the DNS record--the default is 1 hour. -- Call the update method in each iteration of the sketch's loop function. - -License (MIT license): - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - -*/ -#ifndef ESP32MDNS_H -#define ESP32MDNS_H - -#include "Arduino.h" -#include "IPv6Address.h" -#include "mdns.h" - -//this should be defined at build time -#ifndef ARDUINO_VARIANT -#define ARDUINO_VARIANT "esp32" -#endif - -class MDNSResponder { -public: - MDNSResponder(); - ~MDNSResponder(); - bool begin(const char* hostName); - void end(); - - void setInstanceName(String name); - void setInstanceName(const char * name){ - setInstanceName(String(name)); - } - void setInstanceName(char * name){ - setInstanceName(String(name)); - } - - bool addService(char *service, char *proto, uint16_t port); - bool addService(const char *service, const char *proto, uint16_t port){ - return addService((char *)service, (char *)proto, port); - } - bool addService(String service, String proto, uint16_t port){ - return addService(service.c_str(), proto.c_str(), port); - } - - bool addServiceTxt(char *name, char *proto, char * key, char * value); - void addServiceTxt(const char *name, const char *proto, const char *key,const char * value){ - addServiceTxt((char *)name, (char *)proto, (char *)key, (char *)value); - } - void addServiceTxt(String name, String proto, String key, String value){ - addServiceTxt(name.c_str(), proto.c_str(), key.c_str(), value.c_str()); - } - - void enableArduino(uint16_t port=3232, bool auth=false); - void disableArduino(); - - void enableWorkstation(wifi_interface_t interface=WIFI_IF_STA); - void disableWorkstation(); - - IPAddress queryHost(char *host, uint32_t timeout=2000); - IPAddress queryHost(const char *host, uint32_t timeout=2000){ - return queryHost((char *)host, timeout); - } - IPAddress queryHost(String host, uint32_t timeout=2000){ - return queryHost(host.c_str(), timeout); - } - - int queryService(char *service, char *proto); - int queryService(const char *service, const char *proto){ - return queryService((char *)service, (char *)proto); - } - int queryService(String service, String proto){ - return queryService(service.c_str(), proto.c_str()); - } - - String hostname(int idx); - IPAddress IP(int idx); - IPv6Address IPv6(int idx); - uint16_t port(int idx); - int numTxt(int idx); - bool hasTxt(int idx, const char * key); - String txt(int idx, const char * key); - String txt(int idx, int txtIdx); - -private: - String _hostname; - mdns_result_t * results; - mdns_result_t * _getResult(int idx); -}; - -extern MDNSResponder MDNS; - -#endif //ESP32MDNS_H diff --git a/libraries/FFat/examples/FFat_Test/FFat_Test.ino b/libraries/FFat/examples/FFat_Test/FFat_Test.ino deleted file mode 100644 index 26a0bcac..00000000 --- a/libraries/FFat/examples/FFat_Test/FFat_Test.ino +++ /dev/null @@ -1,188 +0,0 @@ -#include "FS.h" -#include "FFat.h" - -// This file should be compiled with 'Partition Scheme' (in Tools menu) -// set to 'Default with ffat' if you have a 4MB ESP32 dev module or -// set to '16M Fat' if you have a 16MB ESP32 dev module. - -// You only need to format FFat the first time you run a test -#define FORMAT_FFAT true - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\r\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("- failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println(" - not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.println(file.name()); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print("\tSIZE: "); - Serial.println(file.size()); - } - file = root.openNextFile(); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\r\n", path); - - File file = fs.open(path); - if(!file || file.isDirectory()){ - Serial.println("- failed to open file for reading"); - return; - } - - Serial.println("- read from file:"); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\r\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\r\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("- failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("- message appended"); - } else { - Serial.println("- append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\r\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("- file renamed"); - } else { - Serial.println("- rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\r\n", path); - if(fs.remove(path)){ - Serial.println("- file deleted"); - } else { - Serial.println("- delete failed"); - } -} - -void testFileIO(fs::FS &fs, const char * path){ - Serial.printf("Testing file I/O with %s\r\n", path); - - static uint8_t buf[512]; - size_t len = 0; - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - - size_t i; - Serial.print("- writing" ); - uint32_t start = millis(); - for(i=0; i<2048; i++){ - if ((i & 0x001F) == 0x001F){ - Serial.print("."); - } - file.write(buf, 512); - } - Serial.println(""); - uint32_t end = millis() - start; - Serial.printf(" - %u bytes written in %u ms\r\n", 2048 * 512, end); - file.close(); - - file = fs.open(path); - start = millis(); - end = start; - i = 0; - if(file && !file.isDirectory()){ - len = file.size(); - size_t flen = len; - start = millis(); - Serial.print("- reading" ); - while(len){ - size_t toRead = len; - if(toRead > 512){ - toRead = 512; - } - file.read(buf, toRead); - if ((i++ & 0x001F) == 0x001F){ - Serial.print("."); - } - len -= toRead; - } - Serial.println(""); - end = millis() - start; - Serial.printf("- %u bytes read in %u ms\r\n", flen, end); - file.close(); - } else { - Serial.println("- failed to open file for reading"); - } -} - -void setup(){ - Serial.begin(115200); - Serial.setDebugOutput(true); - if (FORMAT_FFAT) FFat.format(); - if(!FFat.begin()){ - Serial.println("FFat Mount Failed"); - return; - } - - Serial.printf("Total space: %10u\n", FFat.totalBytes()); - Serial.printf("Free space: %10u\n", FFat.freeBytes()); - listDir(FFat, "/", 0); - writeFile(FFat, "/hello.txt", "Hello "); - appendFile(FFat, "/hello.txt", "World!\r\n"); - readFile(FFat, "/hello.txt"); - renameFile(FFat, "/hello.txt", "/foo.txt"); - readFile(FFat, "/foo.txt"); - deleteFile(FFat, "/foo.txt"); - testFileIO(FFat, "/test.txt"); - Serial.printf("Free space: %10u\n", FFat.freeBytes()); - deleteFile(FFat, "/test.txt"); - Serial.println( "Test complete" ); -} - -void loop(){ - -} diff --git a/libraries/FFat/examples/FFat_time/FFat_time.ino b/libraries/FFat/examples/FFat_time/FFat_time.ino deleted file mode 100644 index 1e379451..00000000 --- a/libraries/FFat/examples/FFat_time/FFat_time.ino +++ /dev/null @@ -1,177 +0,0 @@ -#include "FS.h" -#include "FFat.h" -#include -#include - -const char* ssid = "your-ssid"; -const char* password = "your-password"; - -long timezone = 1; -byte daysavetime = 1; - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.print (file.name()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.print(file.size()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void setup(){ - Serial.begin(115200); - // We start by connecting to a WiFi network - Serial.println(); - Serial.println(); - Serial.print("Connecting to "); - Serial.println(ssid); - - WiFi.begin(ssid, password); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - Serial.println("Contacting Time Server"); - configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); - struct tm tmstruct ; - delay(2000); - tmstruct.tm_year = 0; - getLocalTime(&tmstruct, 5000); - Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec); - Serial.println(""); - - if(!FFat.begin(true)){ - Serial.println("FFat Mount Failed"); - return; - } - - listDir(FFat, "/", 0); - removeDir(FFat, "/mydir"); - createDir(FFat, "/mydir"); - deleteFile(FFat, "/hello.txt"); - writeFile(FFat, "/hello.txt", "Hello "); - appendFile(FFat, "/hello.txt", "World!\n"); - listDir(FFat, "/", 0); -} - -void loop(){ - -} - - diff --git a/libraries/FFat/library.properties b/libraries/FFat/library.properties deleted file mode 100644 index aebca39d..00000000 --- a/libraries/FFat/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=FFat -version=1.0 -author=Hristo Gochkov, Ivan Grokhtkov, Larry Bernstone -maintainer=Hristo Gochkov -sentence=ESP32 FAT on Flash File System -paragraph= -category=Data Storage -url= -architectures=esp32 diff --git a/libraries/FFat/src/FFat.cpp b/libraries/FFat/src/FFat.cpp deleted file mode 100644 index 6441dfca..00000000 --- a/libraries/FFat/src/FFat.cpp +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "vfs_api.h" -extern "C" { -#include "esp_vfs_fat.h" -#include "diskio.h" -#include "diskio_wl.h" -#include "vfs_fat_internal.h" -} -#include "FFat.h" - -using namespace fs; - -F_Fat::F_Fat(FSImplPtr impl) - : FS(impl) -{} - -const esp_partition_t *check_ffat_partition(const char* label) -{ - const esp_partition_t* ck_part = esp_partition_find_first( - ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_FAT, label); - if (!ck_part) { - log_e("No FAT partition found with label %s", label); - return NULL; - } - return ck_part; -} - -bool F_Fat::begin(bool formatOnFail, const char * basePath, uint8_t maxOpenFiles, const char * partitionLabel) -{ - if(_wl_handle != WL_INVALID_HANDLE){ - log_w("Already Mounted!"); - return true; - } - - if (!check_ffat_partition(partitionLabel)){ - log_e("No fat partition found on flash"); - return false; - } - - esp_vfs_fat_mount_config_t conf = { - .format_if_mount_failed = formatOnFail, - .max_files = maxOpenFiles, - .allocation_unit_size = CONFIG_WL_SECTOR_SIZE - }; - esp_err_t err = esp_vfs_fat_spiflash_mount(basePath, partitionLabel, &conf, &_wl_handle); - if(err){ - log_e("Mounting FFat partition failed! Error: %d", err); - esp_vfs_fat_spiflash_unmount(basePath, _wl_handle); - _wl_handle = WL_INVALID_HANDLE; - return false; - } - _impl->mountpoint(basePath); - return true; -} - -void F_Fat::end() -{ - if(_wl_handle != WL_INVALID_HANDLE){ - esp_err_t err = esp_vfs_fat_spiflash_unmount(_impl->mountpoint(), _wl_handle); - if(err){ - log_e("Unmounting FFat partition failed! Error: %d", err); - return; - } - _wl_handle = WL_INVALID_HANDLE; - _impl->mountpoint(NULL); - } -} - -bool F_Fat::format(bool full_wipe, char* partitionLabel) -{ - esp_err_t result; - bool res = true; - if(_wl_handle != WL_INVALID_HANDLE){ - log_w("Already Mounted!"); - return false; - } - wl_handle_t temp_handle; -// Attempt to mount to see if there is already data - const esp_partition_t *ffat_partition = check_ffat_partition(partitionLabel); - if (!ffat_partition){ - log_w("No partition!"); - return false; - } - result = wl_mount(ffat_partition, &temp_handle); - - if (result == ESP_OK) { -// Wipe disk- quick just wipes the FAT. Full zeroes the whole disk - uint32_t wipe_size = full_wipe ? wl_size(temp_handle) : 16384; - wl_erase_range(temp_handle, 0, wipe_size); - wl_unmount(temp_handle); - } else { - res = false; - log_w("wl_mount failed!"); - } -// Now do a mount with format_if_fail (which it will) - esp_vfs_fat_mount_config_t conf = { - .format_if_mount_failed = true, - .max_files = 1, - .allocation_unit_size = CONFIG_WL_SECTOR_SIZE - }; - result = esp_vfs_fat_spiflash_mount("/format_ffat", partitionLabel, &conf, &temp_handle); - esp_vfs_fat_spiflash_unmount("/format_ffat", temp_handle); - if (result != ESP_OK){ - res = false; - log_w("esp_vfs_fat_spiflash_mount failed!"); - } - return res; -} - -size_t F_Fat::totalBytes() -{ - FATFS *fs; - DWORD free_clust, tot_sect, sect_size; - - BYTE pdrv = ff_diskio_get_pdrv_wl(_wl_handle); - char drv[3] = {(char)(48+pdrv), ':', 0}; - if ( f_getfree(drv, &free_clust, &fs) != FR_OK){ - return 0; - } - tot_sect = (fs->n_fatent - 2) * fs->csize; - sect_size = CONFIG_WL_SECTOR_SIZE; - return tot_sect * sect_size; -} - -size_t F_Fat::usedBytes() -{ - FATFS *fs; - DWORD free_clust, used_sect, sect_size; - - BYTE pdrv = ff_diskio_get_pdrv_wl(_wl_handle); - char drv[3] = {(char)(48+pdrv), ':', 0}; - if ( f_getfree(drv, &free_clust, &fs) != FR_OK){ - return 0; - } - used_sect = (fs->n_fatent - 2 - free_clust) * fs->csize; - sect_size = CONFIG_WL_SECTOR_SIZE; - return used_sect * sect_size; -} - -size_t F_Fat::freeBytes() -{ - - FATFS *fs; - DWORD free_clust, free_sect, sect_size; - - BYTE pdrv = ff_diskio_get_pdrv_wl(_wl_handle); - char drv[3] = {(char)(48+pdrv), ':', 0}; - if ( f_getfree(drv, &free_clust, &fs) != FR_OK){ - return 0; - } - free_sect = free_clust * fs->csize; - sect_size = CONFIG_WL_SECTOR_SIZE; - return free_sect * sect_size; -} - -bool F_Fat::exists(const char* path) -{ - File f = open(path, "r"); - return (f == true) && !f.isDirectory(); -} - -bool F_Fat::exists(const String& path) -{ - return exists(path.c_str()); -} - - -F_Fat FFat = F_Fat(FSImplPtr(new VFSImpl())); diff --git a/libraries/FFat/src/FFat.h b/libraries/FFat/src/FFat.h deleted file mode 100644 index ed20e23b..00000000 --- a/libraries/FFat/src/FFat.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _FFAT_H_ -#define _FFAT_H_ - -#include "FS.h" -#include "wear_levelling.h" - -#define FFAT_WIPE_QUICK 0 -#define FFAT_WIPE_FULL 1 -#define FFAT_PARTITION_LABEL "ffat" - -namespace fs -{ - -class F_Fat : public FS -{ -public: - F_Fat(FSImplPtr impl); - bool begin(bool formatOnFail=false, const char * basePath="/ffat", uint8_t maxOpenFiles=10, const char * partitionLabel = (char*)FFAT_PARTITION_LABEL); - bool format(bool full_wipe = FFAT_WIPE_QUICK, char* partitionLabel = (char*)FFAT_PARTITION_LABEL); - size_t totalBytes(); - size_t usedBytes(); - size_t freeBytes(); - void end(); - bool exists(const char* path); - bool exists(const String& path); - -private: - wl_handle_t _wl_handle = WL_INVALID_HANDLE; -}; - -} - -extern fs::F_Fat FFat; - -#endif /* _FFAT_H_ */ diff --git a/libraries/HTTPClient/examples/Authorization/Authorization.ino b/libraries/HTTPClient/examples/Authorization/Authorization.ino deleted file mode 100644 index 400f93cc..00000000 --- a/libraries/HTTPClient/examples/Authorization/Authorization.ino +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Authorization.ino - * - * Created on: 09.12.2015 - * - */ - -#include - -#include -#include - -#include - -#define USE_SERIAL Serial - -WiFiMulti wifiMulti; - -void setup() { - - USE_SERIAL.begin(115200); - - USE_SERIAL.println(); - USE_SERIAL.println(); - USE_SERIAL.println(); - - for(uint8_t t = 4; t > 0; t--) { - USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); - USE_SERIAL.flush(); - delay(1000); - } - - wifiMulti.addAP("SSID", "PASSWORD"); - -} - -void loop() { - // wait for WiFi connection - if((wifiMulti.run() == WL_CONNECTED)) { - - HTTPClient http; - - USE_SERIAL.print("[HTTP] begin...\n"); - // configure traged server and url - - - http.begin("http://user:password@192.168.1.12/test.html"); - - /* - // or - http.begin("http://192.168.1.12/test.html"); - http.setAuthorization("user", "password"); - - // or - http.begin("http://192.168.1.12/test.html"); - http.setAuthorization("dXNlcjpwYXN3b3Jk"); - */ - - - USE_SERIAL.print("[HTTP] GET...\n"); - // start connection and send HTTP header - int httpCode = http.GET(); - - // httpCode will be negative on error - if(httpCode > 0) { - // HTTP header has been send and Server response header has been handled - USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if(httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - USE_SERIAL.println(payload); - } - } else { - USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - - http.end(); - } - - delay(10000); -} - diff --git a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino b/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino deleted file mode 100644 index 9ee620ab..00000000 --- a/libraries/HTTPClient/examples/BasicHttpClient/BasicHttpClient.ino +++ /dev/null @@ -1,101 +0,0 @@ -/** - * BasicHTTPClient.ino - * - * Created on: 24.05.2015 - * - */ - -#include - -#include -#include - -#include - -#define USE_SERIAL Serial - -WiFiMulti wifiMulti; - -/* -const char* ca = \ -"-----BEGIN CERTIFICATE-----\n" \ -"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ -"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ -"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ -"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ -"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ -"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ -"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ -"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ -"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ -"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ -"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ -"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ -"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ -"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ -"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ -"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ -"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ -"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ -"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ -"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ -"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ -"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ -"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ -"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ -"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ -"-----END CERTIFICATE-----\n"; -*/ - -void setup() { - - USE_SERIAL.begin(115200); - - USE_SERIAL.println(); - USE_SERIAL.println(); - USE_SERIAL.println(); - - for(uint8_t t = 4; t > 0; t--) { - USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); - USE_SERIAL.flush(); - delay(1000); - } - - wifiMulti.addAP("SSID", "PASSWORD"); - -} - -void loop() { - // wait for WiFi connection - if((wifiMulti.run() == WL_CONNECTED)) { - - HTTPClient http; - - USE_SERIAL.print("[HTTP] begin...\n"); - // configure traged server and url - //http.begin("https://www.howsmyssl.com/a/check", ca); //HTTPS - http.begin("http://example.com/index.html"); //HTTP - - USE_SERIAL.print("[HTTP] GET...\n"); - // start connection and send HTTP header - int httpCode = http.GET(); - - // httpCode will be negative on error - if(httpCode > 0) { - // HTTP header has been send and Server response header has been handled - USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if(httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - USE_SERIAL.println(payload); - } - } else { - USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - - http.end(); - } - - delay(5000); -} diff --git a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino b/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino deleted file mode 100644 index 9ef2b44e..00000000 --- a/libraries/HTTPClient/examples/BasicHttpsClient/BasicHttpsClient.ino +++ /dev/null @@ -1,147 +0,0 @@ -/** - BasicHTTPSClient.ino - - Created on: 14.10.2018 - -*/ - -#include - -#include -#include - -#include - -#include - -// This is GandiStandardSSLCA2.pem, the root Certificate Authority that signed -// the server certifcate for the demo server https://jigsaw.w3.org in this -// example. This certificate is valid until Sep 11 23:59:59 2024 GMT -const char* rootCACertificate = \ -"-----BEGIN CERTIFICATE-----\n" \ -"MIIF6TCCA9GgAwIBAgIQBeTcO5Q4qzuFl8umoZhQ4zANBgkqhkiG9w0BAQwFADCB\n" \ -"iDELMAkGA1UEBhMCVVMxEzARBgNVBAgTCk5ldyBKZXJzZXkxFDASBgNVBAcTC0pl\n" \ -"cnNleSBDaXR5MR4wHAYDVQQKExVUaGUgVVNFUlRSVVNUIE5ldHdvcmsxLjAsBgNV\n" \ -"BAMTJVVTRVJUcnVzdCBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTQw\n" \ -"OTEyMDAwMDAwWhcNMjQwOTExMjM1OTU5WjBfMQswCQYDVQQGEwJGUjEOMAwGA1UE\n" \ -"CBMFUGFyaXMxDjAMBgNVBAcTBVBhcmlzMQ4wDAYDVQQKEwVHYW5kaTEgMB4GA1UE\n" \ -"AxMXR2FuZGkgU3RhbmRhcmQgU1NMIENBIDIwggEiMA0GCSqGSIb3DQEBAQUAA4IB\n" \ -"DwAwggEKAoIBAQCUBC2meZV0/9UAPPWu2JSxKXzAjwsLibmCg5duNyj1ohrP0pIL\n" \ -"m6jTh5RzhBCf3DXLwi2SrCG5yzv8QMHBgyHwv/j2nPqcghDA0I5O5Q1MsJFckLSk\n" \ -"QFEW2uSEEi0FXKEfFxkkUap66uEHG4aNAXLy59SDIzme4OFMH2sio7QQZrDtgpbX\n" \ -"bmq08j+1QvzdirWrui0dOnWbMdw+naxb00ENbLAb9Tr1eeohovj0M1JLJC0epJmx\n" \ -"bUi8uBL+cnB89/sCdfSN3tbawKAyGlLfOGsuRTg/PwSWAP2h9KK71RfWJ3wbWFmV\n" \ -"XooS/ZyrgT5SKEhRhWvzkbKGPym1bgNi7tYFAgMBAAGjggF1MIIBcTAfBgNVHSME\n" \ -"GDAWgBRTeb9aqitKz1SA4dibwJ3ysgNmyzAdBgNVHQ4EFgQUs5Cn2MmvTs1hPJ98\n" \ -"rV1/Qf1pMOowDgYDVR0PAQH/BAQDAgGGMBIGA1UdEwEB/wQIMAYBAf8CAQAwHQYD\n" \ -"VR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMCIGA1UdIAQbMBkwDQYLKwYBBAGy\n" \ -"MQECAhowCAYGZ4EMAQIBMFAGA1UdHwRJMEcwRaBDoEGGP2h0dHA6Ly9jcmwudXNl\n" \ -"cnRydXN0LmNvbS9VU0VSVHJ1c3RSU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNy\n" \ -"bDB2BggrBgEFBQcBAQRqMGgwPwYIKwYBBQUHMAKGM2h0dHA6Ly9jcnQudXNlcnRy\n" \ -"dXN0LmNvbS9VU0VSVHJ1c3RSU0FBZGRUcnVzdENBLmNydDAlBggrBgEFBQcwAYYZ\n" \ -"aHR0cDovL29jc3AudXNlcnRydXN0LmNvbTANBgkqhkiG9w0BAQwFAAOCAgEAWGf9\n" \ -"crJq13xhlhl+2UNG0SZ9yFP6ZrBrLafTqlb3OojQO3LJUP33WbKqaPWMcwO7lWUX\n" \ -"zi8c3ZgTopHJ7qFAbjyY1lzzsiI8Le4bpOHeICQW8owRc5E69vrOJAKHypPstLbI\n" \ -"FhfFcvwnQPYT/pOmnVHvPCvYd1ebjGU6NSU2t7WKY28HJ5OxYI2A25bUeo8tqxyI\n" \ -"yW5+1mUfr13KFj8oRtygNeX56eXVlogMT8a3d2dIhCe2H7Bo26y/d7CQuKLJHDJd\n" \ -"ArolQ4FCR7vY4Y8MDEZf7kYzawMUgtN+zY+vkNaOJH1AQrRqahfGlZfh8jjNp+20\n" \ -"J0CT33KpuMZmYzc4ZCIwojvxuch7yPspOqsactIGEk72gtQjbz7Dk+XYtsDe3CMW\n" \ -"1hMwt6CaDixVBgBwAc/qOR2A24j3pSC4W/0xJmmPLQphgzpHphNULB7j7UTKvGof\n" \ -"KA5R2d4On3XNDgOVyvnFqSot/kGkoUeuDcL5OWYzSlvhhChZbH2UF3bkRYKtcCD9\n" \ -"0m9jqNf6oDP6N8v3smWe2lBvP+Sn845dWDKXcCMu5/3EFZucJ48y7RetWIExKREa\n" \ -"m9T8bJUox04FB6b9HbwZ4ui3uRGKLXASUoWNjDNKD/yZkuBjcNqllEdjB+dYxzFf\n" \ -"BT02Vf6Dsuimrdfp5gJ0iHRc2jTbkNJtUQoj1iM=\n" \ -"-----END CERTIFICATE-----\n"; - -// Not sure if WiFiClientSecure checks the validity date of the certificate. -// Setting clock just to be sure... -void setClock() { - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); - - Serial.print(F("Waiting for NTP time sync: ")); - time_t nowSecs = time(nullptr); - while (nowSecs < 8 * 3600 * 2) { - delay(500); - Serial.print(F(".")); - yield(); - nowSecs = time(nullptr); - } - - Serial.println(); - struct tm timeinfo; - gmtime_r(&nowSecs, &timeinfo); - Serial.print(F("Current time: ")); - Serial.print(asctime(&timeinfo)); -} - - -WiFiMulti WiFiMulti; - -void setup() { - - Serial.begin(115200); - // Serial.setDebugOutput(true); - - Serial.println(); - Serial.println(); - Serial.println(); - - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); - - // wait for WiFi connection - Serial.print("Waiting for WiFi to connect..."); - while ((WiFiMulti.run() != WL_CONNECTED)) { - Serial.print("."); - } - Serial.println(" connected"); - - setClock(); -} - -void loop() { - WiFiClientSecure *client = new WiFiClientSecure; - if(client) { - client -> setCACert(rootCACertificate); - - { - // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is - HTTPClient https; - - Serial.print("[HTTPS] begin...\n"); - if (https.begin(*client, "https://jigsaw.w3.org/HTTP/connection.html")) { // HTTPS - Serial.print("[HTTPS] GET...\n"); - // start connection and send HTTP header - int httpCode = https.GET(); - - // httpCode will be negative on error - if (httpCode > 0) { - // HTTP header has been send and Server response header has been handled - Serial.printf("[HTTPS] GET... code: %d\n", httpCode); - - // file found at server - if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { - String payload = https.getString(); - Serial.println(payload); - } - } else { - Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str()); - } - - https.end(); - } else { - Serial.printf("[HTTPS] Unable to connect\n"); - } - - // End extra scoping block - } - - delete client; - } else { - Serial.println("Unable to create client"); - } - - Serial.println(); - Serial.println("Waiting 10s before the next round..."); - delay(10000); -} diff --git a/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino b/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino deleted file mode 100644 index b229a868..00000000 --- a/libraries/HTTPClient/examples/HTTPClientEnterprise/HTTPClientEnterprise.ino +++ /dev/null @@ -1,97 +0,0 @@ -/*|----------------------------------------------------------|*/ -/*|WORKING EXAMPLE FOR HTTP/HTTPS CONNECTION |*/ -/*|TESTED BOARDS: Devkit v1 DOIT, Devkitc v4 |*/ -/*|CORE: June 2018 |*/ -/*|----------------------------------------------------------|*/ -#include -#include -#include "esp_wpa2.h" -#include -#define EAP_IDENTITY "identity" //if connecting from another corporation, use identity@organisation.domain in Eduroam -#define EAP_PASSWORD "password" //your Eduroam password -const char* ssid = "eduroam"; // Eduroam SSID -int counter = 0; -const char* test_root_ca= \ -"-----BEGIN CERTIFICATE-----\n" \ -"MIIDrzCCApegAwIBAgIQCDvgVpBCRrGhdWrJWZHHSjANBgkqhkiG9w0BAQUFADBh\n" \ -"MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3\n" \ -"d3cuZGlnaWNlcnQuY29tMSAwHgYDVQQDExdEaWdpQ2VydCBHbG9iYWwgUm9vdCBD\n" \ -"QTAeFw0wNjExMTAwMDAwMDBaFw0zMTExMTAwMDAwMDBaMGExCzAJBgNVBAYTAlVT\n" \ -"MRUwEwYDVQQKEwxEaWdpQ2VydCBJbmMxGTAXBgNVBAsTEHd3dy5kaWdpY2VydC5j\n" \ -"b20xIDAeBgNVBAMTF0RpZ2lDZXJ0IEdsb2JhbCBSb290IENBMIIBIjANBgkqhkiG\n" \ -"9w0BAQEFAAOCAQ8AMIIBCgKCAQEA4jvhEXLeqKTTo1eqUKKPC3eQyaKl7hLOllsB\n" \ -"CSDMAZOnTjC3U/dDxGkAV53ijSLdhwZAAIEJzs4bg7/fzTtxRuLWZscFs3YnFo97\n" \ -"nh6Vfe63SKMI2tavegw5BmV/Sl0fvBf4q77uKNd0f3p4mVmFaG5cIzJLv07A6Fpt\n" \ -"43C/dxC//AH2hdmoRBBYMql1GNXRor5H4idq9Joz+EkIYIvUX7Q6hL+hqkpMfT7P\n" \ -"T19sdl6gSzeRntwi5m3OFBqOasv+zbMUZBfHWymeMr/y7vrTC0LUq7dBMtoM1O/4\n" \ -"gdW7jVg/tRvoSSiicNoxBN33shbyTApOB6jtSj1etX+jkMOvJwIDAQABo2MwYTAO\n" \ -"BgNVHQ8BAf8EBAMCAYYwDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUA95QNVbR\n" \ -"TLtm8KPiGxvDl7I90VUwHwYDVR0jBBgwFoAUA95QNVbRTLtm8KPiGxvDl7I90VUw\n" \ -"DQYJKoZIhvcNAQEFBQADggEBAMucN6pIExIK+t1EnE9SsPTfrgT1eXkIoyQY/Esr\n" \ -"hMAtudXH/vTBH1jLuG2cenTnmCmrEbXjcKChzUyImZOMkXDiqw8cvpOp/2PV5Adg\n" \ -"06O/nVsJ8dWO41P0jmP6P6fbtGbfYmbW0W5BjfIttep3Sp+dWOIrWcBAI+0tKIJF\n" \ -"PnlUkiaY4IBIqDfv8NZ5YBberOgOzW6sRBc4L0na4UU+Krk2U886UAb3LujEV0ls\n" \ -"YSEY1QSteDwsOoBrp+uvFRTp2InBuThs4pFsiv9kuXclVzDAGySj4dzp30d8tbQk\n" \ -"CAUw7C29C79Fv1C5qfPrmAESrciIxpg0X40KPMbp1ZWVbd4=\n" \ -"-----END CERTIFICATE-----\n"; -void setup() { - Serial.begin(115200); - delay(10); - Serial.println(); - Serial.print("Connecting to network: "); - Serial.println(ssid); - WiFi.disconnect(true); //disconnect form wifi to set new wifi connection - WiFi.mode(WIFI_STA); //init wifi mode - esp_wifi_sta_wpa2_ent_set_identity((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide identity - esp_wifi_sta_wpa2_ent_set_username((uint8_t *)EAP_IDENTITY, strlen(EAP_IDENTITY)); //provide username --> identity and username is same - esp_wifi_sta_wpa2_ent_set_password((uint8_t *)EAP_PASSWORD, strlen(EAP_PASSWORD)); //provide password - esp_wifi_sta_wpa2_ent_enable(); - WiFi.begin(ssid); //connect to wifi - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - counter++; - if(counter>=60){ //after 30 seconds timeout - reset board - ESP.restart(); - } - } - Serial.println(""); - Serial.println("WiFi connected"); - Serial.println("IP address set: "); - Serial.println(WiFi.localIP()); //print LAN IP -} -void loop() { - if (WiFi.status() == WL_CONNECTED) { //if we are connected to Eduroam network - counter = 0; //reset counter - Serial.println("Wifi is still connected with IP: "); - Serial.println(WiFi.localIP()); //inform user about his IP address - }else if (WiFi.status() != WL_CONNECTED) { //if we lost connection, retry - WiFi.begin(ssid); - } - while (WiFi.status() != WL_CONNECTED) { //during lost connection, print dots - delay(500); - Serial.print("."); - counter++; - if(counter>=60){ //30 seconds timeout - reset board - ESP.restart(); - } - } - Serial.print("Connecting to website: "); - HTTPClient http; - http.begin("https://arduino.php5.sk/rele/rele1.txt", test_root_ca); //HTTPS example connection - //http.begin("http://www.arduino.php5.sk/rele/rele1.txt"); //HTTP example connection - //if uncomment HTTP example, you can comment root CA certificate too! - int httpCode = http.GET(); - if(httpCode > 0) { - Serial.printf("[HTTP] GET... code: %d\n", httpCode); - //file found at server --> on unsucessful connection code will be -1 - if(httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - Serial.println(payload); - } - }else{ - Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - http.end(); - delay(2000); -} diff --git a/libraries/HTTPClient/examples/ReuseConnection/ReuseConnection.ino b/libraries/HTTPClient/examples/ReuseConnection/ReuseConnection.ino deleted file mode 100644 index d3bcefbe..00000000 --- a/libraries/HTTPClient/examples/ReuseConnection/ReuseConnection.ino +++ /dev/null @@ -1,68 +0,0 @@ -/** - * reuseConnection.ino - * - * Created on: 22.11.2015 - * - */ - - -#include - -#include -#include - -#include - -#define USE_SERIAL Serial - -WiFiMulti wifiMulti; - -HTTPClient http; - -void setup() { - - USE_SERIAL.begin(115200); - - USE_SERIAL.println(); - USE_SERIAL.println(); - USE_SERIAL.println(); - - for(uint8_t t = 4; t > 0; t--) { - USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); - USE_SERIAL.flush(); - delay(1000); - } - - wifiMulti.addAP("SSID", "PASSWORD"); - - // allow reuse (if server supports it) - http.setReuse(true); -} - -void loop() { - // wait for WiFi connection - if((wifiMulti.run() == WL_CONNECTED)) { - - http.begin("http://192.168.1.12/test.html"); - //http.begin("192.168.1.12", 80, "/test.html"); - - int httpCode = http.GET(); - if(httpCode > 0) { - USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if(httpCode == HTTP_CODE_OK) { - http.writeToStream(&USE_SERIAL); - } - } else { - USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - - http.end(); - } - - delay(1000); -} - - - diff --git a/libraries/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino b/libraries/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino deleted file mode 100644 index 6ea07f66..00000000 --- a/libraries/HTTPClient/examples/StreamHttpClient/StreamHttpClient.ino +++ /dev/null @@ -1,100 +0,0 @@ -/** - * StreamHTTPClient.ino - * - * Created on: 24.05.2015 - * - */ - -#include - -#include -#include - -#include - -#define USE_SERIAL Serial - -WiFiMulti wifiMulti; - -void setup() { - - USE_SERIAL.begin(115200); - - USE_SERIAL.println(); - USE_SERIAL.println(); - USE_SERIAL.println(); - - for(uint8_t t = 4; t > 0; t--) { - USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); - USE_SERIAL.flush(); - delay(1000); - } - - wifiMulti.addAP("SSID", "PASSWORD"); - -} - -void loop() { - // wait for WiFi connection - if((wifiMulti.run() == WL_CONNECTED)) { - - HTTPClient http; - - USE_SERIAL.print("[HTTP] begin...\n"); - - // configure server and url - http.begin("http://192.168.1.12/test.html"); - //http.begin("192.168.1.12", 80, "/test.html"); - - USE_SERIAL.print("[HTTP] GET...\n"); - // start connection and send HTTP header - int httpCode = http.GET(); - if(httpCode > 0) { - // HTTP header has been send and Server response header has been handled - USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); - - // file found at server - if(httpCode == HTTP_CODE_OK) { - - // get lenght of document (is -1 when Server sends no Content-Length header) - int len = http.getSize(); - - // create buffer for read - uint8_t buff[128] = { 0 }; - - // get tcp stream - WiFiClient * stream = http.getStreamPtr(); - - // read all data from server - while(http.connected() && (len > 0 || len == -1)) { - // get available data size - size_t size = stream->available(); - - if(size) { - // read up to 128 byte - int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); - - // write it to Serial - USE_SERIAL.write(buff, c); - - if(len > 0) { - len -= c; - } - } - delay(1); - } - - USE_SERIAL.println(); - USE_SERIAL.print("[HTTP] connection closed or file end.\n"); - - } - } else { - USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - - http.end(); - } - - delay(10000); -} - diff --git a/libraries/HTTPClient/library.properties b/libraries/HTTPClient/library.properties deleted file mode 100644 index 153a2e25..00000000 --- a/libraries/HTTPClient/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=HTTPClient -version=1.2 -author=Markus Sattler -maintainer=Markus Sattler -sentence=HTTP Client for ESP32 -paragraph= -category=Communication -url=https://github.com/espressif/arduino-esp32/tree/master/libraries/HTTPClient -architectures=esp32 diff --git a/libraries/HTTPClient/src/HTTPClient.cpp b/libraries/HTTPClient/src/HTTPClient.cpp deleted file mode 100644 index 49b94169..00000000 --- a/libraries/HTTPClient/src/HTTPClient.cpp +++ /dev/null @@ -1,1456 +0,0 @@ -#include -/** - * HTTPClient.cpp - * - * Created on: 02.11.2015 - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the HTTPClient for Arduino. - * Port to ESP32 by Evandro Luis Copercini (2017), - * changed fingerprints to CA verification. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - * Adapted in October 2018 - */ - -#include -#include - -#ifdef HTTPCLIENT_1_1_COMPATIBLE -#include -#include -#endif - -#include -#include - -#include "HTTPClient.h" - -#ifdef HTTPCLIENT_1_1_COMPATIBLE -class TransportTraits -{ -public: - virtual ~TransportTraits() - { - } - - virtual std::unique_ptr create() - { - return std::unique_ptr(new WiFiClient()); - } - - virtual bool verify(WiFiClient& client, const char* host) - { - return true; - } -}; - -class TLSTraits : public TransportTraits -{ -public: - TLSTraits(const char* CAcert, const char* clicert = nullptr, const char* clikey = nullptr) : - _cacert(CAcert), _clicert(clicert), _clikey(clikey) - { - } - - std::unique_ptr create() override - { - return std::unique_ptr(new WiFiClientSecure()); - } - - bool verify(WiFiClient& client, const char* host) override - { - WiFiClientSecure& wcs = static_cast(client); - wcs.setCACert(_cacert); - wcs.setCertificate(_clicert); - wcs.setPrivateKey(_clikey); - return true; - } - -protected: - const char* _cacert; - const char* _clicert; - const char* _clikey; -}; -#endif // HTTPCLIENT_1_1_COMPATIBLE - -/** - * constructor - */ -HTTPClient::HTTPClient() -{ -} - -/** - * destructor - */ -HTTPClient::~HTTPClient() -{ - if(_client) { - _client->stop(); - } - if(_currentHeaders) { - delete[] _currentHeaders; - } -} - -void HTTPClient::clear() -{ - _returnCode = 0; - _size = -1; - _headers = ""; -} - - -/** - * parsing the url for all needed parameters - * @param client Client& - * @param url String - * @param https bool - * @return success bool - */ -bool HTTPClient::begin(WiFiClient &client, String url) { -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if(_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } -#endif - - _client = &client; - - // check for : (http: or https:) - int index = url.indexOf(':'); - if(index < 0) { - log_d("failed to parse protocol"); - return false; - } - - String protocol = url.substring(0, index); - if(protocol != "http" && protocol != "https") { - log_d("unknown protocol '%s'", protocol.c_str()); - return false; - } - - _port = (protocol == "https" ? 443 : 80); - return beginInternal(url, protocol.c_str()); -} - - -/** - * directly supply all needed parameters - * @param client Client& - * @param host String - * @param port uint16_t - * @param uri String - * @param https bool - * @return success bool - */ -bool HTTPClient::begin(WiFiClient &client, String host, uint16_t port, String uri, bool https) -{ -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if(_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } -#endif - - _client = &client; - - clear(); - _host = host; - _port = port; - _uri = uri; - _protocol = (https ? "https" : "http"); - return true; -} - - -#ifdef HTTPCLIENT_1_1_COMPATIBLE -bool HTTPClient::begin(String url, const char* CAcert) -{ - if(_client && !_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } - - _port = 443; - if (!beginInternal(url, "https")) { - return false; - } - _secure = true; - _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert)); - if(!_transportTraits) { - log_e("could not create transport traits"); - return false; - } - - return true; -} - -/** - * parsing the url for all needed parameters - * @param url String - */ -bool HTTPClient::begin(String url) -{ - if(_client && !_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } - - _port = 80; - if (!beginInternal(url, "http")) { - return begin(url, (const char*)NULL); - } - _transportTraits = TransportTraitsPtr(new TransportTraits()); - if(!_transportTraits) { - log_e("could not create transport traits"); - return false; - } - - return true; -} -#endif // HTTPCLIENT_1_1_COMPATIBLE - -bool HTTPClient::beginInternal(String url, const char* expectedProtocol) -{ - log_v("url: %s", url.c_str()); - clear(); - - // check for : (http: or https: - int index = url.indexOf(':'); - if(index < 0) { - log_e("failed to parse protocol"); - return false; - } - - _protocol = url.substring(0, index); - if (_protocol != expectedProtocol) { - log_w("unexpected protocol: %s, expected %s", _protocol.c_str(), expectedProtocol); - return false; - } - - url.remove(0, (index + 3)); // remove http:// or https:// - - index = url.indexOf('/'); - String host = url.substring(0, index); - url.remove(0, index); // remove host part - - // get Authorization - index = host.indexOf('@'); - if(index >= 0) { - // auth info - String auth = host.substring(0, index); - host.remove(0, index + 1); // remove auth part including @ - _base64Authorization = base64::encode(auth); - } - - // get port - index = host.indexOf(':'); - if(index >= 0) { - _host = host.substring(0, index); // hostname - host.remove(0, (index + 1)); // remove hostname + : - _port = host.toInt(); // get port - } else { - _host = host; - } - _uri = url; - log_d("host: %s port: %d url: %s", _host.c_str(), _port, _uri.c_str()); - return true; -} - -#ifdef HTTPCLIENT_1_1_COMPATIBLE -bool HTTPClient::begin(String host, uint16_t port, String uri) -{ - if(_client && !_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } - - clear(); - _host = host; - _port = port; - _uri = uri; - _transportTraits = TransportTraitsPtr(new TransportTraits()); - log_d("host: %s port: %d uri: %s", host.c_str(), port, uri.c_str()); - return true; -} - -bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert) -{ - if(_client && !_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } - - clear(); - _host = host; - _port = port; - _uri = uri; - - if (strlen(CAcert) == 0) { - return false; - } - _secure = true; - _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert)); - return true; -} - -bool HTTPClient::begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key) -{ - if(_client && !_tcpDeprecated) { - log_d("mix up of new and deprecated api"); - _canReuse = false; - end(); - } - - clear(); - _host = host; - _port = port; - _uri = uri; - - if (strlen(CAcert) == 0) { - return false; - } - _secure = true; - _transportTraits = TransportTraitsPtr(new TLSTraits(CAcert, cli_cert, cli_key)); - return true; -} -#endif // HTTPCLIENT_1_1_COMPATIBLE - -/** - * end - * called after the payload is handled - */ -void HTTPClient::end(void) -{ - disconnect(false); - clear(); -} - - - -/** - * disconnect - * close the TCP socket - */ -void HTTPClient::disconnect(bool preserveClient) -{ - if(connected()) { - if(_client->available() > 0) { - log_d("still data in buffer (%d), clean up.\n", _client->available()); - while(_client->available() > 0) { - _client->read(); - } - } - - if(_reuse && _canReuse) { - log_d("tcp keep open for reuse\n"); - } else { - log_d("tcp stop\n"); - _client->stop(); - if(!preserveClient) { - _client = nullptr; - } -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if(_tcpDeprecated) { - _transportTraits.reset(nullptr); - _tcpDeprecated.reset(nullptr); - } -#endif - } - } else { - log_d("tcp is closed\n"); - } -} - - -/** - * connected - * @return connected status - */ -bool HTTPClient::connected() -{ - if(_client) { - return ((_client->available() > 0) || _client->connected()); - } - return false; -} - -/** - * try to reuse the connection to the server - * keep-alive - * @param reuse bool - */ -void HTTPClient::setReuse(bool reuse) -{ - _reuse = reuse; -} - -/** - * set User Agent - * @param userAgent const char * - */ -void HTTPClient::setUserAgent(const String& userAgent) -{ - _userAgent = userAgent; -} - -/** - * set the Authorizatio for the http request - * @param user const char * - * @param password const char * - */ -void HTTPClient::setAuthorization(const char * user, const char * password) -{ - if(user && password) { - String auth = user; - auth += ":"; - auth += password; - _base64Authorization = base64::encode(auth); - } -} - -/** - * set the Authorizatio for the http request - * @param auth const char * base64 - */ -void HTTPClient::setAuthorization(const char * auth) -{ - if(auth) { - _base64Authorization = auth; - } -} - -/** - * set the timeout (ms) for establishing a connection to the server - * @param connectTimeout int32_t - */ -void HTTPClient::setConnectTimeout(int32_t connectTimeout) -{ - _connectTimeout = connectTimeout; -} - -/** - * set the timeout for the TCP connection - * @param timeout unsigned int - */ -void HTTPClient::setTimeout(uint16_t timeout) -{ - _tcpTimeout = timeout; - if(connected()) { - _client->setTimeout((timeout + 500) / 1000); - } -} - -/** - * use HTTP1.0 - * @param use - */ -void HTTPClient::useHTTP10(bool useHTTP10) -{ - _useHTTP10 = useHTTP10; - _reuse = !useHTTP10; -} - -/** - * send a GET request - * @return http code - */ -int HTTPClient::GET() -{ - return sendRequest("GET"); -} - -/** - * sends a post request to the server - * @param payload uint8_t * - * @param size size_t - * @return http code - */ -int HTTPClient::POST(uint8_t * payload, size_t size) -{ - return sendRequest("POST", payload, size); -} - -int HTTPClient::POST(String payload) -{ - return POST((uint8_t *) payload.c_str(), payload.length()); -} - -/** - * sends a patch request to the server - * @param payload uint8_t * - * @param size size_t - * @return http code - */ -int HTTPClient::PATCH(uint8_t * payload, size_t size) -{ - return sendRequest("PATCH", payload, size); -} - -int HTTPClient::PATCH(String payload) -{ - return PATCH((uint8_t *) payload.c_str(), payload.length()); -} - -/** - * sends a put request to the server - * @param payload uint8_t * - * @param size size_t - * @return http code - */ -int HTTPClient::PUT(uint8_t * payload, size_t size) { - return sendRequest("PUT", payload, size); -} - -int HTTPClient::PUT(String payload) { - return PUT((uint8_t *) payload.c_str(), payload.length()); -} - -/** - * sendRequest - * @param type const char * "GET", "POST", .... - * @param payload String data for the message body - * @return - */ -int HTTPClient::sendRequest(const char * type, String payload) -{ - return sendRequest(type, (uint8_t *) payload.c_str(), payload.length()); -} - -/** - * sendRequest - * @param type const char * "GET", "POST", .... - * @param payload uint8_t * data for the message body if null not send - * @param size size_t size for the message body if 0 not send - * @return -1 if no info or > 0 when Content-Length is set by server - */ -int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) -{ - int code; - bool redirect = false; - uint16_t redirectCount = 0; - do { - // wipe out any existing headers from previous request - for(size_t i = 0; i < _headerKeysCount; i++) { - if (_currentHeaders[i].value.length() > 0) { - _currentHeaders[i].value.clear(); - } - } - - log_d("request type: '%s' redirCount: %d\n", type, redirectCount); - - // connect to server - if(!connect()) { - return returnError(HTTPC_ERROR_CONNECTION_REFUSED); - } - - if(payload && size > 0) { - addHeader(F("Content-Length"), String(size)); - } - - // send Header - if(!sendHeader(type)) { - return returnError(HTTPC_ERROR_SEND_HEADER_FAILED); - } - - // send Payload if needed - if(payload && size > 0) { - if(_client->write(&payload[0], size) != size) { - return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); - } - } - - code = handleHeaderResponse(); - log_d("sendRequest code=%d\n", code); - - // Handle redirections as stated in RFC document: - // https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html - // - // Implementing HTTP_CODE_FOUND as redirection with GET method, - // to follow most of existing user agent implementations. - // - redirect = false; - if ( - _followRedirects != HTTPC_DISABLE_FOLLOW_REDIRECTS && - redirectCount < _redirectLimit && - _location.length() > 0 - ) { - switch (code) { - // redirecting using the same method - case HTTP_CODE_MOVED_PERMANENTLY: - case HTTP_CODE_TEMPORARY_REDIRECT: { - if ( - // allow to force redirections on other methods - // (the RFC require user to accept the redirection) - _followRedirects == HTTPC_FORCE_FOLLOW_REDIRECTS || - // allow GET and HEAD methods without force - !strcmp(type, "GET") || - !strcmp(type, "HEAD") - ) { - redirectCount += 1; - log_d("following redirect (the same method): '%s' redirCount: %d\n", _location.c_str(), redirectCount); - if (!setURL(_location)) { - log_d("failed setting URL for redirection\n"); - // no redirection - break; - } - // redirect using the same request method and payload, diffrent URL - redirect = true; - } - break; - } - // redirecting with method dropped to GET or HEAD - // note: it does not need `HTTPC_FORCE_FOLLOW_REDIRECTS` for any method - case HTTP_CODE_FOUND: - case HTTP_CODE_SEE_OTHER: { - redirectCount += 1; - log_d("following redirect (dropped to GET/HEAD): '%s' redirCount: %d\n", _location.c_str(), redirectCount); - if (!setURL(_location)) { - log_d("failed setting URL for redirection\n"); - // no redirection - break; - } - // redirect after changing method to GET/HEAD and dropping payload - type = "GET"; - payload = nullptr; - size = 0; - redirect = true; - break; - } - - default: - break; - } - } - - } while (redirect); - // handle Server Response (Header) - return returnError(code); -} - -/** - * sendRequest - * @param type const char * "GET", "POST", .... - * @param stream Stream * data stream for the message body - * @param size size_t size for the message body if 0 not Content-Length is send - * @return -1 if no info or > 0 when Content-Length is set by server - */ -int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) -{ - - if(!stream) { - return returnError(HTTPC_ERROR_NO_STREAM); - } - - // connect to server - if(!connect()) { - return returnError(HTTPC_ERROR_CONNECTION_REFUSED); - } - - if(size > 0) { - addHeader("Content-Length", String(size)); - } - - // send Header - if(!sendHeader(type)) { - return returnError(HTTPC_ERROR_SEND_HEADER_FAILED); - } - - int buff_size = HTTP_TCP_BUFFER_SIZE; - - int len = size; - int bytesWritten = 0; - - if(len == 0) { - len = -1; - } - - // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE - if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) { - buff_size = len; - } - - // create buffer for read - uint8_t * buff = (uint8_t *) malloc(buff_size); - - if(buff) { - // read all data from stream and send it to server - while(connected() && (stream->available() > -1) && (len > 0 || len == -1)) { - - // get available data size - int sizeAvailable = stream->available(); - - if(sizeAvailable) { - - int readBytes = sizeAvailable; - - // read only the asked bytes - if(len > 0 && readBytes > len) { - readBytes = len; - } - - // not read more the buffer can handle - if(readBytes > buff_size) { - readBytes = buff_size; - } - - // read data - int bytesRead = stream->readBytes(buff, readBytes); - - // write it to Stream - int bytesWrite = _client->write((const uint8_t *) buff, bytesRead); - bytesWritten += bytesWrite; - - // are all Bytes a writen to stream ? - if(bytesWrite != bytesRead) { - log_d("short write, asked for %d but got %d retry...", bytesRead, bytesWrite); - - // check for write error - if(_client->getWriteError()) { - log_d("stream write error %d", _client->getWriteError()); - - //reset write error for retry - _client->clearWriteError(); - } - - // some time for the stream - delay(1); - - int leftBytes = (readBytes - bytesWrite); - - // retry to send the missed bytes - bytesWrite = _client->write((const uint8_t *) (buff + bytesWrite), leftBytes); - bytesWritten += bytesWrite; - - if(bytesWrite != leftBytes) { - // failed again - log_d("short write, asked for %d but got %d failed.", leftBytes, bytesWrite); - free(buff); - return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); - } - } - - // check for write error - if(_client->getWriteError()) { - log_d("stream write error %d", _client->getWriteError()); - free(buff); - return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); - } - - // count bytes to read left - if(len > 0) { - len -= readBytes; - } - - delay(0); - } else { - delay(1); - } - } - - free(buff); - - if(size && (int) size != bytesWritten) { - log_d("Stream payload bytesWritten %d and size %d mismatch!.", bytesWritten, size); - log_d("ERROR SEND PAYLOAD FAILED!"); - return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); - } else { - log_d("Stream payload written: %d", bytesWritten); - } - - } else { - log_d("too less ram! need %d", HTTP_TCP_BUFFER_SIZE); - return returnError(HTTPC_ERROR_TOO_LESS_RAM); - } - - // handle Server Response (Header) - return returnError(handleHeaderResponse()); -} - -/** - * size of message body / payload - * @return -1 if no info or > 0 when Content-Length is set by server - */ -int HTTPClient::getSize(void) -{ - return _size; -} - -/** - * returns the stream of the tcp connection - * @return WiFiClient - */ -WiFiClient& HTTPClient::getStream(void) -{ - if (connected()) { - return *_client; - } - - log_w("getStream: not connected"); - static WiFiClient empty; - return empty; -} - -/** - * returns a pointer to the stream of the tcp connection - * @return WiFiClient* - */ -WiFiClient* HTTPClient::getStreamPtr(void) -{ - if(connected()) { - return _client; - } - - log_w("getStreamPtr: not connected"); - return nullptr; -} - -/** - * write all message body / payload to Stream - * @param stream Stream * - * @return bytes written ( negative values are error codes ) - */ -int HTTPClient::writeToStream(Stream * stream) -{ - - if(!stream) { - return returnError(HTTPC_ERROR_NO_STREAM); - } - - if(!connected()) { - return returnError(HTTPC_ERROR_NOT_CONNECTED); - } - - // get length of document (is -1 when Server sends no Content-Length header) - int len = _size; - int ret = 0; - - if(_transferEncoding == HTTPC_TE_IDENTITY) { - ret = writeToStreamDataBlock(stream, len); - - // have we an error? - if(ret < 0) { - return returnError(ret); - } - } else if(_transferEncoding == HTTPC_TE_CHUNKED) { - int size = 0; - while(1) { - if(!connected()) { - return returnError(HTTPC_ERROR_CONNECTION_LOST); - } - String chunkHeader = _client->readStringUntil('\n'); - - if(chunkHeader.length() <= 0) { - return returnError(HTTPC_ERROR_READ_TIMEOUT); - } - - chunkHeader.trim(); // remove \r - - // read size of chunk - len = (uint32_t) strtol((const char *) chunkHeader.c_str(), NULL, 16); - size += len; - log_d(" read chunk len: %d", len); - - // data left? - if(len > 0) { - int r = writeToStreamDataBlock(stream, len); - if(r < 0) { - // error in writeToStreamDataBlock - return returnError(r); - } - ret += r; - } else { - - // if no length Header use global chunk size - if(_size <= 0) { - _size = size; - } - - // check if we have write all data out - if(ret != _size) { - return returnError(HTTPC_ERROR_STREAM_WRITE); - } - break; - } - - // read trailing \r\n at the end of the chunk - char buf[2]; - auto trailing_seq_len = _client->readBytes((uint8_t*)buf, 2); - if (trailing_seq_len != 2 || buf[0] != '\r' || buf[1] != '\n') { - return returnError(HTTPC_ERROR_READ_TIMEOUT); - } - - delay(0); - } - } else { - return returnError(HTTPC_ERROR_ENCODING); - } - -// end(); - disconnect(true); - return ret; -} - -/** - * return all payload as String (may need lot of ram or trigger out of memory!) - * @return String - */ -String HTTPClient::getString(void) -{ - // _size can be -1 when Server sends no Content-Length header - if(_size > 0 || _size == -1) { - StreamString sstring; - // try to reserve needed memory (noop if _size == -1) - if(sstring.reserve((_size + 1))) { - writeToStream(&sstring); - return sstring; - } else { - log_d("not enough memory to reserve a string! need: %d", (_size + 1)); - } - } - - return ""; -} - -/** - * converts error code to String - * @param error int - * @return String - */ -String HTTPClient::errorToString(int error) -{ - switch(error) { - case HTTPC_ERROR_CONNECTION_REFUSED: - return F("connection refused"); - case HTTPC_ERROR_SEND_HEADER_FAILED: - return F("send header failed"); - case HTTPC_ERROR_SEND_PAYLOAD_FAILED: - return F("send payload failed"); - case HTTPC_ERROR_NOT_CONNECTED: - return F("not connected"); - case HTTPC_ERROR_CONNECTION_LOST: - return F("connection lost"); - case HTTPC_ERROR_NO_STREAM: - return F("no stream"); - case HTTPC_ERROR_NO_HTTP_SERVER: - return F("no HTTP server"); - case HTTPC_ERROR_TOO_LESS_RAM: - return F("too less ram"); - case HTTPC_ERROR_ENCODING: - return F("Transfer-Encoding not supported"); - case HTTPC_ERROR_STREAM_WRITE: - return F("Stream write error"); - case HTTPC_ERROR_READ_TIMEOUT: - return F("read Timeout"); - default: - return String(); - } -} - -/** - * adds Header to the request - * @param name - * @param value - * @param first - */ -void HTTPClient::addHeader(const String& name, const String& value, bool first, bool replace) -{ - // not allow set of Header handled by code - if(!name.equalsIgnoreCase(F("Connection")) && - !name.equalsIgnoreCase(F("User-Agent")) && - !name.equalsIgnoreCase(F("Host")) && - !(name.equalsIgnoreCase(F("Authorization")) && _base64Authorization.length())){ - - String headerLine = name; - headerLine += ": "; - - if (replace) { - int headerStart = _headers.indexOf(headerLine); - if (headerStart != -1 && (headerStart == 0 || _headers[headerStart - 1] == '\n')) { - int headerEnd = _headers.indexOf('\n', headerStart); - _headers = _headers.substring(0, headerStart) + _headers.substring(headerEnd + 1); - } - } - - headerLine += value; - headerLine += "\r\n"; - if(first) { - _headers = headerLine + _headers; - } else { - _headers += headerLine; - } - } -} - -void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKeysCount) -{ - _headerKeysCount = headerKeysCount; - if(_currentHeaders) { - delete[] _currentHeaders; - } - _currentHeaders = new RequestArgument[_headerKeysCount]; - for(size_t i = 0; i < _headerKeysCount; i++) { - _currentHeaders[i].key = headerKeys[i]; - } -} - -String HTTPClient::header(const char* name) -{ - for(size_t i = 0; i < _headerKeysCount; ++i) { - if(_currentHeaders[i].key == name) { - return _currentHeaders[i].value; - } - } - return String(); -} - -String HTTPClient::header(size_t i) -{ - if(i < _headerKeysCount) { - return _currentHeaders[i].value; - } - return String(); -} - -String HTTPClient::headerName(size_t i) -{ - if(i < _headerKeysCount) { - return _currentHeaders[i].key; - } - return String(); -} - -int HTTPClient::headers() -{ - return _headerKeysCount; -} - -bool HTTPClient::hasHeader(const char* name) -{ - for(size_t i = 0; i < _headerKeysCount; ++i) { - if((_currentHeaders[i].key == name) && (_currentHeaders[i].value.length() > 0)) { - return true; - } - } - return false; -} - -/** - * init TCP connection and handle ssl verify if needed - * @return true if connection is ok - */ -bool HTTPClient::connect(void) -{ - if(connected()) { - if(_reuse) { - log_d("already connected, reusing connection"); - } else { - log_d("already connected, try reuse!"); - } - while(_client->available() > 0) { - _client->read(); - } - return true; - } - -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if(_transportTraits && !_client) { - _tcpDeprecated = _transportTraits->create(); - if(!_tcpDeprecated) { - log_e("failed to create client"); - return false; - } - _client = _tcpDeprecated.get(); - } -#endif - - if (!_client) { - log_d("HTTPClient::begin was not called or returned error"); - return false; - } -#ifdef HTTPCLIENT_1_1_COMPATIBLE - if (_tcpDeprecated && !_transportTraits->verify(*_client, _host.c_str())) { - log_d("transport level verify failed"); - _client->stop(); - return false; - } -#endif - if(!_client->connect(_host.c_str(), _port, _connectTimeout)) { - log_d("failed connect to %s:%u", _host.c_str(), _port); - return false; - } - - // set Timeout for WiFiClient and for Stream::readBytesUntil() and Stream::readStringUntil() - _client->setTimeout((_tcpTimeout + 500) / 1000); - - log_d(" connected to %s:%u", _host.c_str(), _port); - - -/* -#ifdef ESP8266 - _client->setNoDelay(true); -#endif - */ - return connected(); -} - -/** - * sends HTTP request header - * @param type (GET, POST, ...) - * @return status - */ -bool HTTPClient::sendHeader(const char * type) -{ - if(!connected()) { - return false; - } - - String header = String(type) + " " + _uri + F(" HTTP/1."); - - if(_useHTTP10) { - header += "0"; - } else { - header += "1"; - } - - header += String(F("\r\nHost: ")) + _host; - if (_port != 80 && _port != 443) - { - header += ':'; - header += String(_port); - } - header += String(F("\r\nUser-Agent: ")) + _userAgent + - F("\r\nConnection: "); - - if(_reuse) { - header += F("keep-alive"); - } else { - header += F("close"); - } - header += "\r\n"; - - if(!_useHTTP10) { - header += F("Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0\r\n"); - } - - if(_base64Authorization.length()) { - _base64Authorization.replace("\n", ""); - header += F("Authorization: Basic "); - header += _base64Authorization; - header += "\r\n"; - } - - header += _headers + "\r\n"; - - return (_client->write((const uint8_t *) header.c_str(), header.length()) == header.length()); -} - -/** - * reads the response from the server - * @return int http code - */ -int HTTPClient::handleHeaderResponse() -{ - - if(!connected()) { - return HTTPC_ERROR_NOT_CONNECTED; - } - - clear(); - - _canReuse = _reuse; - - String transferEncoding; - - _transferEncoding = HTTPC_TE_IDENTITY; - unsigned long lastDataTime = millis(); - bool firstLine = true; - - while(connected()) { - size_t len = _client->available(); - if(len > 0) { - String headerLine = _client->readStringUntil('\n'); - headerLine.trim(); // remove \r - - lastDataTime = millis(); - - log_v("RX: '%s'", headerLine.c_str()); - - if(firstLine) { - firstLine = false; - if(_canReuse && headerLine.startsWith("HTTP/1.")) { - _canReuse = (headerLine[sizeof "HTTP/1." - 1] != '0'); - } - int codePos = headerLine.indexOf(' ') + 1; - _returnCode = headerLine.substring(codePos, headerLine.indexOf(' ', codePos)).toInt(); - } else if(headerLine.indexOf(':')) { - String headerName = headerLine.substring(0, headerLine.indexOf(':')); - String headerValue = headerLine.substring(headerLine.indexOf(':') + 1); - headerValue.trim(); - - if(headerName.equalsIgnoreCase("Content-Length")) { - _size = headerValue.toInt(); - } - - if(_canReuse && headerName.equalsIgnoreCase("Connection")) { - if(headerValue.indexOf("close") >= 0 && headerValue.indexOf("keep-alive") < 0) { - _canReuse = false; - } - } - - if(headerName.equalsIgnoreCase("Transfer-Encoding")) { - transferEncoding = headerValue; - } - - if (headerName.equalsIgnoreCase("Location")) { - _location = headerValue; - } - - for(size_t i = 0; i < _headerKeysCount; i++) { - if(_currentHeaders[i].key.equalsIgnoreCase(headerName)) { - _currentHeaders[i].value = headerValue; - break; - } - } - } - - if(headerLine == "") { - log_d("code: %d", _returnCode); - - if(_size > 0) { - log_d("size: %d", _size); - } - - if(transferEncoding.length() > 0) { - log_d("Transfer-Encoding: %s", transferEncoding.c_str()); - if(transferEncoding.equalsIgnoreCase("chunked")) { - _transferEncoding = HTTPC_TE_CHUNKED; - } else { - return HTTPC_ERROR_ENCODING; - } - } else { - _transferEncoding = HTTPC_TE_IDENTITY; - } - - if(_returnCode) { - return _returnCode; - } else { - log_d("Remote host is not an HTTP Server!"); - return HTTPC_ERROR_NO_HTTP_SERVER; - } - } - - } else { - if((millis() - lastDataTime) > _tcpTimeout) { - return HTTPC_ERROR_READ_TIMEOUT; - } - delay(10); - } - } - - return HTTPC_ERROR_CONNECTION_LOST; -} - -/** - * write one Data Block to Stream - * @param stream Stream * - * @param size int - * @return < 0 = error >= 0 = size written - */ -int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) -{ - int buff_size = HTTP_TCP_BUFFER_SIZE; - int len = size; - int bytesWritten = 0; - - // if possible create smaller buffer then HTTP_TCP_BUFFER_SIZE - if((len > 0) && (len < HTTP_TCP_BUFFER_SIZE)) { - buff_size = len; - } - - // create buffer for read - uint8_t * buff = (uint8_t *) malloc(buff_size); - - if(buff) { - // read all data from server - while(connected() && (len > 0 || len == -1)) { - - // get available data size - size_t sizeAvailable = _client->available(); - - if(sizeAvailable) { - - int readBytes = sizeAvailable; - - // read only the asked bytes - if(len > 0 && readBytes > len) { - readBytes = len; - } - - // not read more the buffer can handle - if(readBytes > buff_size) { - readBytes = buff_size; - } - - // stop if no more reading - if (readBytes == 0) - break; - - // read data - int bytesRead = _client->readBytes(buff, readBytes); - - // write it to Stream - int bytesWrite = stream->write(buff, bytesRead); - bytesWritten += bytesWrite; - - // are all Bytes a writen to stream ? - if(bytesWrite != bytesRead) { - log_d("short write asked for %d but got %d retry...", bytesRead, bytesWrite); - - // check for write error - if(stream->getWriteError()) { - log_d("stream write error %d", stream->getWriteError()); - - //reset write error for retry - stream->clearWriteError(); - } - - // some time for the stream - delay(1); - - int leftBytes = (readBytes - bytesWrite); - - // retry to send the missed bytes - bytesWrite = stream->write((buff + bytesWrite), leftBytes); - bytesWritten += bytesWrite; - - if(bytesWrite != leftBytes) { - // failed again - log_w("short write asked for %d but got %d failed.", leftBytes, bytesWrite); - free(buff); - return HTTPC_ERROR_STREAM_WRITE; - } - } - - // check for write error - if(stream->getWriteError()) { - log_w("stream write error %d", stream->getWriteError()); - free(buff); - return HTTPC_ERROR_STREAM_WRITE; - } - - // count bytes to read left - if(len > 0) { - len -= readBytes; - } - - delay(0); - } else { - delay(1); - } - } - - free(buff); - - log_d("connection closed or file end (written: %d).", bytesWritten); - - if((size > 0) && (size != bytesWritten)) { - log_d("bytesWritten %d and size %d mismatch!.", bytesWritten, size); - return HTTPC_ERROR_STREAM_WRITE; - } - - } else { - log_w("too less ram! need %d", HTTP_TCP_BUFFER_SIZE); - return HTTPC_ERROR_TOO_LESS_RAM; - } - - return bytesWritten; -} - -/** - * called to handle error return, may disconnect the connection if still exists - * @param error - * @return error - */ -int HTTPClient::returnError(int error) -{ - if(error < 0) { - log_w("error(%d): %s", error, errorToString(error).c_str()); - if(connected()) { - log_d("tcp stop"); - _client->stop(); - } - } - return error; -} - -void HTTPClient::setFollowRedirects(followRedirects_t follow) -{ - _followRedirects = follow; -} - -void HTTPClient::setRedirectLimit(uint16_t limit) -{ - _redirectLimit = limit; -} - -/** - * set the URL to a new value. Handy for following redirects. - * @param url - */ -bool HTTPClient::setURL(const String& url) -{ - // if the new location is only a path then only update the URI - if (url && url[0] == '/') { - _uri = url; - clear(); - return true; - } - - if (!url.startsWith(_protocol + ':')) { - log_d("new URL not the same protocol, expected '%s', URL: '%s'\n", _protocol.c_str(), url.c_str()); - return false; - } - - // check if the port is specified - int indexPort = url.indexOf(':', 6); // find the first ':' excluding the one from the protocol - int indexURI = url.indexOf('/', 7); // find where the URI starts to make sure the ':' is not part of it - if (indexPort == -1 || indexPort > indexURI) { - // the port is not specified - _port = (_protocol == "https" ? 443 : 80); - } - - // disconnect but preserve _client. - // Also have to keep the connection otherwise it will free some of the memory used by _client - // and will blow up later when trying to do _client->available() or similar - _canReuse = true; - disconnect(true); - return beginInternal(url, _protocol.c_str()); -} - -const String &HTTPClient::getLocation(void) -{ - return _location; -} diff --git a/libraries/HTTPClient/src/HTTPClient.h b/libraries/HTTPClient/src/HTTPClient.h deleted file mode 100644 index 1b454e33..00000000 --- a/libraries/HTTPClient/src/HTTPClient.h +++ /dev/null @@ -1,270 +0,0 @@ -/** - * HTTPClient.h - * - * Created on: 02.11.2015 - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the HTTPClient for Arduino. - * Port to ESP32 by Evandro Luis Copercini (2017), - * changed fingerprints to CA verification. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef HTTPClient_H_ -#define HTTPClient_H_ - -#define HTTPCLIENT_1_1_COMPATIBLE - -#include -#include -#include -#include - -#define HTTPCLIENT_DEFAULT_TCP_TIMEOUT (5000) - -/// HTTP client errors -#define HTTPC_ERROR_CONNECTION_REFUSED (-1) -#define HTTPC_ERROR_SEND_HEADER_FAILED (-2) -#define HTTPC_ERROR_SEND_PAYLOAD_FAILED (-3) -#define HTTPC_ERROR_NOT_CONNECTED (-4) -#define HTTPC_ERROR_CONNECTION_LOST (-5) -#define HTTPC_ERROR_NO_STREAM (-6) -#define HTTPC_ERROR_NO_HTTP_SERVER (-7) -#define HTTPC_ERROR_TOO_LESS_RAM (-8) -#define HTTPC_ERROR_ENCODING (-9) -#define HTTPC_ERROR_STREAM_WRITE (-10) -#define HTTPC_ERROR_READ_TIMEOUT (-11) - -/// size for the stream handling -#define HTTP_TCP_BUFFER_SIZE (1460) - -/// HTTP codes see RFC7231 -typedef enum { - HTTP_CODE_CONTINUE = 100, - HTTP_CODE_SWITCHING_PROTOCOLS = 101, - HTTP_CODE_PROCESSING = 102, - HTTP_CODE_OK = 200, - HTTP_CODE_CREATED = 201, - HTTP_CODE_ACCEPTED = 202, - HTTP_CODE_NON_AUTHORITATIVE_INFORMATION = 203, - HTTP_CODE_NO_CONTENT = 204, - HTTP_CODE_RESET_CONTENT = 205, - HTTP_CODE_PARTIAL_CONTENT = 206, - HTTP_CODE_MULTI_STATUS = 207, - HTTP_CODE_ALREADY_REPORTED = 208, - HTTP_CODE_IM_USED = 226, - HTTP_CODE_MULTIPLE_CHOICES = 300, - HTTP_CODE_MOVED_PERMANENTLY = 301, - HTTP_CODE_FOUND = 302, - HTTP_CODE_SEE_OTHER = 303, - HTTP_CODE_NOT_MODIFIED = 304, - HTTP_CODE_USE_PROXY = 305, - HTTP_CODE_TEMPORARY_REDIRECT = 307, - HTTP_CODE_PERMANENT_REDIRECT = 308, - HTTP_CODE_BAD_REQUEST = 400, - HTTP_CODE_UNAUTHORIZED = 401, - HTTP_CODE_PAYMENT_REQUIRED = 402, - HTTP_CODE_FORBIDDEN = 403, - HTTP_CODE_NOT_FOUND = 404, - HTTP_CODE_METHOD_NOT_ALLOWED = 405, - HTTP_CODE_NOT_ACCEPTABLE = 406, - HTTP_CODE_PROXY_AUTHENTICATION_REQUIRED = 407, - HTTP_CODE_REQUEST_TIMEOUT = 408, - HTTP_CODE_CONFLICT = 409, - HTTP_CODE_GONE = 410, - HTTP_CODE_LENGTH_REQUIRED = 411, - HTTP_CODE_PRECONDITION_FAILED = 412, - HTTP_CODE_PAYLOAD_TOO_LARGE = 413, - HTTP_CODE_URI_TOO_LONG = 414, - HTTP_CODE_UNSUPPORTED_MEDIA_TYPE = 415, - HTTP_CODE_RANGE_NOT_SATISFIABLE = 416, - HTTP_CODE_EXPECTATION_FAILED = 417, - HTTP_CODE_MISDIRECTED_REQUEST = 421, - HTTP_CODE_UNPROCESSABLE_ENTITY = 422, - HTTP_CODE_LOCKED = 423, - HTTP_CODE_FAILED_DEPENDENCY = 424, - HTTP_CODE_UPGRADE_REQUIRED = 426, - HTTP_CODE_PRECONDITION_REQUIRED = 428, - HTTP_CODE_TOO_MANY_REQUESTS = 429, - HTTP_CODE_REQUEST_HEADER_FIELDS_TOO_LARGE = 431, - HTTP_CODE_INTERNAL_SERVER_ERROR = 500, - HTTP_CODE_NOT_IMPLEMENTED = 501, - HTTP_CODE_BAD_GATEWAY = 502, - HTTP_CODE_SERVICE_UNAVAILABLE = 503, - HTTP_CODE_GATEWAY_TIMEOUT = 504, - HTTP_CODE_HTTP_VERSION_NOT_SUPPORTED = 505, - HTTP_CODE_VARIANT_ALSO_NEGOTIATES = 506, - HTTP_CODE_INSUFFICIENT_STORAGE = 507, - HTTP_CODE_LOOP_DETECTED = 508, - HTTP_CODE_NOT_EXTENDED = 510, - HTTP_CODE_NETWORK_AUTHENTICATION_REQUIRED = 511 -} t_http_codes; - -typedef enum { - HTTPC_TE_IDENTITY, - HTTPC_TE_CHUNKED -} transferEncoding_t; - -/** - * redirection follow mode. - * + `HTTPC_DISABLE_FOLLOW_REDIRECTS` - no redirection will be followed. - * + `HTTPC_STRICT_FOLLOW_REDIRECTS` - strict RFC2616, only requests using - * GET or HEAD methods will be redirected (using the same method), - * since the RFC requires end-user confirmation in other cases. - * + `HTTPC_FORCE_FOLLOW_REDIRECTS` - all redirections will be followed, - * regardless of a used method. New request will use the same method, - * and they will include the same body data and the same headers. - * In the sense of the RFC, it's just like every redirection is confirmed. - */ -typedef enum { - HTTPC_DISABLE_FOLLOW_REDIRECTS, - HTTPC_STRICT_FOLLOW_REDIRECTS, - HTTPC_FORCE_FOLLOW_REDIRECTS -} followRedirects_t; - - -#ifdef HTTPCLIENT_1_1_COMPATIBLE -class TransportTraits; -typedef std::unique_ptr TransportTraitsPtr; -#endif - -class HTTPClient -{ -public: - HTTPClient(); - ~HTTPClient(); - -/* - * Since both begin() functions take a reference to client as a parameter, you need to - * ensure the client object lives the entire time of the HTTPClient - */ - bool begin(WiFiClient &client, String url); - bool begin(WiFiClient &client, String host, uint16_t port, String uri = "/", bool https = false); - -#ifdef HTTPCLIENT_1_1_COMPATIBLE - bool begin(String url); - bool begin(String url, const char* CAcert); - bool begin(String host, uint16_t port, String uri = "/"); - bool begin(String host, uint16_t port, String uri, const char* CAcert); - bool begin(String host, uint16_t port, String uri, const char* CAcert, const char* cli_cert, const char* cli_key); -#endif - - void end(void); - - bool connected(void); - - void setReuse(bool reuse); /// keep-alive - void setUserAgent(const String& userAgent); - void setAuthorization(const char * user, const char * password); - void setAuthorization(const char * auth); - void setConnectTimeout(int32_t connectTimeout); - void setTimeout(uint16_t timeout); - - // Redirections - void setFollowRedirects(followRedirects_t follow); - void setRedirectLimit(uint16_t limit); // max redirects to follow for a single request - - bool setURL(const String &url); - void useHTTP10(bool usehttp10 = true); - - /// request handling - int GET(); - int PATCH(uint8_t * payload, size_t size); - int PATCH(String payload); - int POST(uint8_t * payload, size_t size); - int POST(String payload); - int PUT(uint8_t * payload, size_t size); - int PUT(String payload); - int sendRequest(const char * type, String payload); - int sendRequest(const char * type, uint8_t * payload = NULL, size_t size = 0); - int sendRequest(const char * type, Stream * stream, size_t size = 0); - - void addHeader(const String& name, const String& value, bool first = false, bool replace = true); - - /// Response handling - void collectHeaders(const char* headerKeys[], const size_t headerKeysCount); - String header(const char* name); // get request header value by name - String header(size_t i); // get request header value by number - String headerName(size_t i); // get request header name by number - int headers(); // get header count - bool hasHeader(const char* name); // check if header exists - - - int getSize(void); - const String &getLocation(void); - - WiFiClient& getStream(void); - WiFiClient* getStreamPtr(void); - int writeToStream(Stream* stream); - String getString(void); - - static String errorToString(int error); - -protected: - struct RequestArgument { - String key; - String value; - }; - - bool beginInternal(String url, const char* expectedProtocol); - void disconnect(bool preserveClient = false); - void clear(); - int returnError(int error); - bool connect(void); - bool sendHeader(const char * type); - int handleHeaderResponse(); - int writeToStreamDataBlock(Stream * stream, int len); - - -#ifdef HTTPCLIENT_1_1_COMPATIBLE - TransportTraitsPtr _transportTraits; - std::unique_ptr _tcpDeprecated; -#endif - - WiFiClient* _client = nullptr; - - /// request handling - String _host; - uint16_t _port = 0; - int32_t _connectTimeout = -1; - bool _reuse = true; - uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT; - bool _useHTTP10 = false; - bool _secure = false; - - String _uri; - String _protocol; - String _headers; - String _userAgent = "ESP32HTTPClient"; - String _base64Authorization; - - /// Response handling - RequestArgument* _currentHeaders = nullptr; - size_t _headerKeysCount = 0; - - int _returnCode = 0; - int _size = -1; - bool _canReuse = false; - followRedirects_t _followRedirects = HTTPC_DISABLE_FOLLOW_REDIRECTS; - uint16_t _redirectLimit = 10; - String _location; - transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY; -}; - - - -#endif /* HTTPClient_H_ */ diff --git a/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino b/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino deleted file mode 100644 index e98a5851..00000000 --- a/libraries/HTTPUpdate/examples/httpUpdate/httpUpdate.ino +++ /dev/null @@ -1,72 +0,0 @@ -/** - httpUpdate.ino - - Created on: 27.11.2015 - -*/ - -#include - -#include -#include - -#include -#include - -WiFiMulti WiFiMulti; - -void setup() { - - Serial.begin(115200); - // Serial.setDebugOutput(true); - - Serial.println(); - Serial.println(); - Serial.println(); - - for (uint8_t t = 4; t > 0; t--) { - Serial.printf("[SETUP] WAIT %d...\n", t); - Serial.flush(); - delay(1000); - } - - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); - - -} - -void loop() { - // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - - WiFiClient client; - - // The line below is optional. It can be used to blink the LED on the board during flashing - // The LED will be on during download of one buffer of data from the network. The LED will - // be off during writing that buffer to flash - // On a good connection the LED should flash regularly. On a bad connection the LED will be - // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second - // value is used to put the LED on. If the LED is on with HIGH, that value should be passed - // httpUpdate.setLedPin(LED_BUILTIN, LOW); - - t_httpUpdate_return ret = httpUpdate.update(client, "http://server/file.bin"); - // Or: - //t_httpUpdate_return ret = httpUpdate.update(client, "server", 80, "/file.bin"); - - switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); - break; - - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; - - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; - } - } -} - diff --git a/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino b/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino deleted file mode 100644 index a07e6d2f..00000000 --- a/libraries/HTTPUpdate/examples/httpUpdateSPIFFS/httpUpdateSPIFFS.ino +++ /dev/null @@ -1,75 +0,0 @@ -/** - httpUpdateSPIFFS.ino - - Created on: 05.12.2015 - -*/ - -#include - -#include -#include - -#include -#include - -WiFiMulti WiFiMulti; - -void setup() { - - Serial.begin(115200); - // Serial.setDebugOutput(true); - - Serial.println(); - Serial.println(); - Serial.println(); - - for (uint8_t t = 4; t > 0; t--) { - Serial.printf("[SETUP] WAIT %d...\n", t); - Serial.flush(); - delay(1000); - } - - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); - -} - -void loop() { - // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - - Serial.println("Update SPIFFS..."); - - WiFiClient client; - - // The line below is optional. It can be used to blink the LED on the board during flashing - // The LED will be on during download of one buffer of data from the network. The LED will - // be off during writing that buffer to flash - // On a good connection the LED should flash regularly. On a bad connection the LED will be - // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second - // value is used to put the LED on. If the LED is on with HIGH, that value should be passed - // httpUpdate.setLedPin(LED_BUILTIN, LOW); - - t_httpUpdate_return ret = httpUpdate.updateSpiffs(client, "http://server/spiffs.bin"); - if (ret == HTTP_UPDATE_OK) { - Serial.println("Update sketch..."); - ret = httpUpdate.update(client, "http://server/file.bin"); - - switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); - break; - - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; - - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; - } - } - } -} - diff --git a/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino b/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino deleted file mode 100644 index 1c85ace0..00000000 --- a/libraries/HTTPUpdate/examples/httpUpdateSecure/httpUpdateSecure.ino +++ /dev/null @@ -1,128 +0,0 @@ -/** - httpUpdateSecure.ino - - Created on: 16.10.2018 as an adaptation of the ESP8266 version of httpUpdate.ino - -*/ - -#include -#include - -#include -#include - -#include - -WiFiMulti WiFiMulti; - -// Set time via NTP, as required for x.509 validation -void setClock() { - configTime(0, 0, "pool.ntp.org", "time.nist.gov"); // UTC - - Serial.print(F("Waiting for NTP time sync: ")); - time_t now = time(nullptr); - while (now < 8 * 3600 * 2) { - yield(); - delay(500); - Serial.print(F(".")); - now = time(nullptr); - } - - Serial.println(F("")); - struct tm timeinfo; - gmtime_r(&now, &timeinfo); - Serial.print(F("Current time: ")); - Serial.print(asctime(&timeinfo)); -} - -/** - * This is lets-encrypt-x3-cross-signed.pem - */ -const char* rootCACertificate = \ -"-----BEGIN CERTIFICATE-----\n" \ -"MIIEkjCCA3qgAwIBAgIQCgFBQgAAAVOFc2oLheynCDANBgkqhkiG9w0BAQsFADA/\n" \ -"MSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\n" \ -"DkRTVCBSb290IENBIFgzMB4XDTE2MDMxNzE2NDA0NloXDTIxMDMxNzE2NDA0Nlow\n" \ -"SjELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUxldCdzIEVuY3J5cHQxIzAhBgNVBAMT\n" \ -"GkxldCdzIEVuY3J5cHQgQXV0aG9yaXR5IFgzMIIBIjANBgkqhkiG9w0BAQEFAAOC\n" \ -"AQ8AMIIBCgKCAQEAnNMM8FrlLke3cl03g7NoYzDq1zUmGSXhvb418XCSL7e4S0EF\n" \ -"q6meNQhY7LEqxGiHC6PjdeTm86dicbp5gWAf15Gan/PQeGdxyGkOlZHP/uaZ6WA8\n" \ -"SMx+yk13EiSdRxta67nsHjcAHJyse6cF6s5K671B5TaYucv9bTyWaN8jKkKQDIZ0\n" \ -"Z8h/pZq4UmEUEz9l6YKHy9v6Dlb2honzhT+Xhq+w3Brvaw2VFn3EK6BlspkENnWA\n" \ -"a6xK8xuQSXgvopZPKiAlKQTGdMDQMc2PMTiVFrqoM7hD8bEfwzB/onkxEz0tNvjj\n" \ -"/PIzark5McWvxI0NHWQWM6r6hCm21AvA2H3DkwIDAQABo4IBfTCCAXkwEgYDVR0T\n" \ -"AQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAYYwfwYIKwYBBQUHAQEEczBxMDIG\n" \ -"CCsGAQUFBzABhiZodHRwOi8vaXNyZy50cnVzdGlkLm9jc3AuaWRlbnRydXN0LmNv\n" \ -"bTA7BggrBgEFBQcwAoYvaHR0cDovL2FwcHMuaWRlbnRydXN0LmNvbS9yb290cy9k\n" \ -"c3Ryb290Y2F4My5wN2MwHwYDVR0jBBgwFoAUxKexpHsscfrb4UuQdf/EFWCFiRAw\n" \ -"VAYDVR0gBE0wSzAIBgZngQwBAgEwPwYLKwYBBAGC3xMBAQEwMDAuBggrBgEFBQcC\n" \ -"ARYiaHR0cDovL2Nwcy5yb290LXgxLmxldHNlbmNyeXB0Lm9yZzA8BgNVHR8ENTAz\n" \ -"MDGgL6AthitodHRwOi8vY3JsLmlkZW50cnVzdC5jb20vRFNUUk9PVENBWDNDUkwu\n" \ -"Y3JsMB0GA1UdDgQWBBSoSmpjBH3duubRObemRWXv86jsoTANBgkqhkiG9w0BAQsF\n" \ -"AAOCAQEA3TPXEfNjWDjdGBX7CVW+dla5cEilaUcne8IkCJLxWh9KEik3JHRRHGJo\n" \ -"uM2VcGfl96S8TihRzZvoroed6ti6WqEBmtzw3Wodatg+VyOeph4EYpr/1wXKtx8/\n" \ -"wApIvJSwtmVi4MFU5aMqrSDE6ea73Mj2tcMyo5jMd6jmeWUHK8so/joWUoHOUgwu\n" \ -"X4Po1QYz+3dszkDqMp4fklxBwXRsW10KXzPMTZ+sOPAveyxindmjkW8lGy+QsRlG\n" \ -"PfZ+G6Z6h7mjem0Y+iWlkYcV4PIWL1iwBi8saCbGS5jN2p8M+X+Q7UNKEkROb3N6\n" \ -"KOqkqm57TH2H3eDJAkSnh6/DNFu0Qg==\n" \ -"-----END CERTIFICATE-----\n"; - -void setup() { - - Serial.begin(115200); - // Serial.setDebugOutput(true); - - Serial.println(); - Serial.println(); - Serial.println(); - - for (uint8_t t = 4; t > 0; t--) { - Serial.printf("[SETUP] WAIT %d...\n", t); - Serial.flush(); - delay(1000); - } - - WiFi.mode(WIFI_STA); - WiFiMulti.addAP("SSID", "PASSWORD"); -} - -void loop() { - // wait for WiFi connection - if ((WiFiMulti.run() == WL_CONNECTED)) { - - setClock(); - - WiFiClientSecure client; - client.setCACert(rootCACertificate); - - // Reading data over SSL may be slow, use an adequate timeout - client.setTimeout(12000 / 1000); // timeout argument is defined in seconds for setTimeout - - // The line below is optional. It can be used to blink the LED on the board during flashing - // The LED will be on during download of one buffer of data from the network. The LED will - // be off during writing that buffer to flash - // On a good connection the LED should flash regularly. On a bad connection the LED will be - // on much longer than it will be off. Other pins than LED_BUILTIN may be used. The second - // value is used to put the LED on. If the LED is on with HIGH, that value should be passed - // httpUpdate.setLedPin(LED_BUILTIN, HIGH); - - t_httpUpdate_return ret = httpUpdate.update(client, "https://server/file.bin"); - // Or: - //t_httpUpdate_return ret = httpUpdate.update(client, "server", 443, "/file.bin"); - - - switch (ret) { - case HTTP_UPDATE_FAILED: - Serial.printf("HTTP_UPDATE_FAILED Error (%d): %s\n", httpUpdate.getLastError(), httpUpdate.getLastErrorString().c_str()); - break; - - case HTTP_UPDATE_NO_UPDATES: - Serial.println("HTTP_UPDATE_NO_UPDATES"); - break; - - case HTTP_UPDATE_OK: - Serial.println("HTTP_UPDATE_OK"); - break; - } - } -} diff --git a/libraries/HTTPUpdate/keywords.txt b/libraries/HTTPUpdate/keywords.txt deleted file mode 100644 index 78be600d..00000000 --- a/libraries/HTTPUpdate/keywords.txt +++ /dev/null @@ -1,42 +0,0 @@ -####################################### -# Syntax Coloring Map For ESP8266httpUpdate -####################################### - -####################################### -# Library (KEYWORD3) -####################################### - -ESP8266httpUpdate KEYWORD3 RESERVED_WORD - -####################################### -# Datatypes (KEYWORD1) -####################################### - -HTTPUpdateResult KEYWORD1 DATA_TYPE -ESPhttpUpdate KEYWORD1 DATA_TYPE - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -rebootOnUpdate KEYWORD2 -update KEYWORD2 -updateSpiffs KEYWORD2 -getLastError KEYWORD2 -getLastErrorString KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - -HTTP_UE_TOO_LESS_SPACE LITERAL1 RESERVED_WORD_2 -HTTP_UE_SERVER_NOT_REPORT_SIZE LITERAL1 RESERVED_WORD_2 -HTTP_UE_SERVER_FILE_NOT_FOUND LITERAL1 RESERVED_WORD_2 -HTTP_UE_SERVER_FORBIDDEN LITERAL1 RESERVED_WORD_2 -HTTP_UE_SERVER_WRONG_HTTP_CODE LITERAL1 RESERVED_WORD_2 -HTTP_UE_SERVER_FAULTY_MD5 LITERAL1 RESERVED_WORD_2 -HTTP_UE_BIN_VERIFY_HEADER_FAILED LITERAL1 RESERVED_WORD_2 -HTTP_UE_BIN_FOR_WRONG_FLASH LITERAL1 RESERVED_WORD_2 -HTTP_UPDATE_FAILED LITERAL1 RESERVED_WORD_2 -HTTP_UPDATE_NO_UPDATES LITERAL1 RESERVED_WORD_2 -HTTP_UPDATE_OK LITERAL1 RESERVED_WORD_2 diff --git a/libraries/HTTPUpdate/library.properties b/libraries/HTTPUpdate/library.properties deleted file mode 100644 index 5147ddec..00000000 --- a/libraries/HTTPUpdate/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=HTTPUpdate -version=1.3 -author=Markus Sattler -maintainer=Markus Sattler -sentence=Http Update for ESP32 -paragraph= -category=Data Processing -url=https://github.com/Links2004/Arduino/tree/esp8266/hardware/esp8266com/esp8266/libraries/ESP8266httpUpdate -architectures=esp32 diff --git a/libraries/HTTPUpdate/src/HTTPUpdate.cpp b/libraries/HTTPUpdate/src/HTTPUpdate.cpp deleted file mode 100644 index f4c3d250..00000000 --- a/libraries/HTTPUpdate/src/HTTPUpdate.cpp +++ /dev/null @@ -1,417 +0,0 @@ -/** - * - * @file HTTPUpdate.cpp based om ESP8266HTTPUpdate.cpp - * @date 16.10.2018 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the ESP32 Http Updater. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#include "HTTPUpdate.h" -#include - -#include -#include // get running partition - -// To do extern "C" uint32_t _SPIFFS_start; -// To do extern "C" uint32_t _SPIFFS_end; - -HTTPUpdate::HTTPUpdate(void) - : _httpClientTimeout(8000), _ledPin(-1) -{ -} - -HTTPUpdate::HTTPUpdate(int httpClientTimeout) - : _httpClientTimeout(httpClientTimeout), _ledPin(-1) -{ -} - -HTTPUpdate::~HTTPUpdate(void) -{ -} - -HTTPUpdateResult HTTPUpdate::update(WiFiClient& client, const String& url, const String& currentVersion) -{ - HTTPClient http; - if(!http.begin(client, url)) - { - return HTTP_UPDATE_FAILED; - } - return handleUpdate(http, currentVersion, false); -} - -HTTPUpdateResult HTTPUpdate::updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion) -{ - HTTPClient http; - if(!http.begin(client, url)) - { - return HTTP_UPDATE_FAILED; - } - return handleUpdate(http, currentVersion, true); -} - -HTTPUpdateResult HTTPUpdate::update(WiFiClient& client, const String& host, uint16_t port, const String& uri, - const String& currentVersion) -{ - HTTPClient http; - if(!http.begin(client, host, port, uri)) - { - return HTTP_UPDATE_FAILED; - } - return handleUpdate(http, currentVersion, false); -} - -/** - * return error code as int - * @return int error code - */ -int HTTPUpdate::getLastError(void) -{ - return _lastError; -} - -/** - * return error code as String - * @return String error - */ -String HTTPUpdate::getLastErrorString(void) -{ - - if(_lastError == 0) { - return String(); // no error - } - - // error from Update class - if(_lastError > 0) { - StreamString error; - Update.printError(error); - error.trim(); // remove line ending - return String("Update error: ") + error; - } - - // error from http client - if(_lastError > -100) { - return String("HTTP error: ") + HTTPClient::errorToString(_lastError); - } - - switch(_lastError) { - case HTTP_UE_TOO_LESS_SPACE: - return "Not Enough space"; - case HTTP_UE_SERVER_NOT_REPORT_SIZE: - return "Server Did Not Report Size"; - case HTTP_UE_SERVER_FILE_NOT_FOUND: - return "File Not Found (404)"; - case HTTP_UE_SERVER_FORBIDDEN: - return "Forbidden (403)"; - case HTTP_UE_SERVER_WRONG_HTTP_CODE: - return "Wrong HTTP Code"; - case HTTP_UE_SERVER_FAULTY_MD5: - return "Wrong MD5"; - case HTTP_UE_BIN_VERIFY_HEADER_FAILED: - return "Verify Bin Header Failed"; - case HTTP_UE_BIN_FOR_WRONG_FLASH: - return "New Binary Does Not Fit Flash Size"; - case HTTP_UE_NO_PARTITION: - return "Partition Could Not be Found"; - } - - return String(); -} - - -String getSketchSHA256() { - const size_t HASH_LEN = 32; // SHA-256 digest length - - uint8_t sha_256[HASH_LEN] = { 0 }; - -// get sha256 digest for running partition - if(esp_partition_get_sha256(esp_ota_get_running_partition(), sha_256) == 0) { - char buffer[2 * HASH_LEN + 1]; - - for(size_t index = 0; index < HASH_LEN; index++) { - uint8_t nibble = (sha_256[index] & 0xf0) >> 4; - buffer[2 * index] = nibble < 10 ? char(nibble + '0') : char(nibble - 10 + 'A'); - - nibble = sha_256[index] & 0x0f; - buffer[2 * index + 1] = nibble < 10 ? char(nibble + '0') : char(nibble - 10 + 'A'); - } - - buffer[2 * HASH_LEN] = '\0'; - - return String(buffer); - } else { - - return String(); - } -} - -/** - * - * @param http HTTPClient * - * @param currentVersion const char * - * @return HTTPUpdateResult - */ -HTTPUpdateResult HTTPUpdate::handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs) -{ - - HTTPUpdateResult ret = HTTP_UPDATE_FAILED; - - // use HTTP/1.0 for update since the update handler not support any transfer Encoding - http.useHTTP10(true); - http.setTimeout(_httpClientTimeout); - http.setUserAgent("ESP32-http-Update"); - http.addHeader("Cache-Control", "no-cache"); - http.addHeader("x-ESP32-STA-MAC", WiFi.macAddress()); - http.addHeader("x-ESP32-AP-MAC", WiFi.softAPmacAddress()); - http.addHeader("x-ESP32-free-space", String(ESP.getFreeSketchSpace())); - http.addHeader("x-ESP32-sketch-size", String(ESP.getSketchSize())); - String sketchMD5 = ESP.getSketchMD5(); - if(sketchMD5.length() != 0) { - http.addHeader("x-ESP32-sketch-md5", sketchMD5); - } - // Add also a SHA256 - String sketchSHA256 = getSketchSHA256(); - if(sketchSHA256.length() != 0) { - http.addHeader("x-ESP32-sketch-sha256", sketchSHA256); - } - http.addHeader("x-ESP32-chip-size", String(ESP.getFlashChipSize())); - http.addHeader("x-ESP32-sdk-version", ESP.getSdkVersion()); - - if(spiffs) { - http.addHeader("x-ESP32-mode", "spiffs"); - } else { - http.addHeader("x-ESP32-mode", "sketch"); - } - - if(currentVersion && currentVersion[0] != 0x00) { - http.addHeader("x-ESP32-version", currentVersion); - } - - const char * headerkeys[] = { "x-MD5" }; - size_t headerkeyssize = sizeof(headerkeys) / sizeof(char*); - - // track these headers - http.collectHeaders(headerkeys, headerkeyssize); - - - int code = http.GET(); - int len = http.getSize(); - - if(code <= 0) { - log_e("HTTP error: %s\n", http.errorToString(code).c_str()); - _lastError = code; - http.end(); - return HTTP_UPDATE_FAILED; - } - - - log_d("Header read fin.\n"); - log_d("Server header:\n"); - log_d(" - code: %d\n", code); - log_d(" - len: %d\n", len); - - if(http.hasHeader("x-MD5")) { - log_d(" - MD5: %s\n", http.header("x-MD5").c_str()); - } - - log_d("ESP32 info:\n"); - log_d(" - free Space: %d\n", ESP.getFreeSketchSpace()); - log_d(" - current Sketch Size: %d\n", ESP.getSketchSize()); - - if(currentVersion && currentVersion[0] != 0x00) { - log_d(" - current version: %s\n", currentVersion.c_str() ); - } - - switch(code) { - case HTTP_CODE_OK: ///< OK (Start Update) - if(len > 0) { - bool startUpdate = true; - if(spiffs) { - const esp_partition_t* _partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, ESP_PARTITION_SUBTYPE_DATA_SPIFFS, NULL); - if(!_partition){ - _lastError = HTTP_UE_NO_PARTITION; - return HTTP_UPDATE_FAILED; - } - - if(len > _partition->size) { - log_e("spiffsSize to low (%d) needed: %d\n", _partition->size, len); - startUpdate = false; - } - } else { - int sketchFreeSpace = ESP.getFreeSketchSpace(); - if(!sketchFreeSpace){ - _lastError = HTTP_UE_NO_PARTITION; - return HTTP_UPDATE_FAILED; - } - - if(len > sketchFreeSpace) { - log_e("FreeSketchSpace to low (%d) needed: %d\n", sketchFreeSpace, len); - startUpdate = false; - } - } - - if(!startUpdate) { - _lastError = HTTP_UE_TOO_LESS_SPACE; - ret = HTTP_UPDATE_FAILED; - } else { - - WiFiClient * tcp = http.getStreamPtr(); - -// To do? WiFiUDP::stopAll(); -// To do? WiFiClient::stopAllExcept(tcp); - - delay(100); - - int command; - - if(spiffs) { - command = U_SPIFFS; - log_d("runUpdate spiffs...\n"); - } else { - command = U_FLASH; - log_d("runUpdate flash...\n"); - } - - if(!spiffs) { -/* To do - uint8_t buf[4]; - if(tcp->peekBytes(&buf[0], 4) != 4) { - log_e("peekBytes magic header failed\n"); - _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; - http.end(); - return HTTP_UPDATE_FAILED; - } -*/ - - // check for valid first magic byte -// if(buf[0] != 0xE9) { - if(tcp->peek() != 0xE9) { - log_e("Magic header does not start with 0xE9\n"); - _lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED; - http.end(); - return HTTP_UPDATE_FAILED; - - } -/* To do - uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4); - - // check if new bin fits to SPI flash - if(bin_flash_size > ESP.getFlashChipRealSize()) { - log_e("New binary does not fit SPI Flash size\n"); - _lastError = HTTP_UE_BIN_FOR_WRONG_FLASH; - http.end(); - return HTTP_UPDATE_FAILED; - } -*/ - } - if(runUpdate(*tcp, len, http.header("x-MD5"), command)) { - ret = HTTP_UPDATE_OK; - log_d("Update ok\n"); - http.end(); - - if(_rebootOnUpdate && !spiffs) { - ESP.restart(); - } - - } else { - ret = HTTP_UPDATE_FAILED; - log_e("Update failed\n"); - } - } - } else { - _lastError = HTTP_UE_SERVER_NOT_REPORT_SIZE; - ret = HTTP_UPDATE_FAILED; - log_e("Content-Length was 0 or wasn't set by Server?!\n"); - } - break; - case HTTP_CODE_NOT_MODIFIED: - ///< Not Modified (No updates) - ret = HTTP_UPDATE_NO_UPDATES; - break; - case HTTP_CODE_NOT_FOUND: - _lastError = HTTP_UE_SERVER_FILE_NOT_FOUND; - ret = HTTP_UPDATE_FAILED; - break; - case HTTP_CODE_FORBIDDEN: - _lastError = HTTP_UE_SERVER_FORBIDDEN; - ret = HTTP_UPDATE_FAILED; - break; - default: - _lastError = HTTP_UE_SERVER_WRONG_HTTP_CODE; - ret = HTTP_UPDATE_FAILED; - log_e("HTTP Code is (%d)\n", code); - break; - } - - http.end(); - return ret; -} - -/** - * write Update to flash - * @param in Stream& - * @param size uint32_t - * @param md5 String - * @return true if Update ok - */ -bool HTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command) -{ - - StreamString error; - - if(!Update.begin(size, command, _ledPin, _ledOn)) { - _lastError = Update.getError(); - Update.printError(error); - error.trim(); // remove line ending - log_e("Update.begin failed! (%s)\n", error.c_str()); - return false; - } - - if(md5.length()) { - if(!Update.setMD5(md5.c_str())) { - _lastError = HTTP_UE_SERVER_FAULTY_MD5; - log_e("Update.setMD5 failed! (%s)\n", md5.c_str()); - return false; - } - } - -// To do: the SHA256 could be checked if the server sends it - - if(Update.writeStream(in) != size) { - _lastError = Update.getError(); - Update.printError(error); - error.trim(); // remove line ending - log_e("Update.writeStream failed! (%s)\n", error.c_str()); - return false; - } - - if(!Update.end()) { - _lastError = Update.getError(); - Update.printError(error); - error.trim(); // remove line ending - log_e("Update.end failed! (%s)\n", error.c_str()); - return false; - } - - return true; -} - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) -HTTPUpdate httpUpdate; -#endif diff --git a/libraries/HTTPUpdate/src/HTTPUpdate.h b/libraries/HTTPUpdate/src/HTTPUpdate.h deleted file mode 100644 index f126cba0..00000000 --- a/libraries/HTTPUpdate/src/HTTPUpdate.h +++ /dev/null @@ -1,101 +0,0 @@ -/** - * - * @file HTTPUpdate.h based on ESP8266HTTPUpdate.h - * @date 16.10.2018 - * @author Markus Sattler - * - * Copyright (c) 2015 Markus Sattler. All rights reserved. - * This file is part of the ESP32 Http Updater. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA - * - */ - -#ifndef ___HTTP_UPDATE_H___ -#define ___HTTP_UPDATE_H___ - -#include -#include -#include -#include -#include -#include - -/// note we use HTTP client errors too so we start at 100 -#define HTTP_UE_TOO_LESS_SPACE (-100) -#define HTTP_UE_SERVER_NOT_REPORT_SIZE (-101) -#define HTTP_UE_SERVER_FILE_NOT_FOUND (-102) -#define HTTP_UE_SERVER_FORBIDDEN (-103) -#define HTTP_UE_SERVER_WRONG_HTTP_CODE (-104) -#define HTTP_UE_SERVER_FAULTY_MD5 (-105) -#define HTTP_UE_BIN_VERIFY_HEADER_FAILED (-106) -#define HTTP_UE_BIN_FOR_WRONG_FLASH (-107) -#define HTTP_UE_NO_PARTITION (-108) - -enum HTTPUpdateResult { - HTTP_UPDATE_FAILED, - HTTP_UPDATE_NO_UPDATES, - HTTP_UPDATE_OK -}; - -typedef HTTPUpdateResult t_httpUpdate_return; // backward compatibility - -class HTTPUpdate -{ -public: - HTTPUpdate(void); - HTTPUpdate(int httpClientTimeout); - ~HTTPUpdate(void); - - void rebootOnUpdate(bool reboot) - { - _rebootOnUpdate = reboot; - } - - void setLedPin(int ledPin = -1, uint8_t ledOn = HIGH) - { - _ledPin = ledPin; - _ledOn = ledOn; - } - - t_httpUpdate_return update(WiFiClient& client, const String& url, const String& currentVersion = ""); - - t_httpUpdate_return update(WiFiClient& client, const String& host, uint16_t port, const String& uri = "/", - const String& currentVersion = ""); - - t_httpUpdate_return updateSpiffs(WiFiClient& client, const String& url, const String& currentVersion = ""); - - - int getLastError(void); - String getLastErrorString(void); - -protected: - t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false); - bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH); - - int _lastError; - bool _rebootOnUpdate = true; -private: - int _httpClientTimeout; - - int _ledPin; - uint8_t _ledOn; -}; - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_HTTPUPDATE) -extern HTTPUpdate httpUpdate; -#endif - -#endif /* ___HTTP_UPDATE_H___ */ diff --git a/libraries/HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino b/libraries/HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino deleted file mode 100644 index f2503a7e..00000000 --- a/libraries/HTTPUpdateServer/examples/WebUpdater/WebUpdater.ino +++ /dev/null @@ -1,51 +0,0 @@ -/* - To upload through terminal you can use: curl -F "image=@firmware.bin" esp32-webupdate.local/update -*/ - -#include -#include -#include -#include -#include - -#ifndef STASSID -#define STASSID "your-ssid" -#define STAPSK "your-password" -#endif - -const char* host = "esp32-webupdate"; -const char* ssid = STASSID; -const char* password = STAPSK; - -WebServer httpServer(80); -HTTPUpdateServer httpUpdater; - -void setup(void) { - - Serial.begin(115200); - Serial.println(); - Serial.println("Booting Sketch..."); - WiFi.mode(WIFI_AP_STA); - WiFi.begin(ssid, password); - - while (WiFi.waitForConnectResult() != WL_CONNECTED) { - WiFi.begin(ssid, password); - Serial.println("WiFi failed, retrying."); - } - - MDNS.begin(host); - if (MDNS.begin("esp32")) { - Serial.println("mDNS responder started"); - } - - - httpUpdater.setup(&httpServer); - httpServer.begin(); - - MDNS.addService("http", "tcp", 80); - Serial.printf("HTTPUpdateServer ready! Open http://%s.local/update in your browser\n", host); -} - -void loop(void) { - httpServer.handleClient(); -} \ No newline at end of file diff --git a/libraries/HTTPUpdateServer/keywords.txt b/libraries/HTTPUpdateServer/keywords.txt deleted file mode 100644 index a6f8a0c1..00000000 --- a/libraries/HTTPUpdateServer/keywords.txt +++ /dev/null @@ -1,20 +0,0 @@ -####################################### -# Syntax Coloring Map For HTTPUpdateServer -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -ESP32HTTPUpdateServer KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -setup KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### \ No newline at end of file diff --git a/libraries/HTTPUpdateServer/library.properties b/libraries/HTTPUpdateServer/library.properties deleted file mode 100644 index 0601fd57..00000000 --- a/libraries/HTTPUpdateServer/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=HTTPUpdateServer -version=1.0 -author=Hristo Kapanakov -maintainer= -sentence=Simple HTTP Update server based on the WebServer -paragraph=The library accepts HTTP post requests to the /update url, and updates the ESP32 firmware. -category=Communication -url= -architectures=esp32 \ No newline at end of file diff --git a/libraries/HTTPUpdateServer/src/HTTPUpdateServer.h b/libraries/HTTPUpdateServer/src/HTTPUpdateServer.h deleted file mode 100644 index aa53ce6b..00000000 --- a/libraries/HTTPUpdateServer/src/HTTPUpdateServer.h +++ /dev/null @@ -1,166 +0,0 @@ -#ifndef __HTTP_UPDATE_SERVER_H -#define __HTTP_UPDATE_SERVER_H - -#include -#include -#include -#include - - -static const char serverIndex[] PROGMEM = -R"( - - - - - - -
- Firmware:
- - -
-
- FileSystem:
- - -
- - )"; -static const char successResponse[] PROGMEM = -"Update Success! Rebooting..."; - -class HTTPUpdateServer -{ -public: - HTTPUpdateServer(bool serial_debug=false) { - _serial_output = serial_debug; - _server = NULL; - _username = emptyString; - _password = emptyString; - _authenticated = false; - } - - void setup(WebServer *server) - { - setup(server, emptyString, emptyString); - } - - void setup(WebServer *server, const String& path) - { - setup(server, path, emptyString, emptyString); - } - - void setup(WebServer *server, const String& username, const String& password) - { - setup(server, "/update", username, password); - } - - void setup(WebServer *server, const String& path, const String& username, const String& password) - { - - _server = server; - _username = username; - _password = password; - - // handler for the /update form page - _server->on(path.c_str(), HTTP_GET, [&]() { - if (_username != emptyString && _password != emptyString && !_server->authenticate(_username.c_str(), _password.c_str())) - return _server->requestAuthentication(); - _server->send_P(200, PSTR("text/html"), serverIndex); - }); - - // handler for the /update form POST (once file upload finishes) - _server->on(path.c_str(), HTTP_POST, [&]() { - if (!_authenticated) - return _server->requestAuthentication(); - if (Update.hasError()) { - _server->send(200, F("text/html"), String(F("Update error: ")) + _updaterError); - } - else { - _server->client().setNoDelay(true); - _server->send_P(200, PSTR("text/html"), successResponse); - delay(100); - _server->client().stop(); - ESP.restart(); - } - }, [&]() { - // handler for the file upload, get's the sketch bytes, and writes - // them through the Update object - HTTPUpload& upload = _server->upload(); - - if (upload.status == UPLOAD_FILE_START) { - _updaterError.clear(); - if (_serial_output) - Serial.setDebugOutput(true); - - _authenticated = (_username == emptyString || _password == emptyString || _server->authenticate(_username.c_str(), _password.c_str())); - if (!_authenticated) { - if (_serial_output) - Serial.printf("Unauthenticated Update\n"); - return; - } - - if (_serial_output) - Serial.printf("Update: %s\n", upload.filename.c_str()); - if (upload.name == "filesystem") { - if (!Update.begin(SPIFFS.totalBytes(), U_SPIFFS)) {//start with max available size - if (_serial_output) Update.printError(Serial); - } - } - else { - uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; - if (!Update.begin(maxSketchSpace, U_FLASH)) {//start with max available size - _setUpdaterError(); - } - } - } - else if (_authenticated && upload.status == UPLOAD_FILE_WRITE && !_updaterError.length()) { - if (_serial_output) Serial.printf("."); - if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { - _setUpdaterError(); - } - } - else if (_authenticated && upload.status == UPLOAD_FILE_END && !_updaterError.length()) { - if (Update.end(true)) { //true to set the size to the current progress - if (_serial_output) Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize); - } - else { - _setUpdaterError(); - } - if (_serial_output) Serial.setDebugOutput(false); - } - else if (_authenticated && upload.status == UPLOAD_FILE_ABORTED) { - Update.end(); - if (_serial_output) Serial.println("Update was aborted"); - } - delay(0); - }); - } - - void updateCredentials(const String& username, const String& password) - { - _username = username; - _password = password; - } - -protected: - void _setUpdaterError() - { - if (_serial_output) Update.printError(Serial); - StreamString str; - Update.printError(str); - _updaterError = str.c_str(); - } - -private: - bool _serial_output; - WebServer *_server; - String _username; - String _password; - bool _authenticated; - String _updaterError; -}; - - -#endif \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/.gitignore b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/.gitignore deleted file mode 100644 index 87515a62..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/.gitignore +++ /dev/null @@ -1,4 +0,0 @@ -.pio -.vscode -mklittlefs.exe -mklittlefs \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/README.md b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/README.md deleted file mode 100644 index 773445b6..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/README.md +++ /dev/null @@ -1,68 +0,0 @@ -# How to run on PlatformIO IDE - -- Download and extract to this project root a **mklittlefs** executable for your OS [from a zipped binary here](https://github.com/earlephilhower/mklittlefs/releases) -- Open **LITTLEFS_PlatformIO** folder -- Run PlatformIO project task: **Upload Filesystem Image** -- Run PlatformIO project task: **Upload and Monitor** -- You will see a Serial output like: -``` ---- Miniterm on COM5 115200,8,N,1 --- ---- Quit: Ctrl+C | Menu: Ctrl+T | Help: Ctrl+T followed by Ctrl+H --- -ets Jun 8 2016 00:22:57 - -rst:0x1 (POWERON_RESET),boot:0x13 (Snfigsip: 0, SPIWP:0xee -clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 -mode:DIO, clock div:2 -load:0x3fff0018,len:4 -load:0x3fff001c,len:1044 -load:0x40078000,len:10044 -load:0x40080400,len:5872 -entry 0x400806ac -Listing directory: / - FILE: /file1.txt SIZE: 3 LAST WRITE: 2020-10-06 15:10:33 - DIR : /testfolder LAST WRITE: 2020-10-06 15:10:33 -Creating Dir: /mydir -Dir created -Writing file: /mydir/hello2.txt -- file written -Listing directory: / - FILE: /file1.txt SIZE: 3 LAST WRITE: 2020-10-06 15:10:33 - DIR : /mydir LAST WRITE: 1970-01-01 00:00:00 -Listing directory: /mydir - FILE: /mydir/hello2.txt SIZE: 6 LAST WRITE: 1970-01-01 00:00:00 - DIR : /testfolder LAST WRITE: 2020-10-06 15:10:33 -Listing directory: /testfolder - FILE: /testfolder/test2.txt SIZE: 3 LAST WRITE: 2020-10-06 15:10:33 -Deleting file: /mydir/hello2.txt -- file deleted -Removing Dir: /mydir -Dir removed -Listing directory: / - FILE: /file1.txt SIZE: 3 LAST WRITE: 2020-10-06 15:10:33 - DIR : /testfolder LAST WRITE: 2020-10-06 15:10:33 -Listing directory: /testfolder - FILE: /testfolder/test2.txt SIZE: 3 LAST WRITE: 2020-10-06 15:10:33 -Writing file: /hello.txt -- file written -Appending to file: /hello.txt -- message appended -Reading file: /hello.txt -- read from file: -Hello World! -Renaming file /hello.txt to /foo.txt -- file renamed -Reading file: /foo.txt -- read from file: -Hello World! -Deleting file: /foo.txt -- file deleted -Testing file I/O with /test.txt -- writing................................................................ - - 1048576 bytes written in 12006 ms -- reading................................................................ -- 1048576 bytes read in 547 ms -Deleting file: /test.txt -- file deleted -Test complete -``` -- If you have a module with more than 4MB flash, you can uncomment **partitions_custom.csv** in **platformio.ini** and modify the csv file accordingly \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/file1.txt b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/file1.txt deleted file mode 100644 index 7c4a013e..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/file1.txt +++ /dev/null @@ -1 +0,0 @@ -aaa \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/testfolder/test2.txt b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/testfolder/test2.txt deleted file mode 100644 index 01f02e32..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/data/testfolder/test2.txt +++ /dev/null @@ -1 +0,0 @@ -bbb \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/include/.placeholder.txt b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/include/.placeholder.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/lib/.placeholder.txt b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/lib/.placeholder.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/littlefsbuilder.py b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/littlefsbuilder.py deleted file mode 100644 index 93937e29..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/littlefsbuilder.py +++ /dev/null @@ -1,2 +0,0 @@ -Import("env") -env.Replace( MKSPIFFSTOOL=env.get("PROJECT_DIR") + '/mklittlefs' ) \ No newline at end of file diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/partitions_custom.csv b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/partitions_custom.csv deleted file mode 100644 index 97846fa5..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/partitions_custom.csv +++ /dev/null @@ -1,6 +0,0 @@ -# Name, Type, SubType, Offset, Size, Flags -ota_0, app, ota_0, 0x10000, 0x1A0000, -ota_1, app, ota_1, , 0x1A0000, -otadata, data, ota, 0x350000, 0x2000, -nvs, data, nvs, , 0x6000, -data, data, spiffs, , 0xA8000, diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/platformio.ini b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/platformio.ini deleted file mode 100644 index 43e34ec0..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/platformio.ini +++ /dev/null @@ -1,35 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; https://docs.platformio.org/page/projectconf.html - -[platformio] -default_envs = esp32 - -[env] -framework = arduino - -[env:esp32] -platform = espressif32 -;platform = https://github.com/platformio/platform-espressif32.git -;board_build.mcu = esp32 -platform_packages = framework-arduinoespressif32 @ https://github.com/espressif/arduino-esp32.git - -build_flags = - ${env.build_flags} - -D=${PIOENV} - ;-D CONFIG_LITTLEFS_FOR_IDF_3_2 - -lib_deps = https://github.com/lorol/LITTLEFS.git - -board = esp32dev -;board_build.partitions = partitions_custom.csv -monitor_filters = esp32_exception_decoder -monitor_speed = 115200 - -extra_scripts = ./littlefsbuilder.py diff --git a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/src/main.cpp b/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/src/main.cpp deleted file mode 100644 index fe601ef4..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_PlatformIO/src/main.cpp +++ /dev/null @@ -1,282 +0,0 @@ -#include -#include "FS.h" -#include -#include - -/* You only need to format LITTLEFS the first time you run a - test or else use the LITTLEFS plugin to create a partition - https://github.com/lorol/arduino-esp32littlefs-plugin */ - -#define FORMAT_LITTLEFS_IF_FAILED true - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\r\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("- failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println(" - not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - - Serial.print(file.name()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - - Serial.print(file.size()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\r\n", path); - - File file = fs.open(path); - if(!file || file.isDirectory()){ - Serial.println("- failed to open file for reading"); - return; - } - - Serial.println("- read from file:"); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\r\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\r\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("- failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("- message appended"); - } else { - Serial.println("- append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\r\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("- file renamed"); - } else { - Serial.println("- rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\r\n", path); - if(fs.remove(path)){ - Serial.println("- file deleted"); - } else { - Serial.println("- delete failed"); - } -} - -// SPIFFS-like write and delete file - -// See: https://github.com/esp8266/Arduino/blob/master/libraries/LittleFS/src/LittleFS.cpp#L60 -void writeFile2(fs::FS &fs, const char * path, const char * message){ - if(!fs.exists(path)){ - if (strchr(path, '/')) { - Serial.printf("Create missing folders of: %s\r\n", path); - char *pathStr = strdup(path); - if (pathStr) { - char *ptr = strchr(pathStr, '/'); - while (ptr) { - *ptr = 0; - fs.mkdir(pathStr); - *ptr = '/'; - ptr = strchr(ptr+1, '/'); - } - } - free(pathStr); - } - } - - Serial.printf("Writing file to: %s\r\n", path); - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -// See: https://github.com/esp8266/Arduino/blob/master/libraries/LittleFS/src/LittleFS.h#L149 -void deleteFile2(fs::FS &fs, const char * path){ - Serial.printf("Deleting file and empty folders on path: %s\r\n", path); - - if(fs.remove(path)){ - Serial.println("- file deleted"); - } else { - Serial.println("- delete failed"); - } - - char *pathStr = strdup(path); - if (pathStr) { - char *ptr = strrchr(pathStr, '/'); - if (ptr) { - Serial.printf("Removing all empty folders on path: %s\r\n", path); - } - while (ptr) { - *ptr = 0; - fs.rmdir(pathStr); - ptr = strrchr(pathStr, '/'); - } - free(pathStr); - } -} - -void testFileIO(fs::FS &fs, const char * path){ - Serial.printf("Testing file I/O with %s\r\n", path); - - static uint8_t buf[512]; - size_t len = 0; - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - - size_t i; - Serial.print("- writing" ); - uint32_t start = millis(); - for(i=0; i<2048; i++){ - if ((i & 0x001F) == 0x001F){ - Serial.print("."); - } - file.write(buf, 512); - } - Serial.println(""); - uint32_t end = millis() - start; - Serial.printf(" - %u bytes written in %u ms\r\n", 2048 * 512, end); - file.close(); - - file = fs.open(path); - start = millis(); - end = start; - i = 0; - if(file && !file.isDirectory()){ - len = file.size(); - size_t flen = len; - start = millis(); - Serial.print("- reading" ); - while(len){ - size_t toRead = len; - if(toRead > 512){ - toRead = 512; - } - file.read(buf, toRead); - if ((i++ & 0x001F) == 0x001F){ - Serial.print("."); - } - len -= toRead; - } - Serial.println(""); - end = millis() - start; - Serial.printf("- %u bytes read in %u ms\r\n", flen, end); - file.close(); - } else { - Serial.println("- failed to open file for reading"); - } -} - -void setup(){ - Serial.begin(115200); - if(!LITTLEFS.begin(FORMAT_LITTLEFS_IF_FAILED)){ - Serial.println("LITTLEFS Mount Failed"); - return; - } - - listDir(LITTLEFS, "/", 0); - createDir(LITTLEFS, "/mydir"); - writeFile(LITTLEFS, "/mydir/hello2.txt", "Hello2"); - //writeFile(LITTLEFS, "/mydir/newdir2/newdir3/hello3.txt", "Hello3"); - writeFile2(LITTLEFS, "/mydir/newdir2/newdir3/hello3.txt", "Hello3"); - listDir(LITTLEFS, "/", 3); - deleteFile(LITTLEFS, "/mydir/hello2.txt"); - //deleteFile(LITTLEFS, "/mydir/newdir2/newdir3/hello3.txt"); - deleteFile2(LITTLEFS, "/mydir/newdir2/newdir3/hello3.txt"); - removeDir(LITTLEFS, "/mydir"); - listDir(LITTLEFS, "/", 3); - writeFile(LITTLEFS, "/hello.txt", "Hello "); - appendFile(LITTLEFS, "/hello.txt", "World!\r\n"); - readFile(LITTLEFS, "/hello.txt"); - renameFile(LITTLEFS, "/hello.txt", "/foo.txt"); - readFile(LITTLEFS, "/foo.txt"); - deleteFile(LITTLEFS, "/foo.txt"); - testFileIO(LITTLEFS, "/test.txt"); - deleteFile(LITTLEFS, "/test.txt"); - - Serial.println( "Test complete" ); -} - -void loop(){ - -} diff --git a/libraries/LITTLEFS/examples/LITTLEFS_test/LITTLEFS_test.ino b/libraries/LITTLEFS/examples/LITTLEFS_test/LITTLEFS_test.ino deleted file mode 100644 index 528bfd18..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_test/LITTLEFS_test.ino +++ /dev/null @@ -1,272 +0,0 @@ -#include -#include "FS.h" -#include - -/* You only need to format LITTLEFS the first time you run a - test or else use the LITTLEFS plugin to create a partition - https://github.com/lorol/arduino-esp32littlefs-plugin */ - -#define FORMAT_LITTLEFS_IF_FAILED true - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\r\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("- failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println(" - not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.println(file.name()); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print("\tSIZE: "); - Serial.println(file.size()); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\r\n", path); - - File file = fs.open(path); - if(!file || file.isDirectory()){ - Serial.println("- failed to open file for reading"); - return; - } - - Serial.println("- read from file:"); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\r\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\r\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("- failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("- message appended"); - } else { - Serial.println("- append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\r\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("- file renamed"); - } else { - Serial.println("- rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\r\n", path); - if(fs.remove(path)){ - Serial.println("- file deleted"); - } else { - Serial.println("- delete failed"); - } -} - -// SPIFFS-like write and delete file - -// See: https://github.com/esp8266/Arduino/blob/master/libraries/LittleFS/src/LittleFS.cpp#L60 -void writeFile2(fs::FS &fs, const char * path, const char * message){ - if(!fs.exists(path)){ - if (strchr(path, '/')) { - Serial.printf("Create missing folders of: %s\r\n", path); - char *pathStr = strdup(path); - if (pathStr) { - char *ptr = strchr(pathStr, '/'); - while (ptr) { - *ptr = 0; - fs.mkdir(pathStr); - *ptr = '/'; - ptr = strchr(ptr+1, '/'); - } - } - free(pathStr); - } - } - - Serial.printf("Writing file to: %s\r\n", path); - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("- file written"); - } else { - Serial.println("- write failed"); - } - file.close(); -} - -// See: https://github.com/esp8266/Arduino/blob/master/libraries/LittleFS/src/LittleFS.h#L149 -void deleteFile2(fs::FS &fs, const char * path){ - Serial.printf("Deleting file and empty folders on path: %s\r\n", path); - - if(fs.remove(path)){ - Serial.println("- file deleted"); - } else { - Serial.println("- delete failed"); - } - - char *pathStr = strdup(path); - if (pathStr) { - char *ptr = strrchr(pathStr, '/'); - if (ptr) { - Serial.printf("Removing all empty folders on path: %s\r\n", path); - } - while (ptr) { - *ptr = 0; - fs.rmdir(pathStr); - ptr = strrchr(pathStr, '/'); - } - free(pathStr); - } -} - -void testFileIO(fs::FS &fs, const char * path){ - Serial.printf("Testing file I/O with %s\r\n", path); - - static uint8_t buf[512]; - size_t len = 0; - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("- failed to open file for writing"); - return; - } - - size_t i; - Serial.print("- writing" ); - uint32_t start = millis(); - for(i=0; i<2048; i++){ - if ((i & 0x001F) == 0x001F){ - Serial.print("."); - } - file.write(buf, 512); - } - Serial.println(""); - uint32_t end = millis() - start; - Serial.printf(" - %u bytes written in %u ms\r\n", 2048 * 512, end); - file.close(); - - file = fs.open(path); - start = millis(); - end = start; - i = 0; - if(file && !file.isDirectory()){ - len = file.size(); - size_t flen = len; - start = millis(); - Serial.print("- reading" ); - while(len){ - size_t toRead = len; - if(toRead > 512){ - toRead = 512; - } - file.read(buf, toRead); - if ((i++ & 0x001F) == 0x001F){ - Serial.print("."); - } - len -= toRead; - } - Serial.println(""); - end = millis() - start; - Serial.printf("- %u bytes read in %u ms\r\n", flen, end); - file.close(); - } else { - Serial.println("- failed to open file for reading"); - } -} - -void setup(){ - Serial.begin(115200); - if(!LITTLEFS.begin(FORMAT_LITTLEFS_IF_FAILED)){ - Serial.println("LITTLEFS Mount Failed"); - return; - } - Serial.println( "SPIFFS-like write file to new path and delete it w/folders" ); - writeFile2(LITTLEFS, "/new1/new2/new3/hello3.txt", "Hello3"); - listDir(LITTLEFS, "/", 3); - deleteFile2(LITTLEFS, "/new1/new2/new3/hello3.txt"); - - listDir(LITTLEFS, "/", 3); - createDir(LITTLEFS, "/mydir"); - writeFile(LITTLEFS, "/mydir/hello2.txt", "Hello2"); - listDir(LITTLEFS, "/", 1); - deleteFile(LITTLEFS, "/mydir/hello2.txt"); - removeDir(LITTLEFS, "/mydir"); - listDir(LITTLEFS, "/", 1); - writeFile(LITTLEFS, "/hello.txt", "Hello "); - appendFile(LITTLEFS, "/hello.txt", "World!\r\n"); - readFile(LITTLEFS, "/hello.txt"); - renameFile(LITTLEFS, "/hello.txt", "/foo.txt"); - readFile(LITTLEFS, "/foo.txt"); - deleteFile(LITTLEFS, "/foo.txt"); - testFileIO(LITTLEFS, "/test.txt"); - deleteFile(LITTLEFS, "/test.txt"); - - Serial.println( "Test complete" ); -} - -void loop(){ - -} diff --git a/libraries/LITTLEFS/examples/LITTLEFS_time/LITTLEFS_time.ino b/libraries/LITTLEFS/examples/LITTLEFS_time/LITTLEFS_time.ino deleted file mode 100644 index d4f4aaf1..00000000 --- a/libraries/LITTLEFS/examples/LITTLEFS_time/LITTLEFS_time.ino +++ /dev/null @@ -1,214 +0,0 @@ -#include "FS.h" -//#include "SPIFFS.h" -#include "LITTLEFS.h" -#include -#include - -#define SPIFFS LITTLEFS - -/* This examples uses "quick re-define" of SPIFFS to run - an existing sketch with LITTLEFS instead of SPIFFS - - You only need to format LITTLEFS the first time you run a - test or else use the LITTLEFS plugin to create a partition - https://github.com/lorol/arduino-esp32littlefs-plugin */ - -#define FORMAT_LITTLEFS_IF_FAILED true - -const char* ssid = "yourssid"; -const char* password = "yourpass"; - -long timezone = 1; -byte daysavetime = 1; - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.print (file.name()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.print(file.size()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void setup(){ - Serial.begin(115200); - // We start by connecting to a WiFi network - Serial.println(); - Serial.println(); - Serial.print("Connecting to "); - Serial.println(ssid); - - WiFi.begin(ssid, password); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - Serial.println("Contacting Time Server"); - configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); - struct tm tmstruct ; - delay(2000); - tmstruct.tm_year = 0; - getLocalTime(&tmstruct, 5000); - Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec); - Serial.println(""); - - if(!SPIFFS.begin(FORMAT_LITTLEFS_IF_FAILED)){ - Serial.println("LITTLEFS Mount Failed"); - return; - } - - Serial.println("----list 1----"); - listDir(SPIFFS, "/", 1); - - Serial.println("----remove old dir----"); - removeDir(SPIFFS, "/mydir"); - - Serial.println("----create a new dir----"); - createDir(SPIFFS, "/mydir"); - - Serial.println("----remove the new dir----"); - removeDir(SPIFFS, "/mydir"); - - Serial.println("----create the new again----"); - createDir(SPIFFS, "/mydir"); - - Serial.println("----create and work with file----"); - writeFile(SPIFFS, "/mydir/hello.txt", "Hello "); - appendFile(SPIFFS, "/mydir/hello.txt", "World!\n"); - - Serial.println("----list 2----"); - listDir(SPIFFS, "/", 1); - - Serial.println("----attempt to remove dir w/ file----"); - removeDir(SPIFFS, "/mydir"); - - Serial.println("----remove dir after deleting file----"); - deleteFile(SPIFFS, "/mydir/hello.txt"); - removeDir(SPIFFS, "/mydir"); - - Serial.println("----list 3----"); - listDir(SPIFFS, "/", 1); - - Serial.println( "Test complete" ); - -} - -void loop(){ - -} diff --git a/libraries/LITTLEFS/library.properties b/libraries/LITTLEFS/library.properties deleted file mode 100644 index 1b7a7bca..00000000 --- a/libraries/LITTLEFS/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=LITTLEFS -version=2.0 -author= -maintainer= -sentence=LittleFS for esp32 -paragraph=LittleFS for esp32 -category=Data Storage -url= -architectures=esp32 diff --git a/libraries/LITTLEFS/src/LITTLEFS.cpp b/libraries/LITTLEFS/src/LITTLEFS.cpp deleted file mode 100644 index 4d8e8d67..00000000 --- a/libraries/LITTLEFS/src/LITTLEFS.cpp +++ /dev/null @@ -1,107 +0,0 @@ -// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -static constexpr const char LFS_NAME[] = "spiffs"; - -#include "vfs_api.h" - -extern "C" { -#include -#include -#include -#undef B110 -#undef B1000000 -#include "esp_littlefs.h" -} - -#include "LITTLEFS.h" - -using namespace fs; - -LITTLEFSFS::LITTLEFSFS() : FS(FSImplPtr(new VFSImpl())) -{ - -} - -bool LITTLEFSFS::begin(bool formatOnFail, const char * basePath, uint8_t maxOpenFilesUnused) -{ - if(esp_littlefs_mounted(LFS_NAME)){ - log_w("LITTLEFS Already Mounted!"); - return true; - } - - esp_vfs_littlefs_conf_t conf = { - .base_path = basePath, - .partition_label = LFS_NAME, - .format_if_mount_failed = false - }; - - esp_err_t err = esp_vfs_littlefs_register(&conf); - if(err == ESP_FAIL && formatOnFail){ - if(format()){ - err = esp_vfs_littlefs_register(&conf); - } - } - if(err != ESP_OK){ - log_e("Mounting LITTLEFS failed! Error: %d", err); - return false; - } - _impl->mountpoint(basePath); - return true; -} - -void LITTLEFSFS::end() -{ - if(esp_littlefs_mounted(LFS_NAME)){ - esp_err_t err = esp_vfs_littlefs_unregister(LFS_NAME); - if(err){ - log_e("Unmounting LITTLEFS failed! Error: %d", err); - return; - } - _impl->mountpoint(NULL); - } -} - -bool LITTLEFSFS::format() -{ - disableCore0WDT(); - esp_err_t err = esp_littlefs_format(LFS_NAME); - enableCore0WDT(); - if(err){ - log_e("Formatting LITTLEFS failed! Error: %d", err); - return false; - } - return true; -} - -size_t LITTLEFSFS::totalBytes() -{ - size_t total,used; - if(esp_littlefs_info(LFS_NAME, &total, &used)){ - return 0; - } - return total; -} - -size_t LITTLEFSFS::usedBytes() -{ - size_t total,used; - if(esp_littlefs_info(LFS_NAME, &total, &used)){ - return 0; - } - return used; -} - -LITTLEFSFS LITTLEFS; - diff --git a/libraries/LITTLEFS/src/LITTLEFS.h b/libraries/LITTLEFS/src/LITTLEFS.h deleted file mode 100644 index fbd6f09e..00000000 --- a/libraries/LITTLEFS/src/LITTLEFS.h +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _LITTLEFS_H_ -#define _LITTLEFS_H_ - -#include "FS.h" - -namespace fs -{ - -class LITTLEFSFS : public FS -{ -public: - LITTLEFSFS(); - bool begin(bool formatOnFail=false, const char * basePath="/littlefs", uint8_t maxOpenFiles=5); - bool format(); - size_t totalBytes(); - size_t usedBytes(); - void end(); -}; - -} - -extern fs::LITTLEFSFS LITTLEFS; - - -#endif diff --git a/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino b/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino deleted file mode 100755 index 0f49e5aa..00000000 --- a/libraries/NetBIOS/examples/ESP_NBNST/ESP_NBNST.ino +++ /dev/null @@ -1,31 +0,0 @@ -#include -#include - -const char* ssid = "............"; -const char* password = ".............."; - -void setup() { - Serial.begin(115200); - - // Connect to WiFi network - WiFi.mode(WIFI_STA); - WiFi.begin(ssid, password); - Serial.println(""); - - // Wait for connection - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println(""); - Serial.print("Connected to "); - Serial.println(ssid); - Serial.print("IP address: "); - Serial.println(WiFi.localIP()); - - NBNS.begin("ESP"); -} - -void loop() { - -} diff --git a/libraries/NetBIOS/keywords.txt b/libraries/NetBIOS/keywords.txt deleted file mode 100755 index 68bcbeee..00000000 --- a/libraries/NetBIOS/keywords.txt +++ /dev/null @@ -1,25 +0,0 @@ -####################################### -# Syntax Coloring Map For ESPNBNS -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -NetBIOS KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 - -####################################### -# Instances (KEYWORD2) -####################################### - -NBNS KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/libraries/NetBIOS/library.properties b/libraries/NetBIOS/library.properties deleted file mode 100644 index 50e6e79c..00000000 --- a/libraries/NetBIOS/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=NetBIOS -version=1.0 -author=Pablo@xpablo.cz -maintainer=Hristo Gochkov -sentence=Enables NBNS (NetBIOS) name resolution. -paragraph=With this library you can connect to your ESP from Windows using a short name -category=Communication -url=http://www.xpablo.cz/?p=751#more-751 -architectures=esp32 diff --git a/libraries/NetBIOS/src/NetBIOS.cpp b/libraries/NetBIOS/src/NetBIOS.cpp deleted file mode 100755 index 22d3deca..00000000 --- a/libraries/NetBIOS/src/NetBIOS.cpp +++ /dev/null @@ -1,131 +0,0 @@ -#include "NetBIOS.h" - -#include - -#define NBNS_PORT 137 -#define NBNS_MAX_HOSTNAME_LEN 32 - -typedef struct { - uint16_t id; - uint8_t flags1; - uint8_t flags2; - uint16_t qcount; - uint16_t acount; - uint16_t nscount; - uint16_t adcount; - uint8_t name_len; - char name[NBNS_MAX_HOSTNAME_LEN + 1]; - uint16_t type; - uint16_t clas; -} __attribute__((packed)) nbns_question_t; - -typedef struct { - uint16_t id; - uint8_t flags1; - uint8_t flags2; - uint16_t qcount; - uint16_t acount; - uint16_t nscount; - uint16_t adcount; - uint8_t name_len; - char name[NBNS_MAX_HOSTNAME_LEN + 1]; - uint16_t type; - uint16_t clas; - uint32_t ttl; - uint16_t data_len; - uint16_t flags; - uint32_t addr; -} __attribute__((packed)) nbns_answer_t; - -static void _getnbname(const char *nbname, char *name, uint8_t maxlen){ - uint8_t b; - uint8_t c = 0; - - while ((*nbname) && (c < maxlen)) { - b = (*nbname++ - 'A') << 4; - c++; - if (*nbname) { - b |= *nbname++ - 'A'; - c++; - } - if(!b || b == ' '){ - break; - } - *name++ = b; - } - *name = 0; -} - -static void append_16(void * dst, uint16_t value){ - uint8_t * d = (uint8_t *)dst; - *d++ = (value >> 8) & 0xFF; - *d++ = value & 0xFF; -} - -static void append_32(void * dst, uint32_t value){ - uint8_t * d = (uint8_t *)dst; - *d++ = (value >> 24) & 0xFF; - *d++ = (value >> 16) & 0xFF; - *d++ = (value >> 8) & 0xFF; - *d++ = value & 0xFF; -} - -void NetBIOS::_onPacket(AsyncUDPPacket& packet){ - if (packet.length() >= sizeof(nbns_question_t)) { - nbns_question_t * question = (nbns_question_t *)packet.data(); - if (0 == (question->flags1 & 0x80)) { - char name[ NBNS_MAX_HOSTNAME_LEN + 1 ]; - _getnbname(&question->name[0], (char *)&name, question->name_len); - if (_name.equals(name)) { - nbns_answer_t nbnsa; - nbnsa.id = question->id; - nbnsa.flags1 = 0x85; - nbnsa.flags2 = 0; - append_16((void *)&nbnsa.qcount, 0); - append_16((void *)&nbnsa.acount, 1); - append_16((void *)&nbnsa.nscount, 0); - append_16((void *)&nbnsa.adcount, 0); - nbnsa.name_len = question->name_len; - memcpy(&nbnsa.name[0], &question->name[0], question->name_len + 1); - append_16((void *)&nbnsa.type, 0x20); - append_16((void *)&nbnsa.clas, 1); - append_32((void *)&nbnsa.ttl, 300000); - append_16((void *)&nbnsa.data_len, 6); - append_16((void *)&nbnsa.flags, 0); - nbnsa.addr = WiFi.localIP(); - _udp.writeTo((uint8_t *)&nbnsa, sizeof(nbnsa), packet.remoteIP(), NBNS_PORT); - } - } - } -} - -NetBIOS::NetBIOS(){ - -} -NetBIOS::~NetBIOS(){ - end(); -} - -bool NetBIOS::begin(const char *name){ - _name = name; - _name.toUpperCase(); - - if(_udp.connected()){ - return true; - } - - _udp.onPacket([](void * arg, AsyncUDPPacket& packet){ ((NetBIOS*)(arg))->_onPacket(packet); }, this); - return _udp.listen(NBNS_PORT); -} - -void NetBIOS::end(){ - if(_udp.connected()){ - _udp.close(); - } -} - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_NETBIOS) -NetBIOS NBNS; -#endif - -// EOF diff --git a/libraries/NetBIOS/src/NetBIOS.h b/libraries/NetBIOS/src/NetBIOS.h deleted file mode 100755 index 0321f6b8..00000000 --- a/libraries/NetBIOS/src/NetBIOS.h +++ /dev/null @@ -1,26 +0,0 @@ -// -#ifndef __ESPNBNS_h__ -#define __ESPNBNS_h__ - -#include -#include "AsyncUDP.h" - -class NetBIOS -{ -protected: - AsyncUDP _udp; - String _name; - void _onPacket(AsyncUDPPacket& packet); - -public: - NetBIOS(); - ~NetBIOS(); - bool begin(const char *name); - void end(); -}; - -#if !defined(NO_GLOBAL_INSTANCES) && !defined(NO_GLOBAL_NETBIOS) -extern NetBIOS NBNS; -#endif - -#endif diff --git a/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino b/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino deleted file mode 100644 index 7ed2a73b..00000000 --- a/libraries/Preferences/examples/Prefs2Struct/Prefs2Struct.ino +++ /dev/null @@ -1,43 +0,0 @@ -/* -This example shows how to use Preferences (nvs) to store a -structure. Note that the maximum size of a putBytes is 496K -or 97% of the nvs partition size. nvs has signifcant overhead, -so should not be used for data that will change often. -*/ -#include -Preferences prefs; - -typedef struct { - uint8_t hour; - uint8_t minute; - uint8_t setting1; - uint8_t setting2; -} schedule_t; - -void setup() { - Serial.begin(115200); - prefs.begin("schedule"); // use "schedule" namespace - uint8_t content[] = {9, 30, 235, 255, 20, 15, 0, 1}; // two entries - prefs.putBytes("schedule", content, sizeof(content)); - size_t schLen = prefs.getBytesLength("schedule"); - char buffer[schLen]; // prepare a buffer for the data - prefs.getBytes("schedule", buffer, schLen); - if (schLen % sizeof(schedule_t)) { // simple check that data fits - log_e("Data is not correct size!"); - return; - } - schedule_t *schedule = (schedule_t *) buffer; // cast the bytes into a struct ptr - Serial.printf("%02d:%02d %d/%d\n", - schedule[1].hour, schedule[1].minute, - schedule[1].setting1, schedule[1].setting2); - schedule[2] = {8, 30, 20, 21}; // add a third entry (unsafely) -// force the struct array into a byte array - prefs.putBytes("schedule", schedule, 3*sizeof(schedule_t)); - schLen = prefs.getBytesLength("schedule"); - char buffer2[schLen]; - prefs.getBytes("schedule", buffer2, schLen); - for (int x=0; x - -Preferences preferences; - -void setup() { - Serial.begin(115200); - Serial.println(); - - // Open Preferences with my-app namespace. Each application module, library, etc - // has to use a namespace name to prevent key name collisions. We will open storage in - // RW-mode (second parameter has to be false). - // Note: Namespace name is limited to 15 chars. - preferences.begin("my-app", false); - - // Remove all preferences under the opened namespace - //preferences.clear(); - - // Or remove the counter key only - //preferences.remove("counter"); - - // Get the counter value, if the key does not exist, return a default value of 0 - // Note: Key name is limited to 15 chars. - unsigned int counter = preferences.getUInt("counter", 0); - - // Increase counter by 1 - counter++; - - // Print the counter to Serial Monitor - Serial.printf("Current counter value: %u\n", counter); - - // Store the counter to the Preferences - preferences.putUInt("counter", counter); - - // Close the Preferences - preferences.end(); - - // Wait 10 seconds - Serial.println("Restarting in 10 seconds..."); - delay(10000); - - // Restart ESP - ESP.restart(); -} - -void loop() {} diff --git a/libraries/Preferences/keywords.txt b/libraries/Preferences/keywords.txt deleted file mode 100644 index fe2d4333..00000000 --- a/libraries/Preferences/keywords.txt +++ /dev/null @@ -1,54 +0,0 @@ -####################################### -# Syntax Coloring Map NVS -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -Preferences KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### -begin KEYWORD2 -end KEYWORD2 - -clear KEYWORD2 -remove KEYWORD2 - -putChar KEYWORD2 -putUChar KEYWORD2 -putShort KEYWORD2 -putUShort KEYWORD2 -putInt KEYWORD2 -putUInt KEYWORD2 -putLong KEYWORD2 -putULong KEYWORD2 -putLong64 KEYWORD2 -putULong64 KEYWORD2 -putFloat KEYWORD2 -putDouble KEYWORD2 -putBool KEYWORD2 -putString KEYWORD2 -putBytes KEYWORD2 - -getChar KEYWORD2 -getUChar KEYWORD2 -getShort KEYWORD2 -getUShort KEYWORD2 -getInt KEYWORD2 -getUInt KEYWORD2 -getLong KEYWORD2 -getULong KEYWORD2 -getLong64 KEYWORD2 -getULong64 KEYWORD2 -getFloat KEYWORD2 -getDouble KEYWORD2 -getBool KEYWORD2 -getString KEYWORD2 -getBytes KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/libraries/Preferences/library.properties b/libraries/Preferences/library.properties deleted file mode 100644 index 11675a58..00000000 --- a/libraries/Preferences/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Preferences -version=1.0 -author=Hristo Gochkov -maintainer=Hristo Gochkov -sentence=Provides friendly access to ESP32's Non-Volatile Storage -paragraph= -category=Data Storage -url= -architectures=esp32 diff --git a/libraries/Preferences/src/Preferences.cpp b/libraries/Preferences/src/Preferences.cpp deleted file mode 100644 index 6b45d2c7..00000000 --- a/libraries/Preferences/src/Preferences.cpp +++ /dev/null @@ -1,512 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "Preferences.h" - -#include "nvs.h" - -const char * nvs_errors[] = { "OTHER", "NOT_INITIALIZED", "NOT_FOUND", "TYPE_MISMATCH", "READ_ONLY", "NOT_ENOUGH_SPACE", "INVALID_NAME", "INVALID_HANDLE", "REMOVE_FAILED", "KEY_TOO_LONG", "PAGE_FULL", "INVALID_STATE", "INVALID_LENGTH"}; -#define nvs_error(e) (((e)>ESP_ERR_NVS_BASE)?nvs_errors[(e)&~(ESP_ERR_NVS_BASE)]:nvs_errors[0]) - -Preferences::Preferences() - :_handle(0) - ,_started(false) - ,_readOnly(false) -{} - -Preferences::~Preferences(){ - end(); -} - -bool Preferences::begin(const char * name, bool readOnly){ - if(_started){ - return false; - } - _readOnly = readOnly; - esp_err_t err = nvs_open(name, readOnly?NVS_READONLY:NVS_READWRITE, &_handle); - if(err){ - log_e("nvs_open failed: %s", nvs_error(err)); - return false; - } - _started = true; - return true; -} - -void Preferences::end(){ - if(!_started){ - return; - } - nvs_close(_handle); - _started = false; -} - -/* - * Clear all keys in opened preferences - * */ - -bool Preferences::clear(){ - if(!_started || _readOnly){ - return false; - } - esp_err_t err = nvs_erase_all(_handle); - if(err){ - log_e("nvs_erase_all fail: %s", nvs_error(err)); - return false; - } - return true; -} - -/* - * Remove a key - * */ - -bool Preferences::remove(const char * key){ - if(!_started || !key || _readOnly){ - return false; - } - esp_err_t err = nvs_erase_key(_handle, key); - if(err){ - log_e("nvs_erase_key fail: %s %s", key, nvs_error(err)); - return false; - } - return true; -} - -/* - * Put a key value - * */ - -size_t Preferences::putChar(const char* key, int8_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_i8(_handle, key, value); - if(err){ - log_e("nvs_set_i8 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 1; -} - -size_t Preferences::putUChar(const char* key, uint8_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_u8(_handle, key, value); - if(err){ - log_e("nvs_set_u8 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 1; -} - -size_t Preferences::putShort(const char* key, int16_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_i16(_handle, key, value); - if(err){ - log_e("nvs_set_i16 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 2; -} - -size_t Preferences::putUShort(const char* key, uint16_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_u16(_handle, key, value); - if(err){ - log_e("nvs_set_u16 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 2; -} - -size_t Preferences::putInt(const char* key, int32_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_i32(_handle, key, value); - if(err){ - log_e("nvs_set_i32 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 4; -} - -size_t Preferences::putUInt(const char* key, uint32_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_u32(_handle, key, value); - if(err){ - log_e("nvs_set_u32 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 4; -} - -size_t Preferences::putLong(const char* key, int32_t value){ - return putInt(key, value); -} - -size_t Preferences::putULong(const char* key, uint32_t value){ - return putUInt(key, value); -} - -size_t Preferences::putLong64(const char* key, int64_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_i64(_handle, key, value); - if(err){ - log_e("nvs_set_i64 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 8; -} - -size_t Preferences::putULong64(const char* key, uint64_t value){ - if(!_started || !key || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_u64(_handle, key, value); - if(err){ - log_e("nvs_set_u64 fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return 8; -} - -size_t Preferences::putFloat(const char* key, const float_t value){ - return putBytes(key, (void*)&value, sizeof(float_t)); -} - -size_t Preferences::putDouble(const char* key, const double_t value){ - return putBytes(key, (void*)&value, sizeof(double_t)); -} - -size_t Preferences::putBool(const char* key, const bool value){ - return putUChar(key, (uint8_t) (value ? 1 : 0)); -} - -size_t Preferences::putString(const char* key, const char* value){ - if(!_started || !key || !value || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_str(_handle, key, value); - if(err){ - log_e("nvs_set_str fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return strlen(value); -} - -size_t Preferences::putString(const char* key, const String value){ - return putString(key, value.c_str()); -} - -size_t Preferences::putBytes(const char* key, const void* value, size_t len){ - if(!_started || !key || !value || !len || _readOnly){ - return 0; - } - esp_err_t err = nvs_set_blob(_handle, key, value, len); - if(err){ - log_e("nvs_set_blob fail: %s %s", key, nvs_error(err)); - return 0; - } - err = nvs_commit(_handle); - if(err){ - log_e("nvs_commit fail: %s %s", key, nvs_error(err)); - return 0; - } - return len; -} - -PreferenceType Preferences::getType(const char* key) { - if(!_started || !key || strlen(key)>15){ - return PT_INVALID; - } - int8_t mt1; uint8_t mt2; int16_t mt3; uint16_t mt4; - int32_t mt5; uint32_t mt6; int64_t mt7; uint64_t mt8; - size_t len = 0; - if(nvs_get_i8(_handle, key, &mt1) == ESP_OK) return PT_I8; - if(nvs_get_u8(_handle, key, &mt2) == ESP_OK) return PT_U8; - if(nvs_get_i16(_handle, key, &mt3) == ESP_OK) return PT_I16; - if(nvs_get_u16(_handle, key, &mt4) == ESP_OK) return PT_U16; - if(nvs_get_i32(_handle, key, &mt5) == ESP_OK) return PT_I32; - if(nvs_get_u32(_handle, key, &mt6) == ESP_OK) return PT_U32; - if(nvs_get_i64(_handle, key, &mt7) == ESP_OK) return PT_I64; - if(nvs_get_u64(_handle, key, &mt8) == ESP_OK) return PT_U64; - if(nvs_get_str(_handle, key, NULL, &len) == ESP_OK) return PT_STR; - if(nvs_get_blob(_handle, key, NULL, &len) == ESP_OK) return PT_BLOB; - return PT_INVALID; -} - -bool Preferences::isKey(const char* key) { - return getType(key) != PT_INVALID; -} - -/* - * Get a key value - * */ - -int8_t Preferences::getChar(const char* key, const int8_t defaultValue){ - int8_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_i8(_handle, key, &value); - if(err){ - log_v("nvs_get_i8 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -uint8_t Preferences::getUChar(const char* key, const uint8_t defaultValue){ - uint8_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_u8(_handle, key, &value); - if(err){ - log_v("nvs_get_u8 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -int16_t Preferences::getShort(const char* key, const int16_t defaultValue){ - int16_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_i16(_handle, key, &value); - if(err){ - log_v("nvs_get_i16 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -uint16_t Preferences::getUShort(const char* key, const uint16_t defaultValue){ - uint16_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_u16(_handle, key, &value); - if(err){ - log_v("nvs_get_u16 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -int32_t Preferences::getInt(const char* key, const int32_t defaultValue){ - int32_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_i32(_handle, key, &value); - if(err){ - log_v("nvs_get_i32 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -uint32_t Preferences::getUInt(const char* key, const uint32_t defaultValue){ - uint32_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_u32(_handle, key, &value); - if(err){ - log_v("nvs_get_u32 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -int32_t Preferences::getLong(const char* key, const int32_t defaultValue){ - return getInt(key, defaultValue); -} - -uint32_t Preferences::getULong(const char* key, const uint32_t defaultValue){ - return getUInt(key, defaultValue); -} - -int64_t Preferences::getLong64(const char* key, const int64_t defaultValue){ - int64_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_i64(_handle, key, &value); - if(err){ - log_v("nvs_get_i64 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -uint64_t Preferences::getULong64(const char* key, const uint64_t defaultValue){ - uint64_t value = defaultValue; - if(!_started || !key){ - return value; - } - esp_err_t err = nvs_get_u64(_handle, key, &value); - if(err){ - log_v("nvs_get_u64 fail: %s %s", key, nvs_error(err)); - } - return value; -} - -float_t Preferences::getFloat(const char* key, const float_t defaultValue) { - float_t value = defaultValue; - getBytes(key, (void*) &value, sizeof(float_t)); - return value; -} - -double_t Preferences::getDouble(const char* key, const double_t defaultValue) { - double_t value = defaultValue; - getBytes(key, (void*) &value, sizeof(double_t)); - return value; -} - -bool Preferences::getBool(const char* key, const bool defaultValue) { - return getUChar(key, defaultValue ? 1 : 0) == 1; -} - -size_t Preferences::getString(const char* key, char* value, const size_t maxLen){ - size_t len = 0; - if(!_started || !key || !value || !maxLen){ - return 0; - } - esp_err_t err = nvs_get_str(_handle, key, NULL, &len); - if(err){ - log_e("nvs_get_str len fail: %s %s", key, nvs_error(err)); - return 0; - } - if(len > maxLen){ - log_e("not enough space in value: %u < %u", maxLen, len); - return 0; - } - err = nvs_get_str(_handle, key, value, &len); - if(err){ - log_e("nvs_get_str fail: %s %s", key, nvs_error(err)); - return 0; - } - return len; -} - -String Preferences::getString(const char* key, const String defaultValue){ - char * value = NULL; - size_t len = 0; - if(!_started || !key){ - return String(defaultValue); - } - esp_err_t err = nvs_get_str(_handle, key, value, &len); - if(err){ - log_e("nvs_get_str len fail: %s %s", key, nvs_error(err)); - return String(defaultValue); - } - char buf[len]; - value = buf; - err = nvs_get_str(_handle, key, value, &len); - if(err){ - log_e("nvs_get_str fail: %s %s", key, nvs_error(err)); - return String(defaultValue); - } - return String(buf); -} - -size_t Preferences::getBytesLength(const char* key){ - size_t len = 0; - if(!_started || !key){ - return 0; - } - esp_err_t err = nvs_get_blob(_handle, key, NULL, &len); - if(err){ - log_e("nvs_get_blob len fail: %s %s", key, nvs_error(err)); - return 0; - } - return len; -} - -size_t Preferences::getBytes(const char* key, void * buf, size_t maxLen){ - size_t len = getBytesLength(key); - if(!len || !buf || !maxLen){ - return len; - } - if(len > maxLen){ - log_e("not enough space in buffer: %u < %u", maxLen, len); - return 0; - } - esp_err_t err = nvs_get_blob(_handle, key, buf, &len); - if(err){ - log_e("nvs_get_blob fail: %s %s", key, nvs_error(err)); - return 0; - } - return len; -} - -size_t Preferences::freeEntries() { - nvs_stats_t nvs_stats; - esp_err_t err = nvs_get_stats(NULL, &nvs_stats); - if(err){ - log_e("Failed to get nvs statistics"); - return 0; - } - return nvs_stats.free_entries; -} diff --git a/libraries/Preferences/src/Preferences.h b/libraries/Preferences/src/Preferences.h deleted file mode 100644 index 1b8be270..00000000 --- a/libraries/Preferences/src/Preferences.h +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _PREFERENCES_H_ -#define _PREFERENCES_H_ - -#include "Arduino.h" - -typedef enum { - PT_I8, PT_U8, PT_I16, PT_U16, PT_I32, PT_U32, PT_I64, PT_U64, PT_STR, PT_BLOB, PT_INVALID -} PreferenceType; - -class Preferences { - protected: - uint32_t _handle; - bool _started; - bool _readOnly; - public: - Preferences(); - ~Preferences(); - - bool begin(const char * name, bool readOnly=false); - void end(); - - bool clear(); - bool remove(const char * key); - - size_t putChar(const char* key, int8_t value); - size_t putUChar(const char* key, uint8_t value); - size_t putShort(const char* key, int16_t value); - size_t putUShort(const char* key, uint16_t value); - size_t putInt(const char* key, int32_t value); - size_t putUInt(const char* key, uint32_t value); - size_t putLong(const char* key, int32_t value); - size_t putULong(const char* key, uint32_t value); - size_t putLong64(const char* key, int64_t value); - size_t putULong64(const char* key, uint64_t value); - size_t putFloat(const char* key, float_t value); - size_t putDouble(const char* key, double_t value); - size_t putBool(const char* key, bool value); - size_t putString(const char* key, const char* value); - size_t putString(const char* key, String value); - size_t putBytes(const char* key, const void* value, size_t len); - - bool isKey(const char* key); - PreferenceType getType(const char* key); - int8_t getChar(const char* key, int8_t defaultValue = 0); - uint8_t getUChar(const char* key, uint8_t defaultValue = 0); - int16_t getShort(const char* key, int16_t defaultValue = 0); - uint16_t getUShort(const char* key, uint16_t defaultValue = 0); - int32_t getInt(const char* key, int32_t defaultValue = 0); - uint32_t getUInt(const char* key, uint32_t defaultValue = 0); - int32_t getLong(const char* key, int32_t defaultValue = 0); - uint32_t getULong(const char* key, uint32_t defaultValue = 0); - int64_t getLong64(const char* key, int64_t defaultValue = 0); - uint64_t getULong64(const char* key, uint64_t defaultValue = 0); - float_t getFloat(const char* key, float_t defaultValue = NAN); - double_t getDouble(const char* key, double_t defaultValue = NAN); - bool getBool(const char* key, bool defaultValue = false); - size_t getString(const char* key, char* value, size_t maxLen); - String getString(const char* key, String defaultValue = String()); - size_t getBytesLength(const char* key); - size_t getBytes(const char* key, void * buf, size_t maxLen); - size_t freeEntries(); -}; - -#endif diff --git a/libraries/SD/README.md b/libraries/SD/README.md deleted file mode 100644 index 2cc472dc..00000000 --- a/libraries/SD/README.md +++ /dev/null @@ -1,42 +0,0 @@ - -# SD library - -This library provides the integration of ESP32 and SD (Secure Digital) cards without additional modules. - - -## Sample wiring diagram: - - -![SD card pins](http://i.imgur.com/4CoXOuR.png) - -For others SD formats: - - -![Other SD card formats](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/MMC-SD-miniSD-microSD-Color-Numbers-Names.gif/330px-MMC-SD-miniSD-microSD-Color-Numbers-Names.gif) - - -Image source: [Wikipedia](https://upload.wikimedia.org/wikipedia/commons/thumb/a/ab/MMC-SD-miniSD-microSD-Color-Numbers-Names.gif/330px-MMC-SD-miniSD-microSD-Color-Numbers-Names.gif) - -```diff -- Warning: Some ESP32 modules have different pinouts! -``` - - - -## FAQ: - -**Do I need any additional modules, like Arduino SD module?** - -No, just wire your SD card directly to ESP32. - - - -**What is the difference between SD and SD_MMC libraries?** - -SD runs on SPI, and SD_MMC uses the SDMMC hardware bus on the ESP32. - - - -**Can I change the CS pin?** - -Yes, just use: `SD.begin(CSpin)` diff --git a/libraries/SD/examples/SD_Test/SD_Test.ino b/libraries/SD/examples/SD_Test/SD_Test.ino deleted file mode 100644 index 6059446e..00000000 --- a/libraries/SD/examples/SD_Test/SD_Test.ino +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Connect the SD card to the following pins: - * - * SD Card | ESP32 - * D2 - - * D3 SS - * CMD MOSI - * VSS GND - * VDD 3.3V - * CLK SCK - * VSS GND - * D0 MISO - * D1 - - */ -#include "FS.h" -#include "SD.h" -#include "SPI.h" - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.println(file.name()); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.println(file.size()); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void testFileIO(fs::FS &fs, const char * path){ - File file = fs.open(path); - static uint8_t buf[512]; - size_t len = 0; - uint32_t start = millis(); - uint32_t end = start; - if(file){ - len = file.size(); - size_t flen = len; - start = millis(); - while(len){ - size_t toRead = len; - if(toRead > 512){ - toRead = 512; - } - file.read(buf, toRead); - len -= toRead; - } - end = millis() - start; - Serial.printf("%u bytes read for %u ms\n", flen, end); - file.close(); - } else { - Serial.println("Failed to open file for reading"); - } - - - file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - - size_t i; - start = millis(); - for(i=0; i<2048; i++){ - file.write(buf, 512); - } - end = millis() - start; - Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end); - file.close(); -} - -void setup(){ - Serial.begin(115200); - if(!SD.begin()){ - Serial.println("Card Mount Failed"); - return; - } - uint8_t cardType = SD.cardType(); - - if(cardType == CARD_NONE){ - Serial.println("No SD card attached"); - return; - } - - Serial.print("SD Card Type: "); - if(cardType == CARD_MMC){ - Serial.println("MMC"); - } else if(cardType == CARD_SD){ - Serial.println("SDSC"); - } else if(cardType == CARD_SDHC){ - Serial.println("SDHC"); - } else { - Serial.println("UNKNOWN"); - } - - uint64_t cardSize = SD.cardSize() / (1024 * 1024); - Serial.printf("SD Card Size: %lluMB\n", cardSize); - - listDir(SD, "/", 0); - createDir(SD, "/mydir"); - listDir(SD, "/", 0); - removeDir(SD, "/mydir"); - listDir(SD, "/", 2); - writeFile(SD, "/hello.txt", "Hello "); - appendFile(SD, "/hello.txt", "World!\n"); - readFile(SD, "/hello.txt"); - deleteFile(SD, "/foo.txt"); - renameFile(SD, "/hello.txt", "/foo.txt"); - readFile(SD, "/foo.txt"); - testFileIO(SD, "/test.txt"); - Serial.printf("Total space: %lluMB\n", SD.totalBytes() / (1024 * 1024)); - Serial.printf("Used space: %lluMB\n", SD.usedBytes() / (1024 * 1024)); -} - -void loop(){ - -} diff --git a/libraries/SD/examples/SD_time/SD_time.ino b/libraries/SD/examples/SD_time/SD_time.ino deleted file mode 100644 index 5fc87162..00000000 --- a/libraries/SD/examples/SD_time/SD_time.ino +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Connect the SD card to the following pins: - * - * SD Card | ESP32 - * D2 - - * D3 SS - * CMD MOSI - * VSS GND - * VDD 3.3V - * CLK SCK - * VSS GND - * D0 MISO - * D1 - - */ - -#include "FS.h" -#include "SD.h" -#include "SPI.h" -#include -#include - -const char* ssid = "your-ssid"; -const char* password = "your-password"; - -long timezone = 1; -byte daysavetime = 1; - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.print (file.name()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.print(file.size()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void setup(){ - Serial.begin(115200); - // We start by connecting to a WiFi network - Serial.println(); - Serial.println(); - Serial.print("Connecting to "); - Serial.println(ssid); - - WiFi.begin(ssid, password); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - Serial.println("Contacting Time Server"); - configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); - struct tm tmstruct ; - delay(2000); - tmstruct.tm_year = 0; - getLocalTime(&tmstruct, 5000); - Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec); - Serial.println(""); - - if(!SD.begin()){ - Serial.println("Card Mount Failed"); - return; - } - uint8_t cardType = SD.cardType(); - - if(cardType == CARD_NONE){ - Serial.println("No SD card attached"); - return; - } - - Serial.print("SD Card Type: "); - if(cardType == CARD_MMC){ - Serial.println("MMC"); - } else if(cardType == CARD_SD){ - Serial.println("SDSC"); - } else if(cardType == CARD_SDHC){ - Serial.println("SDHC"); - } else { - Serial.println("UNKNOWN"); - } - - uint64_t cardSize = SD.cardSize() / (1024 * 1024); - Serial.printf("SD Card Size: %lluMB\n", cardSize); - - listDir(SD, "/", 0); - removeDir(SD, "/mydir"); - createDir(SD, "/mydir"); - deleteFile(SD, "/hello.txt"); - writeFile(SD, "/hello.txt", "Hello "); - appendFile(SD, "/hello.txt", "World!\n"); - listDir(SD, "/", 0); -} - -void loop(){ - -} - - diff --git a/libraries/SD/library.properties b/libraries/SD/library.properties deleted file mode 100644 index 63183b73..00000000 --- a/libraries/SD/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=SD(esp32) -version=1.0.5 -author=Arduino, SparkFun -maintainer=Arduino -sentence=Enables reading and writing on SD cards. For all Arduino boards. -paragraph=Once an SD memory card is connected to the SPI interfare of the Arduino board you are enabled to create files and read/write on them. You can also move through directories on the SD card. -category=Data Storage -url=http://www.arduino.cc/en/Reference/SD -architectures=esp32 diff --git a/libraries/SD/src/SD.cpp b/libraries/SD/src/SD.cpp deleted file mode 100644 index d268aa0f..00000000 --- a/libraries/SD/src/SD.cpp +++ /dev/null @@ -1,106 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "vfs_api.h" -#include "sd_diskio.h" -#include "ff.h" -#include "FS.h" -#include "SD.h" - -using namespace fs; - -SDFS::SDFS(FSImplPtr impl): FS(impl), _pdrv(0xFF) {} - -bool SDFS::begin(uint8_t ssPin, SPIClass &spi, uint32_t frequency, const char * mountpoint, uint8_t max_files) -{ - if(_pdrv != 0xFF) { - return true; - } - - spi.begin(); - - _pdrv = sdcard_init(ssPin, &spi, frequency); - if(_pdrv == 0xFF) { - return false; - } - - if(!sdcard_mount(_pdrv, mountpoint, max_files)){ - sdcard_unmount(_pdrv); - sdcard_uninit(_pdrv); - _pdrv = 0xFF; - return false; - } - - _impl->mountpoint(mountpoint); - return true; -} - -void SDFS::end() -{ - if(_pdrv != 0xFF) { - _impl->mountpoint(NULL); - sdcard_unmount(_pdrv); - - sdcard_uninit(_pdrv); - _pdrv = 0xFF; - } -} - -sdcard_type_t SDFS::cardType() -{ - if(_pdrv == 0xFF) { - return CARD_NONE; - } - return sdcard_type(_pdrv); -} - -uint64_t SDFS::cardSize() -{ - if(_pdrv == 0xFF) { - return 0; - } - size_t sectors = sdcard_num_sectors(_pdrv); - size_t sectorSize = sdcard_sector_size(_pdrv); - return (uint64_t)sectors * sectorSize; -} - -uint64_t SDFS::totalBytes() -{ - FATFS* fsinfo; - DWORD fre_clust; - if(f_getfree("0:",&fre_clust,&fsinfo)!= 0) return 0; - uint64_t size = ((uint64_t)(fsinfo->csize))*(fsinfo->n_fatent - 2) -#if _MAX_SS != 512 - *(fsinfo->ssize); -#else - *512; -#endif - return size; -} - -uint64_t SDFS::usedBytes() -{ - FATFS* fsinfo; - DWORD fre_clust; - if(f_getfree("0:",&fre_clust,&fsinfo)!= 0) return 0; - uint64_t size = ((uint64_t)(fsinfo->csize))*((fsinfo->n_fatent - 2) - (fsinfo->free_clst)) -#if _MAX_SS != 512 - *(fsinfo->ssize); -#else - *512; -#endif - return size; -} - -SDFS SD = SDFS(FSImplPtr(new VFSImpl())); diff --git a/libraries/SD/src/SD.h b/libraries/SD/src/SD.h deleted file mode 100644 index da66c386..00000000 --- a/libraries/SD/src/SD.h +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _SD_H_ -#define _SD_H_ - -#include "FS.h" -#include "SPI.h" -#include "sd_defines.h" - -namespace fs -{ - -class SDFS : public FS -{ -protected: - uint8_t _pdrv; - -public: - SDFS(FSImplPtr impl); - bool begin(uint8_t ssPin=SS, SPIClass &spi=SPI, uint32_t frequency=4000000, const char * mountpoint="/sd", uint8_t max_files=5); - void end(); - sdcard_type_t cardType(); - uint64_t cardSize(); - uint64_t totalBytes(); - uint64_t usedBytes(); -}; - -} - -extern fs::SDFS SD; - -using namespace fs; -typedef fs::File SDFile; -typedef fs::SDFS SDFileSystemClass; -#define SDFileSystem SD - -#endif /* _SD_H_ */ diff --git a/libraries/SD/src/sd_defines.h b/libraries/SD/src/sd_defines.h deleted file mode 100644 index 6e42855a..00000000 --- a/libraries/SD/src/sd_defines.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _SD_DEFINES_H_ -#define _SD_DEFINES_H_ - -typedef enum { - CARD_NONE, - CARD_MMC, - CARD_SD, - CARD_SDHC, - CARD_UNKNOWN -} sdcard_type_t; - -#endif /* _SD_DISKIO_H_ */ diff --git a/libraries/SD/src/sd_diskio.cpp b/libraries/SD/src/sd_diskio.cpp deleted file mode 100644 index a10d322b..00000000 --- a/libraries/SD/src/sd_diskio.cpp +++ /dev/null @@ -1,777 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#include "sd_diskio.h" -#include "esp_system.h" -extern "C" { - #include "ff.h" - #include "diskio.h" -#if ESP_IDF_VERSION_MAJOR > 3 - #include "diskio_impl.h" -#endif - //#include "esp_vfs.h" - #include "esp_vfs_fat.h" - char CRC7(const char* data, int length); - unsigned short CRC16(const char* data, int length); -} - -typedef enum { - GO_IDLE_STATE = 0, - SEND_OP_COND = 1, - SEND_CID = 2, - SEND_RELATIVE_ADDR = 3, - SEND_SWITCH_FUNC = 6, - SEND_IF_COND = 8, - SEND_CSD = 9, - STOP_TRANSMISSION = 12, - SEND_STATUS = 13, - SET_BLOCKLEN = 16, - READ_BLOCK_SINGLE = 17, - READ_BLOCK_MULTIPLE = 18, - SEND_NUM_WR_BLOCKS = 22, - SET_WR_BLK_ERASE_COUNT = 23, - WRITE_BLOCK_SINGLE = 24, - WRITE_BLOCK_MULTIPLE = 25, - APP_OP_COND = 41, - APP_CLR_CARD_DETECT = 42, - APP_CMD = 55, - READ_OCR = 58, - CRC_ON_OFF = 59 -} ardu_sdcard_command_t; - -typedef struct { - uint8_t ssPin; - SPIClass * spi; - int frequency; - char * base_path; - sdcard_type_t type; - unsigned long sectors; - bool supports_crc; - int status; -} ardu_sdcard_t; - -static ardu_sdcard_t* s_cards[FF_VOLUMES] = { NULL }; - -/* - * SD SPI - * */ - -bool sdWait(uint8_t pdrv, int timeout) -{ - char resp; - uint32_t start = millis(); - - do { - resp = s_cards[pdrv]->spi->transfer(0xFF); - } while (resp == 0x00 && (millis() - start) < (unsigned int)timeout); - - return (resp > 0x00); -} - -void sdStop(uint8_t pdrv) -{ - s_cards[pdrv]->spi->write(0xFD); -} - -void sdDeselectCard(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - digitalWrite(card->ssPin, HIGH); -} - -bool sdSelectCard(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - digitalWrite(card->ssPin, LOW); - sdWait(pdrv, 300); - return true; -} - -char sdCommand(uint8_t pdrv, char cmd, unsigned int arg, unsigned int* resp) -{ - char token; - ardu_sdcard_t * card = s_cards[pdrv]; - - for (int f = 0; f < 3; f++) { - if (cmd == SEND_NUM_WR_BLOCKS || cmd == SET_WR_BLK_ERASE_COUNT || cmd == APP_OP_COND || cmd == APP_CLR_CARD_DETECT) { - token = sdCommand(pdrv, APP_CMD, 0, NULL); - sdDeselectCard(pdrv); - if (token > 1) { - return token; - } - if(!sdSelectCard(pdrv)) { - return 0xFF; - } - } - - char cmdPacket[7]; - cmdPacket[0] = cmd | 0x40; - cmdPacket[1] = arg >> 24; - cmdPacket[2] = arg >> 16; - cmdPacket[3] = arg >> 8; - cmdPacket[4] = arg; - if(card->supports_crc || cmd == GO_IDLE_STATE || cmd == SEND_IF_COND) { - cmdPacket[5] = (CRC7(cmdPacket, 5) << 1) | 0x01; - } else { - cmdPacket[5] = 0x01; - } - cmdPacket[6] = 0xFF; - - card->spi->writeBytes((uint8_t*)cmdPacket, (cmd == STOP_TRANSMISSION)?7:6); - - for (int i = 0; i < 9; i++) { - token = card->spi->transfer(0xFF); - if (!(token & 0x80)) { - break; - } - } - - if (token == 0xFF) { - log_w("no token received"); - sdDeselectCard(pdrv); - delay(100); - sdSelectCard(pdrv); - continue; - } else if (token & 0x08) { - log_w("crc error"); - sdDeselectCard(pdrv); - delay(100); - sdSelectCard(pdrv); - continue; - } else if (token > 1) { - log_w("token error [%u] 0x%x", cmd, token); - break; - } - - if (cmd == SEND_STATUS && resp) { - *resp = card->spi->transfer(0xFF); - } else if ((cmd == SEND_IF_COND || cmd == READ_OCR) && resp) { - *resp = card->spi->transfer32(0xFFFFFFFF); - } - - break; - } - - return token; -} - -bool sdReadBytes(uint8_t pdrv, char* buffer, int length) -{ - char token; - unsigned short crc; - ardu_sdcard_t * card = s_cards[pdrv]; - - uint32_t start = millis(); - do { - token = card->spi->transfer(0xFF); - } while (token == 0xFF && (millis() - start) < 500); - - if (token != 0xFE) { - return false; - } - - card->spi->transferBytes(NULL, (uint8_t*)buffer, length); - crc = card->spi->transfer16(0xFFFF); - return (!card->supports_crc || crc == CRC16(buffer, length)); -} - -char sdWriteBytes(uint8_t pdrv, const char* buffer, char token) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - unsigned short crc = (card->supports_crc)?CRC16(buffer, 512):0xFFFF; - if (!sdWait(pdrv, 500)) { - return false; - } - - card->spi->write(token); - card->spi->writeBytes((uint8_t*)buffer, 512); - card->spi->write16(crc); - return (card->spi->transfer(0xFF) & 0x1F); -} - -/* - * SPI SDCARD Communication - * */ - -char sdTransaction(uint8_t pdrv, char cmd, unsigned int arg, unsigned int* resp) -{ - if(!sdSelectCard(pdrv)) { - return 0xFF; - } - char token = sdCommand(pdrv, cmd, arg, resp); - sdDeselectCard(pdrv); - return token; -} - -bool sdReadSector(uint8_t pdrv, char* buffer, unsigned long long sector) -{ - for (int f = 0; f < 3; f++) { - if(!sdSelectCard(pdrv)) { - break; - } - if (!sdCommand(pdrv, READ_BLOCK_SINGLE, (s_cards[pdrv]->type == CARD_SDHC) ? sector : sector << 9, NULL)) { - bool success = sdReadBytes(pdrv, buffer, 512); - sdDeselectCard(pdrv); - if (success) { - return true; - } - } else { - break; - } - } - sdDeselectCard(pdrv); - return false; -} - -bool sdReadSectors(uint8_t pdrv, char* buffer, unsigned long long sector, int count) -{ - for (int f = 0; f < 3;) { - if(!sdSelectCard(pdrv)) { - break; - } - - if (!sdCommand(pdrv, READ_BLOCK_MULTIPLE, (s_cards[pdrv]->type == CARD_SDHC) ? sector : sector << 9, NULL)) { - do { - if (!sdReadBytes(pdrv, buffer, 512)) { - f++; - break; - } - - sector++; - buffer += 512; - f = 0; - } while (--count); - - if (sdCommand(pdrv, STOP_TRANSMISSION, 0, NULL)) { - log_e("command failed"); - break; - } - - sdDeselectCard(pdrv); - if (count == 0) { - return true; - } - } else { - break; - } - } - sdDeselectCard(pdrv); - return false; -} - -bool sdWriteSector(uint8_t pdrv, const char* buffer, unsigned long long sector) -{ - for (int f = 0; f < 3; f++) { - if(!sdSelectCard(pdrv)) { - break; - } - if (!sdCommand(pdrv, WRITE_BLOCK_SINGLE, (s_cards[pdrv]->type == CARD_SDHC) ? sector : sector << 9, NULL)) { - char token = sdWriteBytes(pdrv, buffer, 0xFE); - sdDeselectCard(pdrv); - - if (token == 0x0A) { - continue; - } else if (token == 0x0C) { - return false; - } - - unsigned int resp; - if (sdTransaction(pdrv, SEND_STATUS, 0, &resp) || resp) { - return false; - } - return true; - } else { - break; - } - } - sdDeselectCard(pdrv); - return false; -} - -bool sdWriteSectors(uint8_t pdrv, const char* buffer, unsigned long long sector, int count) -{ - char token; - const char* currentBuffer = buffer; - unsigned long long currentSector = sector; - int currentCount = count; - ardu_sdcard_t * card = s_cards[pdrv]; - - for (int f = 0; f < 3;) { - if (card->type != CARD_MMC) { - if (sdTransaction(pdrv, SET_WR_BLK_ERASE_COUNT, currentCount, NULL)) { - break; - } - } - - if(!sdSelectCard(pdrv)) { - break; - } - - if (!sdCommand(pdrv, WRITE_BLOCK_MULTIPLE, (card->type == CARD_SDHC) ? currentSector : currentSector << 9, NULL)) { - do { - token = sdWriteBytes(pdrv, currentBuffer, 0xFC); - if (token != 0x05) { - f++; - break; - } - currentBuffer += 512; - f = 0; - } while (--currentCount); - - if (!sdWait(pdrv, 500)) { - break; - } - - if (currentCount == 0) { - sdStop(pdrv); - sdDeselectCard(pdrv); - - unsigned int resp; - if (sdTransaction(pdrv, SEND_STATUS, 0, &resp) || resp) { - return false; - } - return true; - } else { - if (sdCommand(pdrv, STOP_TRANSMISSION, 0, NULL)) { - break; - } - - sdDeselectCard(pdrv); - - if (token == 0x0A) { - unsigned int writtenBlocks = 0; - if (card->type != CARD_MMC && sdSelectCard(pdrv)) { - if (!sdCommand(pdrv, SEND_NUM_WR_BLOCKS, 0, NULL)) { - char acmdData[4]; - if (sdReadBytes(pdrv, acmdData, 4)) { - writtenBlocks = acmdData[0] << 24; - writtenBlocks |= acmdData[1] << 16; - writtenBlocks |= acmdData[2] << 8; - writtenBlocks |= acmdData[3]; - } - } - sdDeselectCard(pdrv); - } - currentBuffer = buffer + (writtenBlocks << 9); - currentSector = sector + writtenBlocks; - currentCount = count - writtenBlocks; - continue; - } else { - return false; - } - } - } else { - break; - } - } - sdDeselectCard(pdrv); - return false; -} - -unsigned long sdGetSectorsCount(uint8_t pdrv) -{ - for (int f = 0; f < 3; f++) { - if(!sdSelectCard(pdrv)) { - break; - } - - if (!sdCommand(pdrv, SEND_CSD, 0, NULL)) { - char csd[16]; - bool success = sdReadBytes(pdrv, csd, 16); - sdDeselectCard(pdrv); - if (success) { - if ((csd[0] >> 6) == 0x01) { - unsigned long size = ( - ((unsigned long)(csd[7] & 0x3F) << 16) - | ((unsigned long)csd[8] << 8) - | csd[9] - ) + 1; - return size << 10; - } - unsigned long size = ( - ((unsigned long)(csd[6] & 0x03) << 10) - | ((unsigned long)csd[7] << 2) - | ((csd[8] & 0xC0) >> 6) - ) + 1; - size <<= (( - ((csd[9] & 0x03) << 1) - | ((csd[10] & 0x80) >> 7) - ) + 2); - size <<= (csd[5] & 0x0F); - return size >> 9; - } - } else { - break; - } - } - - sdDeselectCard(pdrv); - return 0; -} - - -namespace -{ - -struct AcquireSPI -{ - ardu_sdcard_t *card; - explicit AcquireSPI(ardu_sdcard_t* card) - : card(card) - { - card->spi->beginTransaction(SPISettings(card->frequency, MSBFIRST, SPI_MODE0)); - } - AcquireSPI(ardu_sdcard_t* card, int frequency) - : card(card) - { - card->spi->beginTransaction(SPISettings(frequency, MSBFIRST, SPI_MODE0)); - } - ~AcquireSPI() - { - card->spi->endTransaction(); - } -private: - AcquireSPI(AcquireSPI const&); - AcquireSPI& operator=(AcquireSPI const&); -}; - -} - - -/* - * FATFS API - * */ - -DSTATUS ff_sd_initialize(uint8_t pdrv) -{ - char token; - unsigned int resp; - unsigned int start; - ardu_sdcard_t * card = s_cards[pdrv]; - - if (!(card->status & STA_NOINIT)) { - return card->status; - } - - AcquireSPI card_locked(card, 400000); - - digitalWrite(card->ssPin, HIGH); - for (uint8_t i = 0; i < 20; i++) { - card->spi->transfer(0XFF); - } - - if (sdTransaction(pdrv, GO_IDLE_STATE, 0, NULL) != 1) { - log_w("GO_IDLE_STATE failed"); - goto unknown_card; - } - - token = sdTransaction(pdrv, CRC_ON_OFF, 1, NULL); - if (token == 0x5) { - //old card maybe - card->supports_crc = false; - } else if (token != 1) { - log_w("CRC_ON_OFF failed: %u", token); - goto unknown_card; - } - - if (sdTransaction(pdrv, SEND_IF_COND, 0x1AA, &resp) == 1) { - if ((resp & 0xFFF) != 0x1AA) { - log_w("SEND_IF_COND failed: %03X", resp & 0xFFF); - goto unknown_card; - } - - if (sdTransaction(pdrv, READ_OCR, 0, &resp) != 1 || !(resp & (1 << 20))) { - log_w("READ_OCR failed: %X", resp); - goto unknown_card; - } - - start = millis(); - do { - token = sdTransaction(pdrv, APP_OP_COND, 0x40100000, NULL); - } while (token == 1 && (millis() - start) < 1000); - - if (token) { - log_w("APP_OP_COND failed: %u", token); - goto unknown_card; - } - - if (!sdTransaction(pdrv, READ_OCR, 0, &resp)) { - if (resp & (1 << 30)) { - card->type = CARD_SDHC; - } else { - card->type = CARD_SD; - } - } else { - log_w("READ_OCR failed: %X", resp); - goto unknown_card; - } - } else { - if (sdTransaction(pdrv, READ_OCR, 0, &resp) != 1 || !(resp & (1 << 20))) { - log_w("READ_OCR failed: %X", resp); - goto unknown_card; - } - - start = millis(); - do { - token = sdTransaction(pdrv, APP_OP_COND, 0x100000, NULL); - } while (token == 0x01 && (millis() - start) < 1000); - - if (!token) { - card->type = CARD_SD; - } else { - start = millis(); - do { - token = sdTransaction(pdrv, SEND_OP_COND, 0x100000, NULL); - } while (token != 0x00 && (millis() - start) < 1000); - - if (token == 0x00) { - card->type = CARD_MMC; - } else { - log_w("SEND_OP_COND failed: %u", token); - goto unknown_card; - } - } - } - - if (card->type != CARD_MMC) { - if (sdTransaction(pdrv, APP_CLR_CARD_DETECT, 0, NULL)) { - log_w("APP_CLR_CARD_DETECT failed"); - goto unknown_card; - } - } - - if (card->type != CARD_SDHC) { - if (sdTransaction(pdrv, SET_BLOCKLEN, 512, NULL) != 0x00) { - log_w("SET_BLOCKLEN failed"); - goto unknown_card; - } - } - - card->sectors = sdGetSectorsCount(pdrv); - - if (card->frequency > 25000000) { - card->frequency = 25000000; - } - - card->status &= ~STA_NOINIT; - return card->status; - -unknown_card: - card->type = CARD_UNKNOWN; - return card->status; -} - -DSTATUS ff_sd_status(uint8_t pdrv) -{ - return s_cards[pdrv]->status; -} - -DRESULT ff_sd_read(uint8_t pdrv, uint8_t* buffer, DWORD sector, UINT count) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if (card->status & STA_NOINIT) { - return RES_NOTRDY; - } - DRESULT res = RES_OK; - - AcquireSPI lock(card); - - if (count > 1) { - res = sdReadSectors(pdrv, (char*)buffer, sector, count) ? RES_OK : RES_ERROR; - } else { - res = sdReadSector(pdrv, (char*)buffer, sector) ? RES_OK : RES_ERROR; - } - return res; -} - -DRESULT ff_sd_write(uint8_t pdrv, const uint8_t* buffer, DWORD sector, UINT count) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if (card->status & STA_NOINIT) { - return RES_NOTRDY; - } - - if (card->status & STA_PROTECT) { - return RES_WRPRT; - } - DRESULT res = RES_OK; - - AcquireSPI lock(card); - - if (count > 1) { - res = sdWriteSectors(pdrv, (const char*)buffer, sector, count) ? RES_OK : RES_ERROR; - } else { - res = sdWriteSector(pdrv, (const char*)buffer, sector) ? RES_OK : RES_ERROR; - } - return res; -} - -DRESULT ff_sd_ioctl(uint8_t pdrv, uint8_t cmd, void* buff) -{ - switch(cmd) { - case CTRL_SYNC: - { - AcquireSPI lock(s_cards[pdrv]); - if (sdSelectCard(pdrv)) { - sdDeselectCard(pdrv); - return RES_OK; - } - } - return RES_ERROR; - case GET_SECTOR_COUNT: - *((unsigned long*) buff) = s_cards[pdrv]->sectors; - return RES_OK; - case GET_SECTOR_SIZE: - *((WORD*) buff) = 512; - return RES_OK; - case GET_BLOCK_SIZE: - *((uint32_t*)buff) = 1; - return RES_OK; - } - return RES_PARERR; -} - - -/* - * Public methods - * */ - -uint8_t sdcard_uninit(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if (pdrv >= FF_VOLUMES || card == NULL) { - return 1; - } - sdTransaction(pdrv, GO_IDLE_STATE, 0, NULL); - ff_diskio_register(pdrv, NULL); - s_cards[pdrv] = NULL; - esp_err_t err = ESP_OK; - if (card->base_path) { - err = esp_vfs_fat_unregister_path(card->base_path); - } - free(card); - return err; -} - -uint8_t sdcard_init(uint8_t cs, SPIClass * spi, int hz) -{ - - uint8_t pdrv = 0xFF; - if (ff_diskio_get_drive(&pdrv) != ESP_OK || pdrv == 0xFF) { - return pdrv; - } - - ardu_sdcard_t * card = (ardu_sdcard_t *)malloc(sizeof(ardu_sdcard_t)); - if (!card) { - return 0xFF; - } - - card->base_path = NULL; - card->frequency = hz; - card->spi = spi; - card->ssPin = cs; - - card->supports_crc = true; - card->type = CARD_NONE; - card->status = STA_NOINIT; - - pinMode(card->ssPin, OUTPUT); - digitalWrite(card->ssPin, HIGH); - - s_cards[pdrv] = card; - - static const ff_diskio_impl_t sd_impl = { - .init = &ff_sd_initialize, - .status = &ff_sd_status, - .read = &ff_sd_read, - .write = &ff_sd_write, - .ioctl = &ff_sd_ioctl - }; - ff_diskio_register(pdrv, &sd_impl); - - return pdrv; -} - -uint8_t sdcard_unmount(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if (pdrv >= FF_VOLUMES || card == NULL) { - return 1; - } - card->status |= STA_NOINIT; - card->type = CARD_NONE; - - char drv[3] = {(char)('0' + pdrv), ':', 0}; - f_mount(NULL, drv, 0); - return 0; -} - -bool sdcard_mount(uint8_t pdrv, const char* path, uint8_t max_files) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if(pdrv >= FF_VOLUMES || card == NULL){ - return false; - } - - if(card->base_path){ - free(card->base_path); - } - card->base_path = strdup(path); - - FATFS* fs; - char drv[3] = {(char)('0' + pdrv), ':', 0}; - esp_err_t err = esp_vfs_fat_register(path, drv, max_files, &fs); - if (err == ESP_ERR_INVALID_STATE) { - log_e("esp_vfs_fat_register failed 0x(%x): SD is registered.", err); - return false; - } else if (err != ESP_OK) { - log_e("esp_vfs_fat_register failed 0x(%x)", err); - return false; - } - - FRESULT res = f_mount(fs, drv, 1); - if (res != FR_OK) { - log_e("f_mount failed 0x(%x)", res); - esp_vfs_fat_unregister_path(path); - return false; - } - AcquireSPI lock(card); - card->sectors = sdGetSectorsCount(pdrv); - return true; -} - -uint32_t sdcard_num_sectors(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if(pdrv >= FF_VOLUMES || card == NULL){ - return 0; - } - return card->sectors; -} - -uint32_t sdcard_sector_size(uint8_t pdrv) -{ - if(pdrv >= FF_VOLUMES || s_cards[pdrv] == NULL){ - return 0; - } - return 512; -} - -sdcard_type_t sdcard_type(uint8_t pdrv) -{ - ardu_sdcard_t * card = s_cards[pdrv]; - if(pdrv >= FF_VOLUMES || card == NULL){ - return CARD_NONE; - } - return card->type; -} diff --git a/libraries/SD/src/sd_diskio.h b/libraries/SD/src/sd_diskio.h deleted file mode 100644 index 143be683..00000000 --- a/libraries/SD/src/sd_diskio.h +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _SD_DISKIO_H_ -#define _SD_DISKIO_H_ - -#include "Arduino.h" -#include "SPI.h" -#include "sd_defines.h" - -uint8_t sdcard_init(uint8_t cs, SPIClass * spi, int hz); -uint8_t sdcard_uninit(uint8_t pdrv); - -bool sdcard_mount(uint8_t pdrv, const char* path, uint8_t max_files); -uint8_t sdcard_unmount(uint8_t pdrv); - -sdcard_type_t sdcard_type(uint8_t pdrv); -uint32_t sdcard_num_sectors(uint8_t pdrv); -uint32_t sdcard_sector_size(uint8_t pdrv); - -#endif /* _SD_DISKIO_H_ */ diff --git a/libraries/SD/src/sd_diskio_crc.c b/libraries/SD/src/sd_diskio_crc.c deleted file mode 100644 index 0372df82..00000000 --- a/libraries/SD/src/sd_diskio_crc.c +++ /dev/null @@ -1,103 +0,0 @@ -/* SD/MMC File System Library - * Copyright (c) 2014 Neil Thiessen - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -const char m_CRC7Table[] = { - 0x00, 0x09, 0x12, 0x1B, 0x24, 0x2D, 0x36, 0x3F, - 0x48, 0x41, 0x5A, 0x53, 0x6C, 0x65, 0x7E, 0x77, - 0x19, 0x10, 0x0B, 0x02, 0x3D, 0x34, 0x2F, 0x26, - 0x51, 0x58, 0x43, 0x4A, 0x75, 0x7C, 0x67, 0x6E, - 0x32, 0x3B, 0x20, 0x29, 0x16, 0x1F, 0x04, 0x0D, - 0x7A, 0x73, 0x68, 0x61, 0x5E, 0x57, 0x4C, 0x45, - 0x2B, 0x22, 0x39, 0x30, 0x0F, 0x06, 0x1D, 0x14, - 0x63, 0x6A, 0x71, 0x78, 0x47, 0x4E, 0x55, 0x5C, - 0x64, 0x6D, 0x76, 0x7F, 0x40, 0x49, 0x52, 0x5B, - 0x2C, 0x25, 0x3E, 0x37, 0x08, 0x01, 0x1A, 0x13, - 0x7D, 0x74, 0x6F, 0x66, 0x59, 0x50, 0x4B, 0x42, - 0x35, 0x3C, 0x27, 0x2E, 0x11, 0x18, 0x03, 0x0A, - 0x56, 0x5F, 0x44, 0x4D, 0x72, 0x7B, 0x60, 0x69, - 0x1E, 0x17, 0x0C, 0x05, 0x3A, 0x33, 0x28, 0x21, - 0x4F, 0x46, 0x5D, 0x54, 0x6B, 0x62, 0x79, 0x70, - 0x07, 0x0E, 0x15, 0x1C, 0x23, 0x2A, 0x31, 0x38, - 0x41, 0x48, 0x53, 0x5A, 0x65, 0x6C, 0x77, 0x7E, - 0x09, 0x00, 0x1B, 0x12, 0x2D, 0x24, 0x3F, 0x36, - 0x58, 0x51, 0x4A, 0x43, 0x7C, 0x75, 0x6E, 0x67, - 0x10, 0x19, 0x02, 0x0B, 0x34, 0x3D, 0x26, 0x2F, - 0x73, 0x7A, 0x61, 0x68, 0x57, 0x5E, 0x45, 0x4C, - 0x3B, 0x32, 0x29, 0x20, 0x1F, 0x16, 0x0D, 0x04, - 0x6A, 0x63, 0x78, 0x71, 0x4E, 0x47, 0x5C, 0x55, - 0x22, 0x2B, 0x30, 0x39, 0x06, 0x0F, 0x14, 0x1D, - 0x25, 0x2C, 0x37, 0x3E, 0x01, 0x08, 0x13, 0x1A, - 0x6D, 0x64, 0x7F, 0x76, 0x49, 0x40, 0x5B, 0x52, - 0x3C, 0x35, 0x2E, 0x27, 0x18, 0x11, 0x0A, 0x03, - 0x74, 0x7D, 0x66, 0x6F, 0x50, 0x59, 0x42, 0x4B, - 0x17, 0x1E, 0x05, 0x0C, 0x33, 0x3A, 0x21, 0x28, - 0x5F, 0x56, 0x4D, 0x44, 0x7B, 0x72, 0x69, 0x60, - 0x0E, 0x07, 0x1C, 0x15, 0x2A, 0x23, 0x38, 0x31, - 0x46, 0x4F, 0x54, 0x5D, 0x62, 0x6B, 0x70, 0x79 -}; - -char CRC7(const char* data, int length) -{ - char crc = 0; - for (int i = 0; i < length; i++) { - crc = m_CRC7Table[(crc << 1) ^ data[i]]; - } - return crc; -} - -const unsigned short m_CRC16Table[256] = { - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, - 0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, - 0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485, - 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4, - 0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC, - 0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B, - 0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12, - 0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A, - 0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41, - 0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49, - 0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70, - 0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78, - 0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F, - 0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E, - 0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D, - 0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C, - 0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3, - 0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A, - 0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92, - 0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9, - 0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1, - 0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8, - 0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0 -}; - -unsigned short CRC16(const char* data, int length) -{ - unsigned short crc = 0; - for (int i = 0; i < length; i++) { - crc = (crc << 8) ^ m_CRC16Table[((crc >> 8) ^ data[i]) & 0x00FF]; - } - return crc; -} diff --git a/libraries/SD_MMC/examples/SDMMC_Test/.skip.esp32s2 b/libraries/SD_MMC/examples/SDMMC_Test/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/SD_MMC/examples/SDMMC_Test/SDMMC_Test.ino b/libraries/SD_MMC/examples/SDMMC_Test/SDMMC_Test.ino deleted file mode 100644 index b9e87285..00000000 --- a/libraries/SD_MMC/examples/SDMMC_Test/SDMMC_Test.ino +++ /dev/null @@ -1,218 +0,0 @@ -/* - * Connect the SD card to the following pins: - * - * SD Card | ESP32 - * D2 12 - * D3 13 - * CMD 15 - * VSS GND - * VDD 3.3V - * CLK 14 - * VSS GND - * D0 2 (add 1K pull up after flashing) - * D1 4 - */ - -#include "FS.h" -#include "SD_MMC.h" - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.println(file.name()); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.println(file.size()); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void testFileIO(fs::FS &fs, const char * path){ - File file = fs.open(path); - static uint8_t buf[512]; - size_t len = 0; - uint32_t start = millis(); - uint32_t end = start; - if(file){ - len = file.size(); - size_t flen = len; - start = millis(); - while(len){ - size_t toRead = len; - if(toRead > 512){ - toRead = 512; - } - file.read(buf, toRead); - len -= toRead; - } - end = millis() - start; - Serial.printf("%u bytes read for %u ms\n", flen, end); - file.close(); - } else { - Serial.println("Failed to open file for reading"); - } - - - file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - - size_t i; - start = millis(); - for(i=0; i<2048; i++){ - file.write(buf, 512); - } - end = millis() - start; - Serial.printf("%u bytes written for %u ms\n", 2048 * 512, end); - file.close(); -} - -void setup(){ - Serial.begin(115200); - if(!SD_MMC.begin()){ - Serial.println("Card Mount Failed"); - return; - } - uint8_t cardType = SD_MMC.cardType(); - - if(cardType == CARD_NONE){ - Serial.println("No SD_MMC card attached"); - return; - } - - Serial.print("SD_MMC Card Type: "); - if(cardType == CARD_MMC){ - Serial.println("MMC"); - } else if(cardType == CARD_SD){ - Serial.println("SDSC"); - } else if(cardType == CARD_SDHC){ - Serial.println("SDHC"); - } else { - Serial.println("UNKNOWN"); - } - - uint64_t cardSize = SD_MMC.cardSize() / (1024 * 1024); - Serial.printf("SD_MMC Card Size: %lluMB\n", cardSize); - - listDir(SD_MMC, "/", 0); - createDir(SD_MMC, "/mydir"); - listDir(SD_MMC, "/", 0); - removeDir(SD_MMC, "/mydir"); - listDir(SD_MMC, "/", 2); - writeFile(SD_MMC, "/hello.txt", "Hello "); - appendFile(SD_MMC, "/hello.txt", "World!\n"); - readFile(SD_MMC, "/hello.txt"); - deleteFile(SD_MMC, "/foo.txt"); - renameFile(SD_MMC, "/hello.txt", "/foo.txt"); - readFile(SD_MMC, "/foo.txt"); - testFileIO(SD_MMC, "/test.txt"); - Serial.printf("Total space: %lluMB\n", SD_MMC.totalBytes() / (1024 * 1024)); - Serial.printf("Used space: %lluMB\n", SD_MMC.usedBytes() / (1024 * 1024)); -} - -void loop(){ - -} diff --git a/libraries/SD_MMC/examples/SDMMC_time/.skip.esp32s2 b/libraries/SD_MMC/examples/SDMMC_time/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/SD_MMC/examples/SDMMC_time/SDMMC_time.ino b/libraries/SD_MMC/examples/SDMMC_time/SDMMC_time.ino deleted file mode 100644 index 43dad454..00000000 --- a/libraries/SD_MMC/examples/SDMMC_time/SDMMC_time.ino +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Connect the SD card to the following pins: - * - * SD Card | ESP32 - * D2 - - * D3 SS - * CMD MOSI - * VSS GND - * VDD 3.3V - * CLK SCK - * VSS GND - * D0 MISO - * D1 - - */ - -#include "FS.h" -#include "SD_MMC.h" -#include "SPI.h" -#include -#include - -const char* ssid = "your-ssid"; -const char* password = "your-password"; - -long timezone = 1; -byte daysavetime = 1; - -void listDir(fs::FS &fs, const char * dirname, uint8_t levels){ - Serial.printf("Listing directory: %s\n", dirname); - - File root = fs.open(dirname); - if(!root){ - Serial.println("Failed to open directory"); - return; - } - if(!root.isDirectory()){ - Serial.println("Not a directory"); - return; - } - - File file = root.openNextFile(); - while(file){ - if(file.isDirectory()){ - Serial.print(" DIR : "); - Serial.print (file.name()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - if(levels){ - listDir(fs, file.name(), levels -1); - } - } else { - Serial.print(" FILE: "); - Serial.print(file.name()); - Serial.print(" SIZE: "); - Serial.print(file.size()); - time_t t= file.getLastWrite(); - struct tm * tmstruct = localtime(&t); - Serial.printf(" LAST WRITE: %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct->tm_year)+1900,( tmstruct->tm_mon)+1, tmstruct->tm_mday,tmstruct->tm_hour , tmstruct->tm_min, tmstruct->tm_sec); - } - file = root.openNextFile(); - } -} - -void createDir(fs::FS &fs, const char * path){ - Serial.printf("Creating Dir: %s\n", path); - if(fs.mkdir(path)){ - Serial.println("Dir created"); - } else { - Serial.println("mkdir failed"); - } -} - -void removeDir(fs::FS &fs, const char * path){ - Serial.printf("Removing Dir: %s\n", path); - if(fs.rmdir(path)){ - Serial.println("Dir removed"); - } else { - Serial.println("rmdir failed"); - } -} - -void readFile(fs::FS &fs, const char * path){ - Serial.printf("Reading file: %s\n", path); - - File file = fs.open(path); - if(!file){ - Serial.println("Failed to open file for reading"); - return; - } - - Serial.print("Read from file: "); - while(file.available()){ - Serial.write(file.read()); - } - file.close(); -} - -void writeFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Writing file: %s\n", path); - - File file = fs.open(path, FILE_WRITE); - if(!file){ - Serial.println("Failed to open file for writing"); - return; - } - if(file.print(message)){ - Serial.println("File written"); - } else { - Serial.println("Write failed"); - } - file.close(); -} - -void appendFile(fs::FS &fs, const char * path, const char * message){ - Serial.printf("Appending to file: %s\n", path); - - File file = fs.open(path, FILE_APPEND); - if(!file){ - Serial.println("Failed to open file for appending"); - return; - } - if(file.print(message)){ - Serial.println("Message appended"); - } else { - Serial.println("Append failed"); - } - file.close(); -} - -void renameFile(fs::FS &fs, const char * path1, const char * path2){ - Serial.printf("Renaming file %s to %s\n", path1, path2); - if (fs.rename(path1, path2)) { - Serial.println("File renamed"); - } else { - Serial.println("Rename failed"); - } -} - -void deleteFile(fs::FS &fs, const char * path){ - Serial.printf("Deleting file: %s\n", path); - if(fs.remove(path)){ - Serial.println("File deleted"); - } else { - Serial.println("Delete failed"); - } -} - -void setup(){ - Serial.begin(115200); - // We start by connecting to a WiFi network - Serial.println(); - Serial.println(); - Serial.print("Connecting to "); - Serial.println(ssid); - - WiFi.begin(ssid, password); - - while (WiFi.status() != WL_CONNECTED) { - delay(500); - Serial.print("."); - } - Serial.println("WiFi connected"); - Serial.println("IP address: "); - Serial.println(WiFi.localIP()); - Serial.println("Contacting Time Server"); - configTime(3600*timezone, daysavetime*3600, "time.nist.gov", "0.pool.ntp.org", "1.pool.ntp.org"); - struct tm tmstruct ; - delay(2000); - tmstruct.tm_year = 0; - getLocalTime(&tmstruct, 5000); - Serial.printf("\nNow is : %d-%02d-%02d %02d:%02d:%02d\n",(tmstruct.tm_year)+1900,( tmstruct.tm_mon)+1, tmstruct.tm_mday,tmstruct.tm_hour , tmstruct.tm_min, tmstruct.tm_sec); - Serial.println(""); - - if(!SD_MMC.begin()){ - Serial.println("Card Mount Failed"); - return; - } - uint8_t cardType = SD_MMC.cardType(); - - if(cardType == CARD_NONE){ - Serial.println("No SD card attached"); - return; - } - - Serial.print("SD Card Type: "); - if(cardType == CARD_MMC){ - Serial.println("MMC"); - } else if(cardType == CARD_SD){ - Serial.println("SDSC"); - } else if(cardType == CARD_SDHC){ - Serial.println("SDHC"); - } else { - Serial.println("UNKNOWN"); - } - - uint64_t cardSize = SD_MMC.cardSize() / (1024 * 1024); - Serial.printf("SD Card Size: %lluMB\n", cardSize); - - listDir(SD_MMC, "/", 0); - removeDir(SD_MMC, "/mydir"); - createDir(SD_MMC, "/mydir"); - deleteFile(SD_MMC, "/hello.txt"); - writeFile(SD_MMC, "/hello.txt", "Hello "); - appendFile(SD_MMC, "/hello.txt", "World!\n"); - listDir(SD_MMC, "/", 0); -} - -void loop(){ - -} - - diff --git a/libraries/SD_MMC/library.properties b/libraries/SD_MMC/library.properties deleted file mode 100644 index 9e47a6ee..00000000 --- a/libraries/SD_MMC/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=SD_MMC -version=1.0 -author=Hristo Gochkov, Ivan Grokhtkov -maintainer=Hristo Gochkov -sentence=ESP32 SDMMC File System -paragraph= -category=Data Storage -url= -architectures=esp32 diff --git a/libraries/SD_MMC/src/SD_MMC.cpp b/libraries/SD_MMC/src/SD_MMC.cpp deleted file mode 100644 index 81734b11..00000000 --- a/libraries/SD_MMC/src/SD_MMC.cpp +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "SD_MMC.h" -#ifndef CONFIG_IDF_TARGET_ESP32S2 //SDMMC does not work on ESP32S2 -#include "vfs_api.h" - -extern "C" { -#include -#include -#include -#include "esp_vfs_fat.h" -#include "driver/sdmmc_host.h" -#include "driver/sdmmc_defs.h" -#include "sdmmc_cmd.h" -} -#include "ff.h" - -using namespace fs; -/* - -*/ - -SDMMCFS::SDMMCFS(FSImplPtr impl) - : FS(impl), _card(NULL) -{} - -bool SDMMCFS::begin(const char * mountpoint, bool mode1bit) -{ - if(_card) { - return true; - } - //mount - sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); - sdmmc_host_t host; - host.flags = SDMMC_HOST_FLAG_4BIT; - host.slot = SDMMC_HOST_SLOT_1; - host.max_freq_khz = SDMMC_FREQ_DEFAULT; - host.io_voltage = 3.3f; - host.init = &sdmmc_host_init; - host.set_bus_width = &sdmmc_host_set_bus_width; - host.get_bus_width = &sdmmc_host_get_slot_width; - host.set_bus_ddr_mode = &sdmmc_host_set_bus_ddr_mode; - host.set_card_clk = &sdmmc_host_set_card_clk; - host.do_transaction = &sdmmc_host_do_transaction; - host.deinit_p = &sdspi_host_remove_device; - host.io_int_enable = &sdmmc_host_io_int_enable; - host.io_int_wait = &sdmmc_host_io_int_wait; - host.command_timeout_ms = 0; - host.max_freq_khz = SDMMC_FREQ_HIGHSPEED; -#ifdef BOARD_HAS_1BIT_SDMMC - mode1bit = true; -#endif - if(mode1bit) { - host.flags = SDMMC_HOST_FLAG_1BIT; //use 1-line SD mode - slot_config.width = 1; - } - - esp_vfs_fat_sdmmc_mount_config_t mount_config = { - .format_if_mount_failed = false, - .max_files = 5, - .allocation_unit_size = 0 - }; - - esp_err_t ret = esp_vfs_fat_sdmmc_mount(mountpoint, &host, &slot_config, &mount_config, &_card); - if (ret != ESP_OK) { - if (ret == ESP_FAIL) { - log_e("Failed to mount filesystem. If you want the card to be formatted, set format_if_mount_failed = true."); - } else if (ret == ESP_ERR_INVALID_STATE) { - _impl->mountpoint(mountpoint); - log_w("SD Already mounted"); - return true; - } else { - log_e("Failed to initialize the card (%d). Make sure SD card lines have pull-up resistors in place.", ret); - } - _card = NULL; - return false; - } - _impl->mountpoint(mountpoint); - return true; -} - -void SDMMCFS::end() -{ - if(_card) { - esp_vfs_fat_sdmmc_unmount(); - _impl->mountpoint(NULL); - _card = NULL; - } -} - -sdcard_type_t SDMMCFS::cardType() -{ - if(!_card) { - return CARD_NONE; - } - return (_card->ocr & SD_OCR_SDHC_CAP)?CARD_SDHC:CARD_SD; -} - -uint64_t SDMMCFS::cardSize() -{ - if(!_card) { - return 0; - } - return (uint64_t)_card->csd.capacity * _card->csd.sector_size; -} - -uint64_t SDMMCFS::totalBytes() -{ - FATFS* fsinfo; - DWORD fre_clust; - if(f_getfree("0:",&fre_clust,&fsinfo)!= 0) return 0; - uint64_t size = ((uint64_t)(fsinfo->csize))*(fsinfo->n_fatent - 2) -#if _MAX_SS != 512 - *(fsinfo->ssize); -#else - *512; -#endif - return size; -} - -uint64_t SDMMCFS::usedBytes() -{ - FATFS* fsinfo; - DWORD fre_clust; - if(f_getfree("0:",&fre_clust,&fsinfo)!= 0) return 0; - uint64_t size = ((uint64_t)(fsinfo->csize))*((fsinfo->n_fatent - 2) - (fsinfo->free_clst)) -#if _MAX_SS != 512 - *(fsinfo->ssize); -#else - *512; -#endif - return size; -} - -SDMMCFS SD_MMC = SDMMCFS(FSImplPtr(new VFSImpl())); -#endif /* CONFIG_IDF_TARGET_ESP32 */ diff --git a/libraries/SD_MMC/src/SD_MMC.h b/libraries/SD_MMC/src/SD_MMC.h deleted file mode 100644 index 3613fdfa..00000000 --- a/libraries/SD_MMC/src/SD_MMC.h +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _SDMMC_H_ -#define _SDMMC_H_ - -#include "sdkconfig.h" -#ifndef CONFIG_IDF_TARGET_ESP32S2 - -#include "FS.h" -#include "driver/sdmmc_types.h" -#include "sd_defines.h" - -namespace fs -{ - -class SDMMCFS : public FS -{ -protected: - sdmmc_card_t* _card; - -public: - SDMMCFS(FSImplPtr impl); - bool begin(const char * mountpoint="/sdcard", bool mode1bit=false); - void end(); - sdcard_type_t cardType(); - uint64_t cardSize(); - uint64_t totalBytes(); - uint64_t usedBytes(); -}; - -} - -extern fs::SDMMCFS SD_MMC; - -#endif /* CONFIG_IDF_TARGET_ESP32S2 */ -#endif /* _SDMMC_H_ */ diff --git a/libraries/SD_MMC/src/sd_defines.h b/libraries/SD_MMC/src/sd_defines.h deleted file mode 100644 index 6e42855a..00000000 --- a/libraries/SD_MMC/src/sd_defines.h +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -#ifndef _SD_DEFINES_H_ -#define _SD_DEFINES_H_ - -typedef enum { - CARD_NONE, - CARD_MMC, - CARD_SD, - CARD_SDHC, - CARD_UNKNOWN -} sdcard_type_t; - -#endif /* _SD_DISKIO_H_ */ diff --git a/libraries/SimpleBLE/examples/SimpleBleDevice/.skip.esp32s2 b/libraries/SimpleBLE/examples/SimpleBleDevice/.skip.esp32s2 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/SimpleBLE/examples/SimpleBleDevice/SimpleBleDevice.ino b/libraries/SimpleBLE/examples/SimpleBleDevice/SimpleBleDevice.ino deleted file mode 100644 index 3a9825a6..00000000 --- a/libraries/SimpleBLE/examples/SimpleBleDevice/SimpleBleDevice.ino +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -// Sketch shows how to use SimpleBLE to advertise the name of the device and change it on the press of a button -// Useful if you want to advertise some sort of message -// Button is attached between GPIO 0 and GND, and the device name changes each time the button is pressed - -#include "SimpleBLE.h" - -#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) -#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it -#endif - -SimpleBLE ble; - -void onButton(){ - String out = "BLE32 name: "; - out += String(millis() / 1000); - Serial.println(out); - ble.begin(out); -} - -void setup() { - Serial.begin(115200); - Serial.setDebugOutput(true); - pinMode(0, INPUT_PULLUP); - Serial.print("ESP32 SDK: "); - Serial.println(ESP.getSdkVersion()); - ble.begin("ESP32 SimpleBLE"); - Serial.println("Press the button to change the device's name"); -} - -void loop() { - static uint8_t lastPinState = 1; - uint8_t pinState = digitalRead(0); - if(!pinState && lastPinState){ - onButton(); - } - lastPinState = pinState; - while(Serial.available()) Serial.write(Serial.read()); -} diff --git a/libraries/SimpleBLE/library.properties b/libraries/SimpleBLE/library.properties deleted file mode 100644 index ec28494c..00000000 --- a/libraries/SimpleBLE/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=SimpleBLE -version=1.0 -author=Hristo Gochkov -maintainer=Hristo Gochkov -sentence=Provides really simple BLE advertizer with just on and off -paragraph= -category=Communication -url= -architectures=esp32 diff --git a/libraries/SimpleBLE/src/SimpleBLE.cpp b/libraries/SimpleBLE/src/SimpleBLE.cpp deleted file mode 100644 index d30a177f..00000000 --- a/libraries/SimpleBLE/src/SimpleBLE.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#include "sdkconfig.h" - -#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) - -#include "SimpleBLE.h" -#include "esp32-hal-log.h" - -#include "esp_bt.h" -#include "esp_gap_ble_api.h" -#include "esp_gatts_api.h" -#include "esp_bt_defs.h" -#include "esp_bt_main.h" - -static esp_ble_adv_data_t _adv_config = { - .set_scan_rsp = false, - .include_name = true, - .include_txpower = true, - .min_interval = 512, - .max_interval = 1024, - .appearance = 0, - .manufacturer_len = 0, - .p_manufacturer_data = NULL, - .service_data_len = 0, - .p_service_data = NULL, - .service_uuid_len = 0, - .p_service_uuid = NULL, - .flag = (ESP_BLE_ADV_FLAG_GEN_DISC|ESP_BLE_ADV_FLAG_BREDR_NOT_SPT) -}; - -static esp_ble_adv_params_t _adv_params = { - .adv_int_min = 512, - .adv_int_max = 1024, - .adv_type = ADV_TYPE_NONCONN_IND, - .own_addr_type = BLE_ADDR_TYPE_PUBLIC, - .peer_addr = {0x00, }, - .peer_addr_type = BLE_ADDR_TYPE_PUBLIC, - .channel_map = ADV_CHNL_ALL, - .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY, -}; - -static void _on_gap(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param){ - if(event == ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT){ - esp_ble_gap_start_advertising(&_adv_params); - } -} - -static bool _init_gap(const char * name){ - if(!btStarted() && !btStart()){ - log_e("btStart failed"); - return false; - } - esp_bluedroid_status_t bt_state = esp_bluedroid_get_status(); - if(bt_state == ESP_BLUEDROID_STATUS_UNINITIALIZED){ - if (esp_bluedroid_init()) { - log_e("esp_bluedroid_init failed"); - return false; - } - } - if(bt_state != ESP_BLUEDROID_STATUS_ENABLED){ - if (esp_bluedroid_enable()) { - log_e("esp_bluedroid_enable failed"); - return false; - } - } - if(esp_ble_gap_set_device_name(name)){ - log_e("gap_set_device_name failed"); - return false; - } - if(esp_ble_gap_config_adv_data(&_adv_config)){ - log_e("gap_config_adv_data failed"); - return false; - } - if(esp_ble_gap_register_callback(_on_gap)){ - log_e("gap_register_callback failed"); - return false; - } - return true; -} - -static bool _stop_gap() -{ - if(btStarted()){ - esp_bluedroid_disable(); - esp_bluedroid_deinit(); - btStop(); - } - return true; -} - -/* - * BLE Arduino - * - * */ - -SimpleBLE::SimpleBLE() -{ - local_name = "esp32"; -} - -SimpleBLE::~SimpleBLE(void) -{ - _stop_gap(); -} - -bool SimpleBLE::begin(String localName) -{ - if(localName.length()){ - local_name = localName; - } - return _init_gap(local_name.c_str()); -} - -void SimpleBLE::end() -{ - _stop_gap(); -} - -#endif diff --git a/libraries/SimpleBLE/src/SimpleBLE.h b/libraries/SimpleBLE/src/SimpleBLE.h deleted file mode 100644 index 6e7b702d..00000000 --- a/libraries/SimpleBLE/src/SimpleBLE.h +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2015-2016 Espressif Systems (Shanghai) PTE LTD -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at - -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#ifndef _SIMPLE_BLE_H_ -#define _SIMPLE_BLE_H_ - -#include "sdkconfig.h" - -#if defined(CONFIG_BT_ENABLED) && defined(CONFIG_BLUEDROID_ENABLED) - -#include -#include -#include -#include -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" -#include "esp_bt.h" - -#include "Arduino.h" - -struct ble_gap_adv_params_s; - -class SimpleBLE { - public: - - SimpleBLE(void); - ~SimpleBLE(void); - - /** - * Start BLE Advertising - * - * @param[in] localName local name to advertise - * - * @return true on success - * - */ - bool begin(String localName=String()); - - /** - * Stop BLE Advertising - * - * @return none - */ - void end(void); - - private: - String local_name; - private: - -}; - -#endif - -#endif diff --git a/libraries/Ticker/examples/Arguments/Arguments.ino b/libraries/Ticker/examples/Arguments/Arguments.ino deleted file mode 100644 index cde8acbf..00000000 --- a/libraries/Ticker/examples/Arguments/Arguments.ino +++ /dev/null @@ -1,27 +0,0 @@ -#include -#include - -// attach a LED to GPIO 21 -#define LED_PIN 21 - -Ticker tickerSetHigh; -Ticker tickerSetLow; - -void setPin(int state) { - digitalWrite(LED_PIN, state); -} - -void setup() { - pinMode(LED_PIN, OUTPUT); - digitalWrite(1, LOW); - - // every 25 ms, call setPin(0) - tickerSetLow.attach_ms(25, setPin, 0); - - // every 26 ms, call setPin(1) - tickerSetHigh.attach_ms(26, setPin, 1); -} - -void loop() { - -} diff --git a/libraries/Ticker/examples/Blinker/Blinker.ino b/libraries/Ticker/examples/Blinker/Blinker.ino deleted file mode 100644 index aca1f450..00000000 --- a/libraries/Ticker/examples/Blinker/Blinker.ino +++ /dev/null @@ -1,42 +0,0 @@ -#include -#include - -// attach a LED to pPIO 21 -#define LED_PIN 21 - -Ticker blinker; -Ticker toggler; -Ticker changer; -float blinkerPace = 0.1; //seconds -const float togglePeriod = 5; //seconds - -void change() { - blinkerPace = 0.5; -} - -void blink() { - digitalWrite(LED_PIN, !digitalRead(LED_PIN)); -} - -void toggle() { - static bool isBlinking = false; - if (isBlinking) { - blinker.detach(); - isBlinking = false; - } - else { - blinker.attach(blinkerPace, blink); - isBlinking = true; - } - digitalWrite(LED_PIN, LOW); //make sure LED on on after toggling (pin LOW = led ON) -} - -void setup() { - pinMode(LED_PIN, OUTPUT); - toggler.attach(togglePeriod, toggle); - changer.once(30, change); -} - -void loop() { - -} diff --git a/libraries/Ticker/keywords.txt b/libraries/Ticker/keywords.txt deleted file mode 100644 index 81cce2c8..00000000 --- a/libraries/Ticker/keywords.txt +++ /dev/null @@ -1,14 +0,0 @@ -####################################### -# Datatypes (KEYWORD1) -####################################### - -Ticker KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -attach KEYWORD2 -attach_ms KEYWORD2 -once KEYWORD2 -detach KEYWORD2 diff --git a/libraries/Ticker/library.properties b/libraries/Ticker/library.properties deleted file mode 100644 index 0f399447..00000000 --- a/libraries/Ticker/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=Ticker -version=1.1 -author=Bert Melis -maintainer=Hristo Gochkov -sentence=Allows to call functions with a given interval. -paragraph= -category=Timing -url= -architectures=esp32 diff --git a/libraries/Ticker/src/Ticker.cpp b/libraries/Ticker/src/Ticker.cpp deleted file mode 100644 index 1deeb7fb..00000000 --- a/libraries/Ticker/src/Ticker.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/* - Ticker.cpp - esp32 library that calls functions periodically - - Copyright (c) 2017 Bert Melis. All rights reserved. - - Based on the original work of: - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - The original version is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#include "Ticker.h" - -Ticker::Ticker() : - _timer(nullptr) {} - -Ticker::~Ticker() { - detach(); -} - -void Ticker::_attach_ms(uint32_t milliseconds, bool repeat, callback_with_arg_t callback, uint32_t arg) { - esp_timer_create_args_t _timerConfig; - _timerConfig.arg = reinterpret_cast(arg); - _timerConfig.callback = callback; - _timerConfig.dispatch_method = ESP_TIMER_TASK; - _timerConfig.name = "Ticker"; - if (_timer) { - esp_timer_stop(_timer); - esp_timer_delete(_timer); - } - esp_timer_create(&_timerConfig, &_timer); - if (repeat) { - esp_timer_start_periodic(_timer, milliseconds * 1000ULL); - } else { - esp_timer_start_once(_timer, milliseconds * 1000ULL); - } -} - -void Ticker::detach() { - if (_timer) { - esp_timer_stop(_timer); - esp_timer_delete(_timer); - _timer = nullptr; - } -} diff --git a/libraries/Ticker/src/Ticker.h b/libraries/Ticker/src/Ticker.h deleted file mode 100644 index 82804e0f..00000000 --- a/libraries/Ticker/src/Ticker.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - Ticker.h - esp32 library that calls functions periodically - - Copyright (c) 2017 Bert Melis. All rights reserved. - - Based on the original work of: - Copyright (c) 2014 Ivan Grokhotkov. All rights reserved. - The original version is part of the esp8266 core for Arduino environment. - - This library is free software; you can redistribute it and/or - modify it under the terms of the GNU Lesser General Public - License as published by the Free Software Foundation; either - version 2.1 of the License, or (at your option) any later version. - - This library is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - Lesser General Public License for more details. - - You should have received a copy of the GNU Lesser General Public - License along with this library; if not, write to the Free Software - Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA -*/ - -#ifndef TICKER_H -#define TICKER_H - -extern "C" { - #include "esp_timer.h" -} - -class Ticker -{ -public: - Ticker(); - ~Ticker(); - typedef void (*callback_t)(void); - typedef void (*callback_with_arg_t)(void*); - - void attach(float seconds, callback_t callback) - { - _attach_ms(seconds * 1000, true, reinterpret_cast(callback), 0); - } - - void attach_ms(uint32_t milliseconds, callback_t callback) - { - _attach_ms(milliseconds, true, reinterpret_cast(callback), 0); - } - - template - void attach(float seconds, void (*callback)(TArg), TArg arg) - { - static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach() callback argument size must be <= 4 bytes"); - // C-cast serves two purposes: - // static_cast for smaller integer types, - // reinterpret_cast + const_cast for pointer types - uint32_t arg32 = (uint32_t)arg; - _attach_ms(seconds * 1000, true, reinterpret_cast(callback), arg32); - } - - template - void attach_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg) - { - static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach_ms() callback argument size must be <= 4 bytes"); - uint32_t arg32 = (uint32_t)arg; - _attach_ms(milliseconds, true, reinterpret_cast(callback), arg32); - } - - void once(float seconds, callback_t callback) - { - _attach_ms(seconds * 1000, false, reinterpret_cast(callback), 0); - } - - void once_ms(uint32_t milliseconds, callback_t callback) - { - _attach_ms(milliseconds, false, reinterpret_cast(callback), 0); - } - - template - void once(float seconds, void (*callback)(TArg), TArg arg) - { - static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach() callback argument size must be <= 4 bytes"); - uint32_t arg32 = (uint32_t)(arg); - _attach_ms(seconds * 1000, false, reinterpret_cast(callback), arg32); - } - - template - void once_ms(uint32_t milliseconds, void (*callback)(TArg), TArg arg) - { - static_assert(sizeof(TArg) <= sizeof(uint32_t), "attach_ms() callback argument size must be <= 4 bytes"); - uint32_t arg32 = (uint32_t)(arg); - _attach_ms(milliseconds, false, reinterpret_cast(callback), arg32); - } - - void detach(); - bool active(); - -protected: - void _attach_ms(uint32_t milliseconds, bool repeat, callback_with_arg_t callback, uint32_t arg); - - -protected: - esp_timer_handle_t _timer; -}; - - -#endif // TICKER_H diff --git a/libraries/USB/examples/USBSerial/.skip.esp32 b/libraries/USB/examples/USBSerial/.skip.esp32 deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/USB/examples/USBSerial/USBSerial.ino b/libraries/USB/examples/USBSerial/USBSerial.ino deleted file mode 100644 index 2309bce7..00000000 --- a/libraries/USB/examples/USBSerial/USBSerial.ino +++ /dev/null @@ -1,74 +0,0 @@ -#include "USB.h" -USBCDC USBSerial; - -static void usbEventCallback(void* arg, esp_event_base_t event_base, int32_t event_id, void* event_data){ - if(event_base == ARDUINO_USB_EVENTS){ - arduino_usb_event_data_t * data = (arduino_usb_event_data_t*)event_data; - switch (event_id){ - case ARDUINO_USB_STARTED_EVENT: - Serial.println("USB PLUGGED"); - break; - case ARDUINO_USB_STOPPED_EVENT: - Serial.println("USB UNPLUGGED"); - break; - case ARDUINO_USB_SUSPEND_EVENT: - Serial.printf("USB SUSPENDED: remote_wakeup_en: %u\n", data->suspend.remote_wakeup_en); - break; - case ARDUINO_USB_RESUME_EVENT: - Serial.println("USB RESUMED"); - break; - - default: - break; - } - } else if(event_base == ARDUINO_USB_CDC_EVENTS){ - arduino_usb_cdc_event_data_t * data = (arduino_usb_cdc_event_data_t*)event_data; - switch (event_id){ - case ARDUINO_USB_CDC_CONNECTED_EVENT: - Serial.println("CDC CONNECTED"); - break; - case ARDUINO_USB_CDC_DISCONNECTED_EVENT: - Serial.println("CDC DISCONNECTED"); - break; - case ARDUINO_USB_CDC_LINE_STATE_EVENT: - Serial.printf("CDC LINE STATE: dtr: %u, rts: %u\n", data->line_state.dtr, data->line_state.rts); - break; - case ARDUINO_USB_CDC_LINE_CODING_EVENT: - Serial.printf("CDC LINE CODING: bit_rate: %u, data_bits: %u, stop_bits: %u, parity: %u\n", data->line_coding.bit_rate, data->line_coding.data_bits, data->line_coding.stop_bits, data->line_coding.parity); - break; - case ARDUINO_USB_CDC_RX_EVENT: - Serial.printf("CDC RX: %u\n", data->rx.len); - { - uint8_t buf[data->rx.len]; - size_t len = USBSerial.read(buf, data->rx.len); - Serial.write(buf, len); - } - break; - - default: - break; - } - } -} - - -void setup() { - Serial.begin(115200); - Serial.setDebugOutput(true); - - USB.onEvent(usbEventCallback); - USB.productName("ESP32S2-USB"); - USB.begin(); - - USBSerial.onEvent(usbEventCallback); - USBSerial.begin(); -} - -void loop() { - while(Serial.available()){ - size_t l = Serial.available(); - uint8_t b[l]; - l = Serial.read(b, l); - USBSerial.write(b, l); - } -} diff --git a/libraries/USB/keywords.txt b/libraries/USB/keywords.txt deleted file mode 100644 index 8b1442df..00000000 --- a/libraries/USB/keywords.txt +++ /dev/null @@ -1,24 +0,0 @@ -####################################### -# Syntax Coloring Map -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -USB KEYWORD1 -USBCDC KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -begin KEYWORD2 -end KEYWORD2 -onEvent KEYWORD2 -enableReset KEYWORD2 - -####################################### -# Constants (LITERAL1) -####################################### - diff --git a/libraries/USB/library.properties b/libraries/USB/library.properties deleted file mode 100644 index a3aac631..00000000 --- a/libraries/USB/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=USB -version=1.0 -author=Hristo Gochkov -maintainer=Hristo Gochkov -sentence=ESP32S2 USB Library -paragraph= -category=Communication -url= -architectures=esp32 diff --git a/libraries/USB/src/USB_NOT.h b/libraries/USB/src/USB_NOT.h deleted file mode 100644 index e69de29b..00000000 diff --git a/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino b/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino deleted file mode 100644 index 8582874f..00000000 --- a/libraries/Update/examples/AWS_S3_OTA_Update/AWS_S3_OTA_Update.ino +++ /dev/null @@ -1,283 +0,0 @@ -/** - AWS S3 OTA Update - Date: 14th June 2017 - Author: Arvind Ravulavaru - Purpose: Perform an OTA update from a bin located in Amazon S3 (HTTP Only) - - Upload: - Step 1 : Download the sample bin file from the examples folder - Step 2 : Upload it to your Amazon S3 account, in a bucket of your choice - Step 3 : Once uploaded, inside S3, select the bin file >> More (button on top of the file list) >> Make Public - Step 4 : You S3 URL => http://bucket-name.s3.ap-south-1.amazonaws.com/sketch-name.ino.bin - Step 5 : Build the above URL and fire it either in your browser or curl it `curl -I -v http://bucket-name.ap-south-1.amazonaws.com/sketch-name.ino.bin` to validate the same - Step 6: Plug in your SSID, Password, S3 Host and Bin file below - - Build & upload - Step 1 : Menu > Sketch > Export Compiled Library. The bin file will be saved in the sketch folder (Menu > Sketch > Show Sketch folder) - Step 2 : Upload bin to S3 and continue the above process - - // Check the bottom of this sketch for sample serial monitor log, during and after successful OTA Update -*/ - -#include -#include - -WiFiClient client; - -// Variables to validate -// response from S3 -long contentLength = 0; -bool isValidContentType = false; - -// Your SSID and PSWD that the chip needs -// to connect to -const char* SSID = "YOUR-SSID"; -const char* PSWD = "YOUR-SSID-PSWD"; - -// S3 Bucket Config -String host = "bucket-name.s3.ap-south-1.amazonaws.com"; // Host => bucket-name.s3.region.amazonaws.com -int port = 80; // Non https. For HTTPS 443. As of today, HTTPS doesn't work. -String bin = "/sketch-name.ino.bin"; // bin file name with a slash in front. - -// Utility to extract header value from headers -String getHeaderValue(String header, String headerName) { - return header.substring(strlen(headerName.c_str())); -} - -// OTA Logic -void execOTA() { - Serial.println("Connecting to: " + String(host)); - // Connect to S3 - if (client.connect(host.c_str(), port)) { - // Connection Succeed. - // Fecthing the bin - Serial.println("Fetching Bin: " + String(bin)); - - // Get the contents of the bin file - client.print(String("GET ") + bin + " HTTP/1.1\r\n" + - "Host: " + host + "\r\n" + - "Cache-Control: no-cache\r\n" + - "Connection: close\r\n\r\n"); - - // Check what is being sent - // Serial.print(String("GET ") + bin + " HTTP/1.1\r\n" + - // "Host: " + host + "\r\n" + - // "Cache-Control: no-cache\r\n" + - // "Connection: close\r\n\r\n"); - - unsigned long timeout = millis(); - while (client.available() == 0) { - if (millis() - timeout > 5000) { - Serial.println("Client Timeout !"); - client.stop(); - return; - } - } - // Once the response is available, - // check stuff - - /* - Response Structure - HTTP/1.1 200 OK - x-amz-id-2: NVKxnU1aIQMmpGKhSwpCBh8y2JPbak18QLIfE+OiUDOos+7UftZKjtCFqrwsGOZRN5Zee0jpTd0= - x-amz-request-id: 2D56B47560B764EC - Date: Wed, 14 Jun 2017 03:33:59 GMT - Last-Modified: Fri, 02 Jun 2017 14:50:11 GMT - ETag: "d2afebbaaebc38cd669ce36727152af9" - Accept-Ranges: bytes - Content-Type: application/octet-stream - Content-Length: 357280 - Server: AmazonS3 - - {{BIN FILE CONTENTS}} - - */ - while (client.available()) { - // read line till /n - String line = client.readStringUntil('\n'); - // remove space, to check if the line is end of headers - line.trim(); - - // if the the line is empty, - // this is end of headers - // break the while and feed the - // remaining `client` to the - // Update.writeStream(); - if (!line.length()) { - //headers ended - break; // and get the OTA started - } - - // Check if the HTTP Response is 200 - // else break and Exit Update - if (line.startsWith("HTTP/1.1")) { - if (line.indexOf("200") < 0) { - Serial.println("Got a non 200 status code from server. Exiting OTA Update."); - break; - } - } - - // extract headers here - // Start with content length - if (line.startsWith("Content-Length: ")) { - contentLength = atol((getHeaderValue(line, "Content-Length: ")).c_str()); - Serial.println("Got " + String(contentLength) + " bytes from server"); - } - - // Next, the content type - if (line.startsWith("Content-Type: ")) { - String contentType = getHeaderValue(line, "Content-Type: "); - Serial.println("Got " + contentType + " payload."); - if (contentType == "application/octet-stream") { - isValidContentType = true; - } - } - } - } else { - // Connect to S3 failed - // May be try? - // Probably a choppy network? - Serial.println("Connection to " + String(host) + " failed. Please check your setup"); - // retry?? - // execOTA(); - } - - // Check what is the contentLength and if content type is `application/octet-stream` - Serial.println("contentLength : " + String(contentLength) + ", isValidContentType : " + String(isValidContentType)); - - // check contentLength and content type - if (contentLength && isValidContentType) { - // Check if there is enough to OTA Update - bool canBegin = Update.begin(contentLength); - - // If yes, begin - if (canBegin) { - Serial.println("Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience!"); - // No activity would appear on the Serial monitor - // So be patient. This may take 2 - 5mins to complete - size_t written = Update.writeStream(client); - - if (written == contentLength) { - Serial.println("Written : " + String(written) + " successfully"); - } else { - Serial.println("Written only : " + String(written) + "/" + String(contentLength) + ". Retry?" ); - // retry?? - // execOTA(); - } - - if (Update.end()) { - Serial.println("OTA done!"); - if (Update.isFinished()) { - Serial.println("Update successfully completed. Rebooting."); - ESP.restart(); - } else { - Serial.println("Update not finished? Something went wrong!"); - } - } else { - Serial.println("Error Occurred. Error #: " + String(Update.getError())); - } - } else { - // not enough space to begin OTA - // Understand the partitions and - // space availability - Serial.println("Not enough space to begin OTA"); - client.flush(); - } - } else { - Serial.println("There was no content in the response"); - client.flush(); - } -} - -void setup() { - //Begin Serial - Serial.begin(115200); - delay(10); - - Serial.println("Connecting to " + String(SSID)); - - // Connect to provided SSID and PSWD - WiFi.begin(SSID, PSWD); - - // Wait for connection to establish - while (WiFi.status() != WL_CONNECTED) { - Serial.print("."); // Keep the serial monitor lit! - delay(500); - } - - // Connection Succeed - Serial.println(""); - Serial.println("Connected to " + String(SSID)); - - // Execute OTA Update - execOTA(); -} - -void loop() { - // chill -} - -/* - * Serial Monitor log for this sketch - * - * If the OTA succeeded, it would load the preference sketch, with a small modification. i.e. - * Print `OTA Update succeeded!! This is an example sketch : Preferences > StartCounter` - * And then keeps on restarting every 10 seconds, updating the preferences - * - * - rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) - configsip: 0, SPIWP:0x00 - clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 - mode:DIO, clock div:1 - load:0x3fff0008,len:8 - load:0x3fff0010,len:160 - load:0x40078000,len:10632 - load:0x40080000,len:252 - entry 0x40080034 - Connecting to SSID - ...... - Connected to SSID - Connecting to: bucket-name.s3.ap-south-1.amazonaws.com - Fetching Bin: /StartCounter.ino.bin - Got application/octet-stream payload. - Got 357280 bytes from server - contentLength : 357280, isValidContentType : 1 - Begin OTA. This may take 2 - 5 mins to complete. Things might be quite for a while.. Patience! - Written : 357280 successfully - OTA done! - Update successfully completed. Rebooting. - ets Jun 8 2016 00:22:57 - - rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) - configsip: 0, SPIWP:0x00 - clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 - mode:DIO, clock div:1 - load:0x3fff0008,len:8 - load:0x3fff0010,len:160 - load:0x40078000,len:10632 - load:0x40080000,len:252 - entry 0x40080034 - - OTA Update succeeded!! This is an example sketch : Preferences > StartCounter - Current counter value: 1 - Restarting in 10 seconds... - E (102534) wifi: esp_wifi_stop 802 wifi is not init - ets Jun 8 2016 00:22:57 - - rst:0x10 (RTCWDT_RTC_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) - configsip: 0, SPIWP:0x00 - clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 - mode:DIO, clock div:1 - load:0x3fff0008,len:8 - load:0x3fff0010,len:160 - load:0x40078000,len:10632 - load:0x40080000,len:252 - entry 0x40080034 - - OTA Update succeeded!! This is an example sketch : Preferences > StartCounter - Current counter value: 2 - Restarting in 10 seconds... - - .... - * - */ diff --git a/libraries/Update/examples/AWS_S3_OTA_Update/StartCounter.ino.bin b/libraries/Update/examples/AWS_S3_OTA_Update/StartCounter.ino.bin deleted file mode 100644 index 14732a0adb109d05668916b9b06643358bdf9ca3..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 357280 zcmaFK!K7ay#Nohz1-$r=MQ~JTGz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!n zMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ON zU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU z1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0q zLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$( zGz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!n zMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ON zU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU z1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0q zLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$( zGz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!n zMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtr!nMnhmU1V%$(Gz3ON zU^E0qLtr!nMnhmU1V%$(Gz3ONU^E0qLtt0~0R{(qjzk8AG8tZnoszr``y_cCM5TBg z++}zjTxED2K1lOAh{*6dERf}O@RZ_p=#u4im?{h5gTz1>B#sM%)FR8(L(M@J*OP*n zjjRrx4YS8qiq`?89>j-XkXn!!h(^XByFlU~8YT{7gT!HCAU2;guS2R7ufr@UUI!;> zUWYPiUWaYcybiadcpV&Nc^%%!Kxi>pUI!2ciA|H|bvWP%!OM}@Ah8%E{u+5+haCzK zb(g)!O1uu!m3bXNd>BU86QBf93ljfeh+u>Gr_3Py z`{ocDBo>I|2M`|{2H6D?2id;}&Hhj&UI&oaBB;GpP?|}P*WtGzufs!AUWX}AF_8UI z^1KeOknBHV4RH%d+yD(IpaE6}1_nt628LQ_Zr#&)WBR5`b8L*4uehrG&C}9$`4^YJ z{7a4IPVYI-u`62DIe$%x2HOcPhK2{`m4_Xj#q(IVZrw52?dwnbm(2bazDBYJKRwEu zqHOjT*WdLQErl5S!5%`ZI6&w~2<^}hp*s#k=&T=Lx}inS5v1;dP%@Zqxjr3Cr=C3v zq7~v7FgYt%koER8P)V^l(IK$k@u;4~( zxJj8a!wJ9i+=Hu~8EhveJc)Sd?9j8dLUz5VOTha_*PcjuyG*+3%Xa=lgUdIshsT+8 zx4LYZd$ZEH;+4y!bY6$6DZCE1Qg|H;W(s>>BWbitqrt&&0 z%iwj`m;vE~#6TD%jthg-BFoK&nu9Fvl?pK%SsgkXW=~`)uLDRuh!4XcwIDGNjf_Ed zfy6;HOdQ4riNnM|Y^^k2hsIQ1hi$364smI`4wKS&9WJHuI($pzb%@R2b>PT=&_)@& z4j>E?>&oVJSlbH0vys>!u>d6gf^1%g%{dTtt8;iA4no-sdAts6L|~A4gm6tBuR}sU z#12AgLGnw=P}N#iL->X@5E`V$3&{^4K0XYxKNZb>%RF8OkXUIR#LP%2eXxkvVPzSw zLu?hV156HNzf?A_gBgiLRZDL^HAOP4oIM|suIM_Kj*w{JPSveROVF0R; zg@XkIKs;s+4i*j&W&sf(5eN??&&*pfD1D+Fd%}2k&&5^k)4^9k&%gsiJ6&&g_W6wnT0il zfq{XEgFu=4iaQ