-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestScreen.dart
More file actions
219 lines (204 loc) · 7.2 KB
/
TestScreen.dart
File metadata and controls
219 lines (204 loc) · 7.2 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
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import 'dart:convert';
import 'dart:math';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:mesh_base_flutter/mesh_base_flutter.dart';
import 'package:file_picker/file_picker.dart';
final PREFIX = "my_example_app";
class ExampleTestScreen extends StatefulWidget {
const ExampleTestScreen({super.key});
@override
State<ExampleTestScreen> createState() => _BleTestScreenState();
}
class _BleTestScreenState extends State<ExampleTestScreen> {
final mesh = MeshBaseFlutter();
final List<Device> _connected = [];
bool _meshOn = false, _bleOn = false;
String _selfId = '';
String _message = '';
late final MeshManagerListener _listener;
Widget container = Container();
@override
void initState() {
super.initState();
_listener = MeshManagerListener(
onDataReceivedForSelf: _handleData,
onStatusChange: _updateStatus,
onNeighborConnected: (d) => setState(() => _connected.add(d)),
onNeighborDisconnected:
(d) =>
setState(() => _connected.removeWhere((x) => x.uuid == d.uuid)),
onError: (e) => _showSnack('Error: $e'),
);
// Subscribe and turn on
debugPrint("$PREFIX subscribing");
mesh.subscribe(_listener).then((_) async {
debugPrint("$PREFIX turning on");
await mesh.turnOn();
debugPrint("$PREFIX turned on");
});
mesh.getId().then((id) {
setState(() {
_selfId = id;
});
});
}
@override
void dispose() {
mesh.unsubscribe();
super.dispose();
}
void _handleData(MeshProtocol protocol) {
if (protocol.messageType == ProtocolType.FILE_TRANSFER) {
Uint8List jpegData = Uint8List.sublistView(protocol.body, 12);
debugPrint("chunk received");
setState(() {
container = Image.memory(jpegData);
});
return;
}
final text = utf8.decode(protocol.body);
_showSnack('Recv: "$text" from ${protocol.sender}');
if (protocol.messageType == ProtocolType.RAW_BYTES_MESSAGE &&
protocol.destination != BROADCAST_UUID) {
// auto‐reply
final replyText = 'Reply to "$text"';
final reply = MeshProtocol(
messageType: ProtocolType.RAW_BYTES_MESSAGE,
remainingHops: 10,
messageId: protocol.messageId,
sender: protocol.destination,
destination: protocol.sender,
body: Uint8List.fromList(utf8.encode(replyText)),
);
mesh.send(protocol: reply, keepMessageId: true).then((res) {
if (res.acked) {
_showSnack('Reply acked');
} else if (res.error != null) {
_showSnack('Reply error: ${res.error}');
} else if (res.response != null) {
_showSnack(
'Reply received (should not happen): ${res.response.toString()}',
);
}
});
}
}
void _updateStatus(MeshStatus status) {
debugPrint("$PREFIX new status update");
setState(() {
_meshOn = status.isOn;
_bleOn = status.statuses[ConnectionType.BLE]?.isOn ?? false;
});
}
void _showSnack(String msg) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(msg), duration: const Duration(seconds: 1)),
);
}
@override
Widget build(BuildContext c) {
return Column(
children: [
Text(
'Mesh: ${_meshOn ? 'ON' : 'OFF'} BLE: ${_bleOn ? 'ON' : 'OFF'}',
),
const SizedBox(height: 8),
ElevatedButton(
onPressed: () => _meshOn ? mesh.turnOff() : mesh.turnOn(),
child: Text(_meshOn ? 'Turn Off' : 'Turn On'),
),
const SizedBox(height: 16),
Expanded(
child: ListView.builder(
itemCount: _connected.length,
itemBuilder: (_, i) {
final d = _connected[i];
return ListTile(
title: Text('${d.name} (${d.uuid})'),
trailing: ElevatedButton(
onPressed: () async {
FilePickerResult? result = await FilePicker.platform
.pickFiles(
type: FileType.image,
withData: true, // important to get bytes
);
final int messageId = Random().nextInt(1 << 30);
if (result != null && result.files.single.bytes != null) {
Uint8List fileBytes = result.files.single.bytes!;
final protocol = MeshProtocol(
messageType: ProtocolType.FILE_TRANSFER,
remainingHops: 10,
messageId: messageId,
sender: _selfId,
destination: d.uuid,
body: fileBytes,
);
mesh.send(protocol: protocol);
}
},
child: const Text("Send img"),
),
// trailing: ElevatedButton(
// onPressed: () {
// final protocol = MeshProtocol(
// messageType: ProtocolType.RAW_BYTES_MESSAGE,
// remainingHops: -1,
// messageId: -1,
// sender: _selfId,
// destination: d.uuid,
// body: Uint8List.fromList(utf8.encode(_message)),
// );
// mesh.send(protocol: protocol, keepMessageId: false).then((
// res,
// ) {
// if (res.acked) {
// _showSnack('Ack for "$_message"');
// } else if (res.error != null) {
// _showSnack('Send error: ${res.error}');
// } else if (res.response?.body != null) {
// _showSnack(
// "Response received from :${d.uuid} ${utf8.decode(res.response!.body)}",
// );
// }
// });
// },
// child: const Text('Send'),
// ),
);
},
),
),
container,
TextButton(
onPressed: () async {
final protocol = MeshProtocol(
messageType: ProtocolType.RAW_BYTES_MESSAGE,
remainingHops: -1,
messageId: -1,
sender: _selfId,
destination: BROADCAST_UUID,
body: Uint8List.fromList(utf8.encode(_message)),
);
mesh.send(protocol: protocol, keepMessageId: false).then((res) {
if (res.acked) {
_showSnack('Ack for broadcast"$_message"');
} else if (res.error != null) {
_showSnack('Send error: ${res.error}');
} else if (res.response?.body != null) {
_showSnack(
'Response received (should not happen for broadcast): ${utf8.decode(res.response!.body)}',
);
}
});
},
child: Text("broadcast"),
),
TextField(
decoration: const InputDecoration(labelText: 'Message'),
onChanged: (v) => _message = v,
),
],
);
}
}