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