1+ #include < BLESerial.h>
2+
3+ // FOR ETL: Uncomment the following lines
4+ // #include <Embedded_Template_Library.h>
5+ // #include <etl/queue.h>
6+ // #include <etl/circular_buffer.h>
7+
8+ BLESerial SerialBLE;
9+ // If you are using an older version of Arduino IDE or C++ compiler, you may need to use
10+ // an empty template argument (<>), as Class Template Argument Deduction (CTAD) is not
11+ // supported in C++ versions older than C++17. For more details, see:
12+ // https://www.cppreference.com/w/cpp/language/ctad.html
13+ //
14+ // Uncomment the line below if you are using an older version of Arduino IDE/C++ compiler
15+ // BLESerial<> SerialBLE;
16+
17+ // FOR ETL: Uncomment one of the following lines
18+ // BLESerial<etl::queue<uint8_t, 255, etl::memory_model::MEMORY_MODEL_SMALL>> SerialBLE;
19+ // OR
20+ // BLESerial<etl::circular_buffer<uint8_t, 255>> SerialBLE;
21+
22+ class AppSecurityCallbacks : public BLESecurityCallbacks {
23+ public:
24+ AppSecurityCallbacks () {
25+ this ->passKey = random (111111 , 999999 );
26+ }
27+
28+ uint32_t onPassKeyRequest (){
29+ ESP_LOGI (LOG_TAG, " PassKeyRequest" );
30+
31+ // Generate a random passkey
32+ this ->passKey = random (111111 , 999999 );
33+
34+ return this ->passKey ;
35+ }
36+
37+ void onPassKeyNotify (uint32_t pass_key){
38+ ESP_LOGI (LOG_TAG, " The passkey Notify number: %d" , pass_key);
39+ }
40+
41+ bool onConfirmPIN (uint32_t pass_key){
42+ ESP_LOGI (LOG_TAG, " The passkey YES/NO number: %d" , pass_key);
43+ vTaskDelay (5000 );
44+ return true ;
45+ }
46+
47+ bool onSecurityRequest (){
48+ ESP_LOGI (LOG_TAG, " SecurityRequest" );
49+ return true ;
50+ }
51+
52+ void onAuthenticationComplete (esp_ble_auth_cmpl_t cmpl){
53+ ESP_LOGI (LOG_TAG, " Starting BLE work!" );
54+ }
55+
56+ private:
57+ uint32_t passKey;
58+ };
59+
60+ void setup () {
61+ BLEDevice::init (" ESP32-BLE-Slave" );
62+ BLEDevice::setEncryptionLevel (ESP_BLE_SEC_ENCRYPT);
63+ BLEDevice::setSecurityCallbacks (new AppSecurityCallbacks ());
64+
65+ BLEServer* pServer = BLEDevice::createServer ();
66+
67+ BLESecurity *pSecurity = new BLESecurity ();
68+ pSecurity->setKeySize ();
69+ pSecurity->setAuthenticationMode (ESP_LE_AUTH_REQ_SC_ONLY);
70+ pSecurity->setCapability (ESP_IO_CAP_IO);
71+ pSecurity->setInitEncryptionKey (ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);
72+
73+ Serial.begin (9600 );
74+ SerialBLE.begin (pServer);
75+ }
76+
77+ void loop () {
78+ if (Serial.available ()) {
79+ SerialBLE.write (Serial.read ());
80+ SerialBLE.flush ();
81+ }
82+
83+ if (SerialBLE.available ()) {
84+ Serial.write (SerialBLE.read ());
85+ }
86+ }
0 commit comments