-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic_example.dart
More file actions
101 lines (84 loc) · 2.58 KB
/
basic_example.dart
File metadata and controls
101 lines (84 loc) · 2.58 KB
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
import 'dart:typed_data';
import 'package:flutter_webhid/flutter_webhid.dart';
void main() async {
if (!WebHID.isSupported) {
print('WebHID not supported. Try Chrome/Edge 89+');
return;
}
final webHid = WebHID.instance;
if (webHid == null) {
print('Failed to access WebHID');
return;
}
print('WebHID Example\n');
try {
await _listDevices(webHid);
await _requestDevice(webHid);
_listenConnections(webHid);
} catch (e) {
print('Error: $e');
}
}
Future<void> _listDevices(WebHID webHid) async {
final devices = await webHid.getDevices();
if (devices.isEmpty) {
print('No authorized devices\n');
return;
}
print('Authorized devices:');
for (final device in devices) {
print(' ${device.productName}');
print(' VID: 0x${device.vendorId.toRadixString(16).padLeft(4, '0')}');
print(' PID: 0x${device.productId.toRadixString(16).padLeft(4, '0')}');
}
print('');
}
Future<void> _requestDevice(WebHID webHid) async {
print('Requesting device...');
try {
final devices = await webHid.requestDevice(RequestOptions(filters: []));
if (devices.isEmpty) return;
final device = devices.first;
print('Selected: ${device.productName}\n');
await device.open();
_printDeviceInfo(device);
print('Listening for reports (10s)...');
final sub = device.onInputReport.listen((event) {
print('Report ${event.reportId}: ${_hex(event.data)}');
});
await Future.delayed(Duration(seconds: 10));
await sub.cancel();
await device.close();
print('Device closed\n');
} on HIDException catch (e) {
print('HID error: $e\n');
}
}
void _printDeviceInfo(Device device) {
print('VID: 0x${device.vendorId.toRadixString(16).padLeft(4, '0')}');
print('PID: 0x${device.productId.toRadixString(16).padLeft(4, '0')}');
print('Collections: ${device.collections.length}');
for (var i = 0; i < device.collections.length; i++) {
final c = device.collections[i];
print(
' [$i] Usage ${c.usagePage.toRadixString(16)}:${c.usage.toRadixString(16)}',
);
if (c.inputReports != null) {
print(' Input reports: ${c.inputReports!.length}');
}
}
print('');
}
void _listenConnections(WebHID webHid) {
webHid.onConnect.listen((e) => print('Connected: ${e.device.productName}'));
webHid.onDisconnect.listen(
(e) => print('Disconnected: ${e.device.productName}'),
);
}
String _hex(Uint8List bytes) {
final s = bytes
.take(16)
.map((b) => b.toRadixString(16).padLeft(2, '0'))
.join(' ');
return bytes.length > 16 ? '$s... (${bytes.length}B)' : s;
}