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