From f0c3c81141abaad261ee11ed50560fb49143e7f3 Mon Sep 17 00:00:00 2001 From: Jan Romann Date: Mon, 20 Jun 2022 03:52:26 +0200 Subject: [PATCH] feat: update CoAP discovery example --- example/coap_discovery.dart | 53 +++++++++++++++++++++++++------------ 1 file changed, 36 insertions(+), 17 deletions(-) diff --git a/example/coap_discovery.dart b/example/coap_discovery.dart index e5810c42..8c17c537 100644 --- a/example/coap_discovery.dart +++ b/example/coap_discovery.dart @@ -16,27 +16,46 @@ extension PrintExtension on InteractionOutput { } } +Future handleThingDescription( + WoT wot, + ThingDescription thingDescription, +) async { + final consumedThing = await wot.consume(thingDescription); + await consumedThing.writeProperty(propertyName, 'Hello World!'); + var output = await consumedThing.readProperty(propertyName); + await output.printValue(); + await consumedThing.writeProperty(propertyName, 'Bye World!'); + output = await consumedThing.readProperty(propertyName); + await output.printValue(); +} + Future main(List args) async { final servient = Servient()..addClientFactory(CoapClientFactory()); final wot = await servient.start(); - - await for (final thingDescription in wot.discover( - ThingFilter( - url: Uri.parse('coap://plugfest.thingweb.io:5683/testthing'), - ), - )) { - final consumedThing = await wot.consume(thingDescription); - - try { - await consumedThing.writeProperty(propertyName, 'Hello World!'); - var output = await consumedThing.readProperty(propertyName); - await output.printValue(); - await consumedThing.writeProperty(propertyName, 'Bye World!'); - output = await consumedThing.readProperty(propertyName); - await output.printValue(); - } on Exception catch (e) { - print(e); + final thingFilter = ThingFilter( + url: Uri.parse('coap://plugfest.thingweb.io:5683/testthing'), + ); + + // Example using for-await-loop + try { + await for (final thingDescription in wot.discover(thingFilter)) { + await handleThingDescription(wot, thingDescription); } + print('Discovery with "await for" has finished.'); + } on Exception catch (error) { + print(error); } + + // Example using the .listen() method, allowing for error handling + // + // Notice how the "onDone" callback is called before the result is passed + // to the handleThingDescription function. + wot.discover(thingFilter).listen( + (thingDescription) async { + await handleThingDescription(wot, thingDescription); + }, + onError: (error) => print('Encountered an error: $error'), + onDone: () => print('Discovery with "listen" has finished.'), + ); }