いろいろ試しましたが、普通の方法では使うことができませんでしたので、ちょっと黒魔術を使っています。
M5StickCで実験しましたが、コード的には単なるESP32です。
※現時点の情報ですので、最新情報はM5StickC非公式日本語リファレンスを確認してください。
Arduino IDE版ESP32 1.0.2ライブラリの問題点
リセットがかかる
特定のデバイスでCharacteristicを取得しようとするとリセットがかかります!
結構検索して事例が出てきますが、なかなかライブラリが更新されません。
- C:\Users\%USERNAME%\AppData\Local\Arduino15\packages\esp32\hardware\esp32\1.0.2\libraries\BLE\src\BLERemoteService.cpp
Windowsだと上記のファイルが原因です。
void BLERemoteService::retrieveCharacteristics() {
log_v(">> getCharacteristics() for service: %s", getUUID().toString().c_str());
removeCharacteristics(); // Forget any previous characteristics.
uint16_t offset = 0;
esp_gattc_char_elem_t result;
while (true) {
uint16_t count = 10; // this value is used as in parameter that allows to search max 10 chars with the same uuid
esp_gatt_status_t status = ::esp_ble_gattc_get_all_char(
getClient()->getGattcIf(),
getClient()->getConnId(),
m_startHandle,
m_endHandle,
&result,
&count,
offset
);
count = 10となっていますが、ここが1以外だと正しく取得できませんでいした。
ESP32のBLEライブラリ作者の作業用Githubだとここが、1になっていました。ただし、ESP32にはこの更新は取り込まれていません。
このリポジトリもアーカイブ状態になっているので、今後どうなるんだろう?
同一CharacteristicUUIDがあると1つしか取得できない
これはCharacteristicUUIDをキーにしたMapでgetCharacteristics()で返却してくるので、同一UUIDがあると1つにまとめられてしまいます。
キーボード系デバイスだと同じUUIDが複数あったりするので、個別キーが取得できなくなります。
解決方法
ライブラリの書き換え
このリポジトリのBLERemoteService.cppとBLERemoteService.hを、ESP32のライブラリに上書きすれば動くようになります。
個人的にはライブラリには極力手を入れたくないので、他の解決方法も探しました。
ラッパー関数を作って無理やり修正する
エラーがでる箇所はわかっているので、そこの処理だけ書き換えた関数を作ってみました。しかしながらBLERemoteCharacteristicクラスのコンストラクタがPrivateなのです!
private: BLERemoteCharacteristic(uint16_t handle, BLEUUID uuid, esp_gatt_char_prop_t charProp, BLERemoteService* pRemoteService); friend class BLEClient; friend class BLERemoteService; friend class BLERemoteDescriptor;
フレンドクラスを指定しているので、BLERemoteServiceの内部からは呼べるのですが、自作クラスからは呼び出せません。
そこで、アクセス指定子の無効化を参考にして、黒魔術で乗り切ることにしました。
#ifndef __BLEDEVICE_EX_H__
#define __BLEDEVICE_EX_H__
// 内部関数などにアクセスするためにprivateを無効化する
#define private public
#include "BLEDevice.h"
#undef private
std::map<uint16_t, BLERemoteCharacteristic*>* retrieveCharacteristicsEx( BLERemoteService* pRemoteService ) {
ESP_LOGD(LOG_TAG, ">> retrieveCharacteristics() for service: %s", getUUID().toString().c_str());
pRemoteService->removeCharacteristics(); // Forget any previous characteristics.
uint16_t offset = 0;
esp_gattc_char_elem_t result;
while (true) {
uint16_t count = 1; // this value is used as in parameter that allows to search max 10 chars with the same uuid
esp_gatt_status_t status = ::esp_ble_gattc_get_all_char(
pRemoteService->getClient()->getGattcIf(),
pRemoteService->getClient()->getConnId(),
pRemoteService->m_startHandle,
pRemoteService->m_endHandle,
&result,
&count,
offset
);
if (status == ESP_GATT_INVALID_OFFSET || status == ESP_GATT_NOT_FOUND) { // We have reached the end of the entries.
break;
}
if (status != ESP_GATT_OK) { // If we got an error, end.
ESP_LOGE(LOG_TAG, "esp_ble_gattc_get_all_char: %s", BLEUtils::gattStatusToString(status).c_str());
break;
}
if (count == 0) { // If we failed to get any new records, end.
break;
}
ESP_LOGD(LOG_TAG, "Found a characteristic: Handle: %d, UUID: %s", result.char_handle, BLEUUID(result.uuid).toString().c_str());
// We now have a new characteristic ... let us add that to our set of known characteristics
BLERemoteCharacteristic *pNewRemoteCharacteristic = new BLERemoteCharacteristic(
result.char_handle,
BLEUUID(result.uuid),
result.properties,
pRemoteService
);
pRemoteService->m_characteristicMap.insert(std::pair<std::string, BLERemoteCharacteristic*>(pNewRemoteCharacteristic->getUUID().toString(), pNewRemoteCharacteristic));
pRemoteService->m_characteristicMapByHandle.insert(std::pair<uint16_t, BLERemoteCharacteristic*>(result.char_handle, pNewRemoteCharacteristic));
offset++; // Increment our count of number of descriptors found.
} // Loop forever (until we break inside the loop).
pRemoteService->m_haveCharacteristics = true; // Remember that we have received the characteristics.
ESP_LOGD(LOG_TAG, "<< retrieveCharacteristics()");
return &pRemoteService->m_characteristicMapByHandle;
} // retrieveCharacteristicsEx
#endif
素晴らしい!
しかしながら、もちろん非推奨です。ライブラリを書き換えるのと、黒魔術だと同じぐらいグレーな気がします。
最新版のretrieveCharacteristics()を元に、privateに直接アクセスして同じような処理をしています。
複数UUID問題に関しては、内部にm_characteristicMapByHandleというMapがあるのですが、getCharacteristicsByHandle()が1.0.2だと実装されていないので、直接返却しています。
サンプルスケッチ
/**
A BLE client example that is rich in capabilities.
There is a lot new capabilities implemented.
author unknown
updated by chegewara
*/
#include "BLEDeviceEx.h"
// The remote service we wish to connect to.
static BLEUUID serviceUUID("1812");
static boolean doConnect = false;
static boolean connected = false;
static boolean doScan = false;
static BLEAdvertisedDevice* myDevice;
static void notifyCallback(
BLERemoteCharacteristic* pBLERemoteCharacteristic,
uint8_t* pData,
size_t length,
bool isNotify) {
Serial.print("Notify callback for characteristic ");
Serial.print(pBLERemoteCharacteristic->getUUID().toString().c_str());
Serial.print(" of data length ");
Serial.print(length);
Serial.print(" data: ");
for ( int i = 0 ; i < length ; i++ ) {
Serial.printf( "%02X ", pData[i] );
}
Serial.println();
}
class MyClientCallback : public BLEClientCallbacks {
void onConnect(BLEClient* pclient) {
}
void onDisconnect(BLEClient* pclient) {
connected = false;
Serial.println("onDisconnect");
}
};
bool connectToServer() {
Serial.print("Forming a connection to ");
Serial.println(myDevice->getAddress().toString().c_str());
BLEClient* pClient = BLEDevice::createClient();
Serial.println(" - Created client");
pClient->setClientCallbacks(new MyClientCallback());
// Connect to the remove BLE Server.
pClient->connect(myDevice); // if you pass BLEAdvertisedDevice instead of address, it will be recognized type of peer device address (public or private)
Serial.println(" - Connected to server");
// Obtain a reference to the service we are after in the remote BLE server.
BLERemoteService* pRemoteService = pClient->getService(serviceUUID);
if (pRemoteService == nullptr) {
Serial.print("Failed to find our service UUID: ");
Serial.println(serviceUUID.toString().c_str());
pClient->disconnect();
return false;
}
Serial.println(" - Found our service");
std::map<uint16_t, BLERemoteCharacteristic*>* mapCharacteristics = retrieveCharacteristicsEx(pRemoteService);
for (std::map<uint16_t, BLERemoteCharacteristic*>::iterator i = mapCharacteristics->begin(); i != mapCharacteristics->end(); ++i) {
if (i->second->canNotify()) {
Serial.println(" - Add Notify");
i->second->registerForNotify(notifyCallback);
}
}
connected = true;
return true;
}
/**
Scan for BLE servers and find the first one that advertises the service we are looking for.
*/
class MyAdvertisedDeviceCallbacks: public BLEAdvertisedDeviceCallbacks {
/**
Called for each advertising BLE server.
*/
void onResult(BLEAdvertisedDevice advertisedDevice) {
Serial.print("BLE Advertised Device found: ");
Serial.println(advertisedDevice.toString().c_str());
// We have found a device, let us now see if it contains the service we are looking for.
if (advertisedDevice.haveServiceUUID() && advertisedDevice.isAdvertisingService(serviceUUID)) {
BLEDevice::getScan()->stop();
myDevice = new BLEAdvertisedDevice(advertisedDevice);
doConnect = true;
doScan = true;
} // Found our server
} // onResult
}; // MyAdvertisedDeviceCallbacks
void setup() {
Serial.begin(115200);
Serial.println("Starting Arduino BLE Client application...");
BLEDevice::init("");
// Retrieve a Scanner and set the callback we want to use to be informed when we
// have detected a new device. Specify that we want active scanning and start the
// scan to run for 5 seconds.
BLEScan* pBLEScan = BLEDevice::getScan();
pBLEScan->setAdvertisedDeviceCallbacks(new MyAdvertisedDeviceCallbacks());
pBLEScan->setInterval(1349);
pBLEScan->setWindow(449);
pBLEScan->setActiveScan(true);
pBLEScan->start(5, false);
} // End of setup.
// This is the Arduino main loop function.
void loop() {
// If the flag "doConnect" is true then we have scanned for and found the desired
// BLE Server with which we wish to connect. Now we connect to it. Once we are
// connected we set the connected flag to be true.
if (doConnect == true) {
if (connectToServer()) {
Serial.println("We are now connected to the BLE Server.");
} else {
Serial.println("We have failed to connect to the server; there is nothin more we will do.");
}
doConnect = false;
}
// If we are connected to a peer BLE Server, update the characteristic each time we are reached
// with the current time since boot.
if (connected) {
} else if (doScan) {
BLEDevice::getScan()->start(0); // this is just eample to start scan after disconnect, most likely there is better way to do it in arduino
}
delay(1000); // Delay a second between loops.
} // End of loop
ほぼSDKのスケッチのままですが、BLEDevice.hのかわりに黒魔術で汚染されたBLEDeviceEx.hを読み込んでいます。
動作例(ダイソーシャッターリモコン)
characteristic一覧
| UUID | 役割 | 機能 |
| 2a4a | HID Information | Broadcast:X Read:O WriteNoResponse:X Write:X Notify:X Indicate:X |
| 2a4b | Report Map | Broadcast:X Read:O WriteNoResponse:X Write:X Notify:X Indicate:X |
| 2a4c | HID Control Point | Broadcast:X Read:X WriteNoResponse:O Write:X Notify:X Indicate:X |
| 2a4d | Report | Broadcast:X Read:O WriteNoResponse:X Write:X Notify:O Indicate:X |
| 2a4d | Report | Broadcast:X Read:O WriteNoResponse:X Write:X Notify:O Indicate:X |
| 2a4e | Protocol Mode | Broadcast:X Read:O WriteNoResponse:O Write:X Notify:X Indicate:X |
複数のReportがありますが、1.0.2のライブラリだと1つしか取得することができませんでした。このシャッター以外のリモコンも試してみたのですが、どっちはReportが6個もありました!
実行時ログ
BLE Advertised Device found: Name: AB Shutter3 , Address: ff:ff:c1:??:??:??, appearance: 961, serviceUUID: 00001812-0000-1000-8000-00805f9b34fb Forming a connection to ff:ff:c1:??:??:?? - Created client - Connected to server - Found our service - Add Notify - Add Notify We are now connected to the BLE Server. Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 01 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 28 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 01 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00
ダイソーのシャッターは「AB Shutter3」って名前で、HIDとして動いています。
2つNotifyが登録されていますので、2つのReportが正しく認識しているのがわかります。
iOSキー
Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 01 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00
2つあるキーのうち、iOSキーを押した場合、01 00(ボリュームアップ)と00 00(キーアップ)が飛んできます。
Androidキー
Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 28 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 01 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00 Notify callback for characteristic 00002a4d-0000-1000-8000-00805f9b34fb of data length 2 data: 00 00
Androidキーを押した場合には、00 28(エンター)と01 00 (ボリュームアップ) と00 00(キーアップ)が2つ飛んできます。
エンターとボリュームアップは別のReportから飛んでくるので、pBLERemoteCharacteristic->getHandle()でどのHandleかを確かめることで、その区別もつきます。キーアップはHandleみないとどっちのキーがアップしたのかわからないですが、この機材の場合にはそこまで見なくても判定できそうです。
参考サイト
まとめ
ちょっとBluetoothは不安定なので、どこまで実用的に使えるかは微妙なところがあります。ブツブツ切れたり、わりとハングアップしたりとケアをしないといけないことが多そうです。
サンプルスケッチは今後なるべくGithubにも保存して公開していくつもりです。



コメント