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