728x90
반응형
블루투스 데이터 송수신
이번 글에서는 UUID, service와 characteristics를 이용해서 블루투스 데이터 송수신을 구현합니다.
위 내용을 모르면 구현하기 어렵습니다. 먼저 아래 글을 읽고 구현하세요.
[자전거 도난 방지] 05. 블루투스 이해하기
블루투스 이해하기 블루투스를 연결하고 send와 recv를 통해 데이터를 송수신하는 줄 알았습니다. 하지만, UUID, service와 characteristics의 개념을 알고 있어야 통신할 수 있었습니다. UUID UUID는 블루투
gogomake.tistory.com
데이터 수신
1. service 찾기
데이터 송수신을 하기 위해 특정 service를 이용해야 합니다. 아래 코드는 특정 uuid를 이용해서 service를 찾는 코드입니다.
꼭! 원하는 service의 uuid를 확인하고 접근해주세요.
static void find(List<BluetoothService> services) async {
for (BluetoothService service_ in services) {
if (service_.uuid.toString() == "6e400001-b5a3-f393-e0a9-e50e24dcca9e") {
isFind = true;
service = service_;
...
2. 데이터 수신
characteristic를 찾고 setNotifyValue를 true로 세팅해야 합니다.
static void find(List<BluetoothService> services) async {
...
// 원하는 characteristic 찾기
for (BluetoothCharacteristic characteristic
in service.characteristics) {
// 데이터 수신 characteristic
if (characteristic.uuid.toString() ==
"6e400003-b5a3-f393-e0a9-e50e24dcca9e") {
debugPrint("Characteristic: ${characteristic.uuid}");
// 데이터 수신
readCharacteristic = characteristic;
readCharacteristic.setNotifyValue(true);
}
...
다른 클래스에서 사용할 경우 다음과 같이 코드를 작성하면 됩니다.
List<String> get dataLogs => BluetoothControlService.dataLogs;
late StreamSubscription<List<int>> _lastValueSubscription;
@override
void initState() {
super.initState();
if (BluetoothControlService.isFind) {
// 데이터 수신
_lastValueSubscription = BluetoothControlService
.readCharacteristic.lastValueStream
.listen((value) {
dataLogs.add(String.fromCharCodes(value)); // 수신 데이터 저장
setState(() {});
});
}
...
@override
void dispose() {
if (BluetoothControlService.isFind) {
_lastValueSubscription.cancel();
}
...
데이터 송신
데이터를 송신은 간단합니다. 위에서 찾은 송신 characteristic을 이용해서 value를 write 하면 됩니다.
static void find(List<BluetoothService> services) async {
...
// 데이터 전송 characteristic
if (characteristic.uuid.toString() ==
"6e400002-b5a3-f393-e0a9-e50e24dcca9e") {
debugPrint("Characteristic: ${characteristic.uuid}");
writeCharacteristic = characteristic;
}
...
// 데이터 전송
static void write(List<int> value) async {
if (isFind) {
await writeCharacteristic.write(value);
}
}
다음 계획
데이터 송수신 구현을 완료했습니다. 다음 계획은 데이터를 이용해서 도난 알람 신호를 구현하도록 하겠습니다.
728x90
반응형
'OpenCowork > 자전거 도난 방지' 카테고리의 다른 글
[자전거 도난 방지] 07. 기능구현(1) (0) | 2023.10.28 |
---|---|
[자전거 도난 방지] 05. 블루투스 이해하기 (0) | 2023.10.18 |
[자전거 도난 방지] 04. 아두이노 블루투스 모듈 사용하기 (0) | 2023.10.15 |
[자전거 도난 방지] 03. 블루투스 기능 구현(2) (1) | 2023.10.14 |
[자전거 도난 방지] 02. 블루투스 기능 구현(1) (0) | 2023.10.12 |