Skip to content

Commit

Permalink
feat: update CoAP discovery example
Browse files Browse the repository at this point in the history
  • Loading branch information
JKRhb committed Jul 10, 2022
1 parent fa1656f commit f0c3c81
Showing 1 changed file with 36 additions and 17 deletions.
53 changes: 36 additions & 17 deletions example/coap_discovery.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,46 @@ extension PrintExtension on InteractionOutput {
}
}

Future<void> 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<void> main(List<String> 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.'),
);
}

0 comments on commit f0c3c81

Please sign in to comment.