/
main.dart
524 lines (433 loc) · 13.6 KB
/
main.dart
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_hue/flutter_hue.dart';
import 'package:uni_links/uni_links.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
static const double padding = 15.0;
/// Whether or not the page is loading some async action.
bool isLoading = false;
/// The IP address of the bridges on the network.
final List<String> bridgeIps = [];
/// Controls the bridge discovery process.
final DiscoveryTimeoutController timeoutController =
DiscoveryTimeoutController(timeoutSeconds: 25);
/// Cancels the "first contact" action.
VoidCallback? onContactCancel;
/// The bridge that [firstContact] decided to connect with.
Bridge? bridge;
/// All of the Philips Hue resources connected to [bridge].
HueNetwork? hueNetwork;
/// The light that is being worked with in the "writing data" section.
Light? light;
/// Watches for deep links.
late final StreamSubscription deepLinkStream;
@override
void initState() {
super.initState();
deepLinkStream = uriLinkStream.listen(
(Uri? uri) {
if (uri == null) return;
final int start = uri.toString().indexOf("?");
String queryParams = uri.toString().substring(start);
Uri truncatedUri = Uri.parse(queryParams);
try {
final String? pkce = truncatedUri.queryParameters[ApiFields.pkce];
final String? code = truncatedUri.queryParameters[ApiFields.code];
final String? resState =
truncatedUri.queryParameters[ApiFields.state];
// Handle Flutter Hue deep link
if (pkce != null && code != null && resState != null) {
String stateSecret;
if (resState.contains("-")) {
stateSecret = resState.substring(0, resState.indexOf("-"));
} else {
stateSecret = resState;
}
TokenRepo.fetchRemoteToken(
clientId: "[clientId]",
clientSecret: "[clientSecret]",
pkce: pkce,
code: code,
stateSecret: stateSecret,
decrypter: (ciphertext) =>
ciphertext.substring(4, ciphertext.length - 4),
);
}
} catch (_) {
// Do nothing
}
},
);
// Initialize Flutter Hue and keep all of the locally stored data up to
// date.
FlutterHueMaintenanceRepo.maintain(
clientId: "[clientId]",
clientSecret: "[clientSecret]",
redirectUri: "flutterhue://auth",
deviceName: "TestDevice",
stateEncrypter: (plaintext) => "abcd${plaintext}1234",
);
}
@override
void dispose() {
deepLinkStream.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Hue"),
actions: isLoading
? [
const Padding(
padding: EdgeInsets.only(right: padding),
child: Row(
children: [
Text("Loading... "),
Icon(Icons.query_builder),
],
),
),
]
: null,
),
body: SafeArea(
child: SingleChildScrollView(
child: Column(
children: [
const SizedBox(height: padding),
sectionHeader("Getting Started"),
// DISCOVER BRIDGES
Column(
children: [
ElevatedButton(
onPressed: discoverBridges,
child: const Text("Discover Bridges"),
),
Visibility(
visible: bridgeIps.isNotEmpty,
child: TextButton(
onPressed: () => showIps(context),
child: Text("Found ${bridgeIps.length} bridge IP"
"${bridgeIps.length == 1 ? "" : "s"}"),
),
),
],
),
const SizedBox(height: padding * 2),
// FIRST CONTACT
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: bridgeIps.isEmpty ? null : () => firstContact(),
child: const Text("First Contact"),
),
const SizedBox(width: 11),
ElevatedButton(
onPressed: onContactCancel,
child: const Text("Cancel"),
),
],
),
const SizedBox(height: padding * 2),
// ESTABLISH REMOTE CONTACT
ElevatedButton(
onPressed: bridge == null ? null : remoteContact,
child: const Text("Establish Remote Contact"),
),
const SizedBox(height: padding * 2),
sectionHeader("Reading Data"),
// FETCH NETWORK
ElevatedButton(
onPressed: bridge == null ? null : fetchNetwork,
child: const Text("Fetch Network"),
),
const SizedBox(height: padding * 2),
// FETCH BRIDGE
ElevatedButton(
onPressed: bridge == null ? null : fetchBridge,
child: const Text("Fetch Bridge"),
),
const SizedBox(height: padding * 2),
// FETCH LIGHT
ElevatedButton(
onPressed: bridge == null ? null : fetchLight,
child: const Text("Fetch Light"),
),
const SizedBox(height: padding * 2),
sectionHeader("Writing Data"),
// IDENTIFY LIGHT
ElevatedButton(
onPressed: light == null ? null : identifyLight,
child: const Text("Identify Light"),
),
const SizedBox(height: padding * 2),
// TOGGLE LIGHT ON/OFF
ElevatedButton(
onPressed: light == null ? null : toggleLight,
child: const Text("Toggle Light on/off"),
),
const SizedBox(height: padding * 2),
// LIGHT COLORS
Padding(
padding: const EdgeInsets.symmetric(horizontal: padding),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
// RED
ElevatedButton(
onPressed: light == null ? null : () => colorLight("red"),
child: const Text("Red"),
),
// GREEN
ElevatedButton(
onPressed:
light == null ? null : () => colorLight("green"),
child: const Text("Green"),
),
// BLUE
ElevatedButton(
onPressed:
light == null ? null : () => colorLight("blue"),
child: const Text("Blue"),
),
// WHITE
ElevatedButton(
onPressed:
light == null ? null : () => colorLight("white"),
child: const Text("White"),
),
],
),
),
const SizedBox(height: padding),
],
),
),
),
);
}
/// The titles and dividers that separate each group of buttons.
Widget sectionHeader(String title) {
return Column(
children: [
Row(
children: [
const SizedBox(width: padding),
Text(
title,
style: const TextStyle(
fontSize: padding,
fontWeight: FontWeight.bold,
),
),
],
),
const Padding(
padding: EdgeInsets.symmetric(horizontal: padding),
child: Divider(thickness: 2.0),
),
],
);
}
/// Show the IP addresses of the bridges that have been found on the network.
void showIps(BuildContext context) {
showDialog<void>(
context: context,
builder: (context) {
return AlertDialog(
title: const Text("Bridge IP"),
content: SingleChildScrollView(
child: ListBody(
children: bridgeIps.map((ip) => Text(ip)).toList(),
),
),
actions: [
TextButton(
child: const Text("Ok"),
onPressed: () {
Navigator.of(context).pop();
},
),
],
);
},
);
}
/// Searches the network for bridges.
///
/// If any are found, their IP addresses are placed in the [bridgeIps] list.
Future<void> discoverBridges() async {
setState(() {
isLoading = true;
});
List<String> bridges = await BridgeDiscoveryRepo.discoverBridges();
setState(() {
bridgeIps.addAll(bridges);
isLoading = false;
});
}
/// For the simplicity of this demo, this method only looks at the first
/// bridge from the [bridgeIps] list.
///
/// It attempts to establish contact with the bridge. This is when the user
/// needs to press the button on their bridge.
Future<void> firstContact() async {
setState(() {
onContactCancel = () => timeoutController.cancelDiscovery = true;
isLoading = true;
});
bridge = await BridgeDiscoveryRepo.firstContact(
bridgeIpAddr: bridgeIps.first,
controller: timeoutController,
);
setState(() {
onContactCancel = null;
isLoading = false;
});
}
/// Establishes remote contact with the bridge.
Future<void> remoteContact() async {
setState(() {
isLoading = true;
});
await BridgeDiscoveryRepo.remoteAuthRequest(
clientId: "[clientId]",
redirectUri: "flutterhue://auth",
deviceName: "TestDevice",
encrypter: (plaintext) => "abcd${plaintext}1234",
);
setState(() {
isLoading = false;
});
}
/// Fetches all of the resources that are attached to [bridge].
Future<void> fetchNetwork() async {
setState(() {
isLoading = true;
});
hueNetwork = HueNetwork(bridges: [bridge!]);
await hueNetwork?.fetchAll();
try {
light = hueNetwork!.lights.first;
} catch (_) {
// Do nothing
}
setState(() {
isLoading = false;
});
}
/// This does nothing for the demo other than to show the code that is used to
/// fetch a bridge object from JSON.
Future<void> fetchBridge() async {
setState(() {
isLoading = true;
});
final List<Map<String, dynamic>>? res =
await bridge!.getResource(ResourceType.bridge);
try {
// ignore: unused_local_variable
Bridge myBridge = Bridge.fromJson(res?.first ?? {});
// Shows a way to display the info in these objects.
// log("Bridge Json - ${JsonTool.writeJson(res?.first ?? {})}");
// log("Bridge Object - ${JsonTool.writeJson(myBridge.toJson(optimizeFor: OptimizeFor.dontOptimize))}");
} catch (_) {
// res list was empty
}
setState(() {
isLoading = false;
});
}
/// This does nothing for the demo other than to show the code that is used to
/// fetch a light object from JSON.
Future<void> fetchLight() async {
setState(() {
isLoading = true;
});
final Map<String, dynamic>? res =
(await bridge!.getResource(ResourceType.light))?.first;
// ignore: unused_local_variable
Light light = Light.fromJson(res ?? {});
setState(() {
isLoading = false;
});
}
/// Causes the light to "breath" to let the user know which light they are
/// working with.
Future<void> identifyLight() async {
setState(() {
isLoading = true;
});
Device lightDevice;
try {
lightDevice = hueNetwork!.devices
// ignore: deprecated_member_use
.firstWhere((device) => device.metadata.name == light!.metadata.name);
} catch (_) {
return;
}
lightDevice.identifyAction = "identify";
await bridge!.put(lightDevice);
setState(() {
isLoading = false;
});
}
/// Toggles [light] on and off.
Future<void> toggleLight() async {
setState(() {
isLoading = true;
});
bool isOn = light!.isOn;
light!.on.isOn = !isOn;
await bridge!.put(light!);
setState(() {
isLoading = false;
});
}
/// Changes the color of [light].
Future<void> colorLight(String color) async {
setState(() {
isLoading = true;
});
double x;
double y;
if (color == "red") {
x = 0.6718;
y = 0.3184;
} else if (color == "green") {
x = 0.2487;
y = 0.6923;
} else if (color == "blue") {
x = 0.1121;
y = 0.1139;
} else {
x = 0.3127;
y = 0.3127;
}
light = light!
.copyWith(color: light!.color.copyWith(xy: LightColorXy(x: x, y: y)));
await bridge!.put(light!);
setState(() {
isLoading = false;
});
}
}