obniz BLE/Wi-Fi Gateway での BLEデバイスとの接続エラーについて
いつもお世話になっております。
下記のようなコードであるBLEデバイスのperipheralで
await peripheral.connectWait();
を実行した時エラーが発生し接続できません。
chatchしたeの内容は
ObnizBleHciStateError: Connection Failed to be Established /
Synchronization Timeout {"peripheralAddress":"#####"}
というものでした。
また、await peripheral.connectWait(); を実行すると
obniz.ble.scan.onfinish がコールされscanが停止するようです。
再スキャンしようと
await obniz.ble.scan.startWait();
を実行するとたまにエラーが発生します。
chatchしたeの内容は
ObnizBleScanStartError: startScanning enable=true was failed.
Maybe Connection to a device is under going. state=12(Command Disallowed )
というものでした。
なにか対策はありますでしょうか?
よろしくお願いします。
obniz = new Obniz(id);
obniz.onconnect = async function(){
await obniz.ble.initWait();
obniz.ble.scan.onfind = async function(peripheral){
try{
await peripheral.connectWait();
}catch(e){
console.log("connection error", e);
}
}
obniz.ble.scan.onfinish = async function(peripherals, error){
console.log("scan timeout!");
try{
await obniz.ble.scan.startWait();
}catch(e){
console.log("can't scan", e);
}
}
await obniz.ble.scan.startWait();
}
-
正式なコメント
obnizのデバイスで、ESP32がCPUのものは接続を開始して終了するまではscanを停止しなければいけません。
エラーとなったのは終了時に再スキャンを実施しようとしてまだ接続が確立していないとエラーになります。
継続的にスキャンかつデバイスにも接続する場合はスキャンと接続を分離するほうが良いです。
そこまですぐに見つけなくても良い場合はこの関数でスキャンをawaitで待機することが出来ます。
https://obniz.github.io/obniz/obnizjs/classes/obnizcore.components.ble.hci.blescan.html#startallwait
obniz.onconnect = async () => {
// onlineである限りずっと繰り返される
obniz.onloop = async () => {
// 30秒(デフォルト)スキャンして見つかったものを返却
var peripherals = await obniz.ble.scan.startAllWait();
for (const p of peripherals) {
try{
// TODO: ここで本当につなぎたいものかどうか判別
await peripheral.connectWait();
}catch(e){
console.log("connection error", e);
}
}
}
}これであればスキャンと接続は同時に存在させずに実施でき、上記のエラーは発生しません。
見つけたらすぐに接続したい場合は
- 対象を設定して見つけるまで待機する関数を利用する
- onfindを利用するが、見つけたらscan.endWait()でスキャンを停止してscanを抜けてから接続する
となります。
どちらにしても見つけ次第スキャンを止めて、接続し終わったらscanに戻るというのは同じです。 -
コネクト(await peripheral.connectWait();)
の処理が終わってから
スキャン(await obniz.ble.scan.startWait();)
を実行するようにしたらエラーは発生しなくなりました。
ご丁寧な解説ありがとうございました。0
サインインしてコメントを残してください。
コメント
2件のコメント