Flutter 개발 Story
Flutter BLE 다루기 본문
Flutter BLE 다루기
Flutter에서 ble를 다루기 위한 대표적인 라이브러리는 flutter_blue이다.
세팅같은 것은 위의 글에서 설명해주는 데로 하면 된다.
해당 글에서는 ble를 다루는 방법을 아래와 같은 방법으로 설명할 것이다.
BLE 다루기 순서
1. BLE 디바이스 스캔
2. BLE 디바이스와 앱 연결(페어링)
3. BLE 디바이스와 통신
사실 BLE 관련 글에서 위의 1번과 2번에대한 내용의 글은 많다. 하지만 3번에 대한 내용이 없어서 이 글을 쓰게 됐다.
1. BLE 디바이스 스캔
우선 BLE 디바이스를 스캔하기 위해서는 flutter_blue 객체를 생성하고, 해당 객체를 이용해 스캔하면 된다.
FlutterBlue flutterBlue = FlutterBlue.instance;
flutterBlue.startScan(timeout: Duration(seconds: 10));
flutterBlue.scanResults.listen((results) {
for (ScanResult r in results) {
print(r.device.name);
if (r.device.name != null) {
if (r.device.name != '' && r.device.name != ' ') {
if (!foundDevice.contains(r)) {
setState(() {
foundDevice.add(r);
});
}
}
}
}
});
2. BLE 디바이스와 앱 연결(페어링)
해당 부분에서는 디바이스와 페어링하고, readCharacteristic과 writeCharactertisc을 구하고, notification 설정까지 할 것이다. (readCharacteristic과 writeCharactertistic을 구하는 이유는 3번에서 사용하기 위함인데 보통 charactersitic하나로 해결하지만, 회사에서 사용하는 ble 기기는 나눠져있다.)
//Connect to ble device
Future<void> initConnect()async{
if(_selectDevice != null){
try{
if(_alreadyConnected){
await disconnectBleDevice();
}else{
await _selectDevice.connect().then((_) => {
matchServiceCharactertistic(),
_alreadyConnected = true
});
}
}catch(e){
log('$e in initConnect',name: tag);
}
}else{
log('Device is null(in initConnect)',name: tag);
}
}
//Find matching service, charactertistic with own service uuid and charactertistic uuid
Future<void> matchServiceCharactertistic()async{
try{
List<BluetoothService> services = await _selectDevice.discoverServices();
services.forEach((service) {
if(service.uuid.toString() == _bleProtocol.serviceUUID){
service.characteristics.forEach((characteristic) async{
if(characteristic.uuid.toString() == _bleProtocol.writeCharacteristicUUID){
writeCharacteristic = characteristic;
}else if(characteristic.uuid.toString() == _bleProtocol.readCharacteristicUUID){
readCharacteristic = characteristic;
await setNotification(readCharacteristic);
}
});
}
});
}catch(e){
log('$e in matchServiceCharactertistic',name: tag);
}
}
//Read data from ble device
Future<void> setNotification(BluetoothCharacteristic _readCharactertistic)async{
try{
await _readCharactertistic.setNotifyValue(!_readCharactertistic.isNotifying);
await _readCharactertistic.read();
}catch(e){
log('$e in setNotification',name: tag);
}
}
위의 UUID들은 BLE 디바이스 기기에 정의돼 있기때문에 해당 UUID을 찾아야한다.
3.BLE 디바이스와 통신
//Communicate with ble device
Future<void> writeDescriptorOnDevice() async{
try{
writeCharacteristic.write(_bleProtocol.temperature, withoutResponse: true).then((value){
readCharacteristic.value.listen((event) {
print('data : $event');
});
});
}catch(e){
log('$e in writeDescriptorOnDevice',name: tag);
}
}
2번에서 readCharactertisc에 notification을 설정한 이유가 3번에서 나온다. writeCharacteristic을 통해 디바이스에 데이터를 보내면, 디바이스에서 오는 데이터를 readCharactertisc에서 받기 때문이다. notification을 열어놔야지 listen 상태가 된다.
'Flutter' 카테고리의 다른 글
Flutter _ Retrofit (0) | 2021.05.24 |
---|---|
위젯) SingleChildScrollView (0) | 2021.05.11 |
Provider 패턴 (0) | 2021.04.26 |
State란? (0) | 2021.04.15 |
StateManagement(InheritedWidget, Provider) (0) | 2021.04.15 |
Comments