1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
|
import 'dart:io' show Platform;
import 'package:badge/device_details.dart';
import 'package:badge/device_scan_select.dart';
import 'package:flutter/material.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:logger/logger.dart';
import 'package:permission_handler/permission_handler.dart';
var logger = Logger(printer: PrettyPrinter());
class ScanPage extends StatefulWidget {
const ScanPage({super.key, required this.title});
// Original doc: Fields in a Widget subclass are always marked "final".
final String title;
@override
State<ScanPage> createState() => _ScanPageState();
}
class _ScanPageState extends State<ScanPage> {
List<ScanResult> scanResults = [];
bool isScanning = false;
ScanResult? selectedDevice;
void _doConnect() async {
var dev = selectedDevice?.device;
if (dev == null) return;
//???
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => DeviceDetailsScreen(btDevice: dev),
),
);
}
void _doScan() async {
var system = await FlutterBluePlus.systemDevices([]);
for (var d in system) {
logger.i('${d.platformName} already connected to! ${d.remoteId}');
}
setState(() {
selectedDevice = null;
scanResults = [];
isScanning = true;
});
var subscription = FlutterBluePlus.scanResults.listen(
onScanResult,
onError: (e) => logger.e(e),
);
// either this, or the cancel in the finally block, should do the same?
FlutterBluePlus.cancelWhenScanComplete(subscription);
try {
if (Platform.isAndroid) {
// Ehhhh... can't have both keyword/services
await FlutterBluePlus.startScan(
withKeywords: ["NimBLE"],
timeout: Duration(seconds: 5),
);
} else {
// for Linux, which can't do advNames (but platformname, for whatever reason)
// msd doesn't work, either????
await FlutterBluePlus.startScan(
//withMsd: [MsdFilter(0xffff, data: ascii.encode("uvok"))],
timeout: Duration(seconds: 5),
);
}
// wait for scanning to stop
await FlutterBluePlus.isScanning.where((val) => val == false).first;
} finally {
subscription.cancel();
setState(() {
isScanning = false;
});
}
}
void onScanResult(List<ScanResult> results) {
if (results.isNotEmpty) {
for (var r in results.where(
(d) => d.rssi > -90 && !_deviceInResults(d),
)) {
logger.i(
'${r.device.remoteId}: "${r.device.platformName}" / "${r.device.advName}" / "${r.advertisementData.advName}" found!',
);
scanResults.add(r);
}
setState(() {});
}
}
bool _deviceInResults(ScanResult incomingDev) => scanResults.any(
(existingDev) => existingDev.device.remoteId == incomingDev.device.remoteId,
);
Future getPermissions() async {
try {
await Permission.bluetooth.request();
} catch (e) {
logger.e(e.toString());
}
}
void btHandler(BluetoothAdapterState event) {
logger.i(event);
switch (event) {
case BluetoothAdapterState.on:
break;
default:
break;
}
}
@override
void initState() {
super.initState();
getPermissions();
FlutterBluePlus.adapterState.listen(btHandler);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
// TRY THIS: Invoke "debug painting" (choose the "Toggle Debug Paint"
// action in the IDE, or press "p" in the console), to see the
// wireframe for each widget.
mainAxisAlignment: MainAxisAlignment.center,
spacing: 24,
children: <Widget>[
SizedBox(height: 15),
Row(
mainAxisAlignment: MainAxisAlignment.center,
spacing: 15.0,
children: [
ElevatedButton(
onPressed: isScanning ? null : _doScan,
child: isScanning ? Text("Scanning...") : Text("Start scan"),
),
ElevatedButton(
onPressed: (selectedDevice == null || isScanning)
? null
: _doConnect,
child: Text("Connect"),
),
],
),
Expanded(
child: DeviceScanSelection(
items: scanResults,
onItemSelected: (item) {
setState(() => selectedDevice = item);
},
),
),
],
),
),
);
}
}
|