반응형

앞선 블루투스 4.0 연결 방식에 대해 살펴보면서 ESP32의 BLE연결시 비밀번호 페어링 시연을 한적이 있다. 

https://postpop.tistory.com/13

 

이번엔 그 코드에 대해 살펴 보고 원격제어 코드에 적용시켜 보겠다. 

 

 

 

PIN CODE관련 BLE 클래스 함수

class MySecurity : public BLESecurityCallbacks {  // BLE 클래스 pin code

  uint32_t onPassKeyRequest(){

    ESP_LOGI(LOG_TAG, "PassKeyRequest");

    return 123456;

  }

  void onPassKeyNotify(uint32_t pass_key){

    ESP_LOGI(LOG_TAG, "The passkey Notify number:%d", pass_key);

  }

  bool onConfirmPIN(uint32_t pass_key){

    ESP_LOGI(LOG_TAG, "The passkey YES/NO number:%d", pass_key);

    vTaskDelay(5000);

    return true;

  }

  bool onSecurityRequest(){

    ESP_LOGI(LOG_TAG, "SecurityRequest");

    return true;

  }

  void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl){

    ESP_LOGI(LOG_TAG, "Starting BLE work!");

  }

};

 

PIN CODE 함수 지정

BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);

BLEDevice::setSecurityCallbacks(new MySecurity());

 

PIN CODE 설정

BLESecurity *pSecurity = new BLESecurity();  // pin code 설정

uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;

uint32_t passkey = 123456; // 비밀 번호 6자리

uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE;

esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t));

pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);

pSecurity->setCapability(ESP_IO_CAP_OUT);

pSecurity->setKeySize(16);

esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t));

pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);

esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));

 

 

 

 

아래코드를 ESP32에 업로드하면 아래 영상과 같이 BLE 연결시 비밀번호 입력화면이 표시된다.

 

 

이전글(블루투스 4.0 BLE, 스마트폰 연결과 페어링(pairing), AT-09)에 올렸던 영상임.

 

 

시연에 사용된 앱(arduino bluetooth controller PWM v3.5)은 안드로이드 버전업에 따라 안드로이드 특정버전에서만 와이이파이 및 블루투스 연결이 가능합니다. 

(*** 와이파이 연결은 안드로이드8 [갤럭시S7]이하 버전에서만 작동합니다 ***)

(*** 블루투스 연결은 안드로이드10 이하 버전에서만 작동합니다 ***)

esp32_BLE_pin_code_paring.ino
0.00MB

 

#include <BLEDevice.h>

#include <BLEUtils.h>

#include <BLEServer.h>

 

#define SERVICE_UUID        "0000FFE0-0000-1000-8000-00805F9B34FB"

#define CHARACTERISTIC_UUID "0000FFE1-0000-1000-8000-00805F9B34FB"

 

class MySecurity : public BLESecurityCallbacks {  // BLE 클래스 pin code 함수

  uint32_t onPassKeyRequest(){

    ESP_LOGI(LOG_TAG, "PassKeyRequest");

    return 123456;

  }

  void onPassKeyNotify(uint32_t pass_key){

    ESP_LOGI(LOG_TAG, "The passkey Notify number:%d", pass_key);

  }

  bool onConfirmPIN(uint32_t pass_key){

    ESP_LOGI(LOG_TAG, "The passkey YES/NO number:%d", pass_key);

    vTaskDelay(5000);

    return true;

  }

  bool onSecurityRequest(){

    ESP_LOGI(LOG_TAG, "SecurityRequest");

    return true;

  }

  void onAuthenticationComplete(esp_ble_auth_cmpl_t cmpl){

    ESP_LOGI(LOG_TAG, "Starting BLE work!");

  }

};

 

class MyCallbacks: public BLECharacteristicCallbacks {

    void onWrite(BLECharacteristic *pCharacteristic) {

      std::string value = pCharacteristic->getValue();

      if (value.length() > 0) {

        for (int i = 0; i < value.length(); i++)

          Serial.print(value[i]);

      }

    }

};

 

