昨日投稿した「BluetoothSerial」のトラブルに関する記事の解決策が判明したので、私のための備忘録も兼ねてご紹介。
解決策ですが…プラグインを変更したらうまくいきました!
正攻法ではないような気もしますが、とりあえず解決したから良しとします!
変更したプラグインはこちらです。
GitHub – don/cordova-plugin-ble-central: Bluetooth Low Energy (BLE) Central plugin for Apache Cordova (aka PhoneGap)
https://github.com/don/cordova-plugin-ble-central
インストールには下記のコマンドを実行します。
cordova plugin add cordova-plugin-ble-central
この時、cordova-plugin-compat も同時にインストールされますが、もし失敗したら手動で入れ直してください。
私の環境ではこちらのプラグインの導入に失敗したので、一度プラットフォームを削除してから、cordova-plugin-compat を再度インストールしました。
あとはメソッドの一覧を組み合わせて、端末の検出~接続~データ取得までを行えました。
サンプルコードはこちらから。
ちなみに、React で書いています。
import React, { Component } from 'react';
class App extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
result: null,
};
this.scanDevices = this.scanDevices.bind(this);
this.connectDevice = this.connectDevice.bind(this);
this.readDeviceData = this.readDeviceData.bind(this);
}
componentDidMount() {
const that = this;
if (window.device.platform === 'Android') {
window.ble.enable(function() {
that.scanDevices();
}, function(error) {
that.setState({ error: "Bluetooth を有効にしてください" });
console.log("Bluetooth を有効にしてください");
});
} else {
this.scanDevices();
}
}
componentWillUnmount() {
window.ble.stopScan(function() {
console.log('stop scan');
}, function(error) {
console.log(error);
});
}
scanDevices() {
const that = this;
window.ble.startScanWithOptions([], { reportDuplicates: true }, function(result) {
that.connectDevice(result.id);
}, function(error) {
console.log(error);
that.setState({ error: "デバイス情報を取得できませんでした" });
});
}
connectDevice(deviceId) {
const that = this;
window.ble.connect(deviceId, function(result) {
that.readDeviceData(result);
}, function(error) {
console.log('デバイス接続 失敗');
console.log(error);
that.setState({ error: "デバイスとの接続に失敗しました" });
});
}
readDeviceData(result) {
const that = this;
window.ble.read(result.id, result.characteristics[0].service, result.characteristics[0].characteristic,
function(data) {
console.log("Hooray we have data"+JSON.stringify(data));
that.setState({ result: JSON.stringify(data) });
},
function(failure) {
console.log("Failed to read characteristic from device.");
console.log(failure);
that.setState({ error: "端末のデータの取得に失敗しました" });
}
);
}
render() {
return (
<div className="App">
<p>{this.state.result}</p>
<p>{this.state.error}</p>
</div>
);
}
}
export default App;
とりあえずのサンプルアプリで見た目などは全然こだわっていませんので、その点はご了承ください。
ただしこのコードを実行したところ、端末には接続できたのですが、データが Empty で取得できませんでした…。
こちらは引き続き修正中です。
以上、BLE で端末と接続できない時の対処法でした。
Cordova のプラグインはたくさんあるので環境に合わせて使い分ける必要がありますね。
個人的には、プラグイン名で検索してみて参考サイトがある程度見つかるかや、Cordova の公式サイトの Plugin Search でヒットしたものを使うようにしています。
どなたかのご参考になれば幸いです。