Skip to content

Commit f129331

Browse files
committed
📝 Add BLESecurity example
1 parent 0bea04f commit f129331

File tree

2 files changed

+83
-0
lines changed

2 files changed

+83
-0
lines changed

.github/workflows/platformio-ci.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ jobs:
2121
os: [ ubuntu-latest ]
2222
example:
2323
- "SerialToSerialBLE"
24+
- "SerialToSerialBLE_Secure"
2425
boards:
2526
- [ esp32dev, esp32-s3-devkitc-1, esp32-c3-devkitm-1 ]
2627
nimble: [ false, true ]
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
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

Comments
 (0)