void setup() {

  Serial.begin(115200);

  BLEDevice::init("ESP32");

  BLEDevice::setEncryptionLevel(ESP_BLE_SEC_ENCRYPT);

  BLEDevice::setSecurityCallbacks(new MySecurity());

  BLEServer *pServer = BLEDevice::createServer();

  BLEService *pService = pServer->createService(SERVICE_UUID);

  BLECharacteristic *pCharacteristic = pService->createCharacteristic(

                                         CHARACTERISTIC_UUID,

                                         BLECharacteristic::PROPERTY_READ |

                                         BLECharacteristic::PROPERTY_WRITE

                                       );

  pCharacteristic->setValue("Hello World");

  pService->start();

  BLEAdvertising *pAdvertising = pServer->getAdvertising();

  pAdvertising->start();

  BLESecurity *pSecurity = new BLESecurity();  // pin code 설정

  uint8_t rsp_key = ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK;

  uint32_t passkey = 123456; // PASS

  uint8_t auth_option = ESP_BLE_ONLY_ACCEPT_SPECIFIED_AUTH_DISABLE;

  esp_ble_gap_set_security_param(ESP_BLE_SM_SET_STATIC_PASSKEY, &passkey, sizeof(uint32_t));

  pSecurity->setAuthenticationMode(ESP_LE_AUTH_REQ_SC_MITM_BOND);

  pSecurity->setCapability(ESP_IO_CAP_OUT);

  pSecurity->setKeySize(16);

  esp_ble_gap_set_security_param(ESP_BLE_SM_ONLY_ACCEPT_SPECIFIED_SEC_AUTH, &auth_option, sizeof(uint8_t));

  pSecurity->setInitEncryptionKey(ESP_BLE_ENC_KEY_MASK | ESP_BLE_ID_KEY_MASK);

  esp_ble_gap_set_security_param(ESP_BLE_SM_SET_RSP_KEY, &rsp_key, sizeof(uint8_t));

  Serial.println("Characteristic defined! Now you can read it in your phone!");

}

 

void loop() {

  // put your main code here, to run repeatedly:

  delay(2000);

}

 

참조 사이트

https://github.com/nkolban/esp32-snippets/issues/793

 

https://github.com/espressif/esp-idf/blob/3c94b6e10a471223616564bfc9b9c88232e749e6/examples/bluetooth/gatt_security_server/main/example_ble_sec_gatts_demo.c#L555-L575

 

https://github.com/nkolban/esp32-snippets/blob/master/cpp_utils/tests/BLETests/Arduino/security/BLE_server/BLE_server_numeric_confirmation/BLE_server_numeric_confirmation.ino#L63-L67

 

위의 코드를 이전글에서 작성하였던 원격제어 코드에 합쳐 보겠다.

 

아래 코드를 업로드하고 잘 작동하는 것을 확인 하였다. 

영상은 앞선글의 영상으로 대체하니 위의 영상과 합쳐서 생각하면 될 듯 싶다.

 

다음편에는 ESP32 블루투스 2.0의 PIN CODE 페어링에 관해 살펴보겠다.

 

 

esp32_ble_uart_full_pin_code_paring.ino
0.01MB

 

최신 업데이트 유료앱(모든 안드로이드 버전 블루투스 연결 지원)

https://postpop.tistory.com/175

 

ADUCON - Arduino wireless remote control application

Arduino remote control app using a wireless module available in Arduino. Bluetooth 2.0 Classic / 4.0 BLE : HC-05, HC-06, HM-10, AT-09, BT05, ESP32, etc. Wi-Fi : ESP01, ESP8266 NodeMcu, ESP32, etc. https://play.google.com/store/apps/details?id=com.tistory.p

postpop.tistory.com

 

 

관련 글

[arduino] - 블루투스 4.0 BLE, 스마트폰 연결과 페어링(pairing), AT-09

[arduino] - 블루투스 4.0 BLE 기초 용어

[arduino] - 블루투스 4.0 BLE 이용 아두이노 및 ESP32 원격제어

[arduino] - ESP32 블루투스 4.0 BLE, 비밀번호(pin code) 이용 페어링 연결

 

 

 

+ Recent posts