From 408f6a2fc5a0bcefa13d196ce34704f1144d7299 Mon Sep 17 00:00:00 2001 From: Jan Romann Date: Wed, 20 Dec 2023 09:20:31 +0100 Subject: [PATCH] docs: create seperate MQTT example --- example/mqtt_example.dart | 105 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 example/mqtt_example.dart diff --git a/example/mqtt_example.dart b/example/mqtt_example.dart new file mode 100644 index 00000000..15358070 --- /dev/null +++ b/example/mqtt_example.dart @@ -0,0 +1,105 @@ +// Copyright 2023 Contributors to the Eclipse Foundation. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. +// +// SPDX-License-Identifier: BSD-3-Clause + +// ignore_for_file: avoid_print + +import 'package:dart_wot/dart_wot.dart'; + +const thingDescriptionJson = ''' + { + "@context": "https://www.w3.org/2022/wot/td/v1.1", + "title": "Test Thing", + "id": "urn:test", + "base": "coap://coap.me", + "security": ["auto_sc"], + "securityDefinitions": { + "auto_sc": { + "scheme": "auto" + } + }, + "properties": { + "status": { + "observable": true, + "forms": [ + { + "href": "mqtt://test.mosquitto.org:1884", + "mqv:filter": "test", + "op": ["readproperty", "observeproperty"], + "contentType": "text/plain" + } + ] + } + }, + "actions": { + "toggle": { + "input": { + "type": "string" + }, + "forms": [ + { + "href": "mqtt://test.mosquitto.org:1884", + "mqv:topic": "test", + "mqv:retain": true + } + ] + } + } + } + '''; + +final Map basicCredentials = { + 'urn:test': BasicCredentials('rw', 'readwrite'), +}; + +Future basicCredentialsCallback( + Uri uri, + Form? form, [ + BasicCredentials? invalidCredentials, +]) async { + final id = form?.thingDescription.identifier; + + return basicCredentials[id]; +} + +Future main(List args) async { + final servient = Servient( + clientFactories: [ + MqttClientFactory(basicCredentialsCallback: basicCredentialsCallback), + ], + ); + + final wot = await servient.start(); + + final thingDescription = ThingDescription(thingDescriptionJson); + final consumedThing = await wot.consume(thingDescription); + await consumedThing.readAndPrintProperty('status'); + + final subscription = await consumedThing.observeProperty( + 'status', + (data) async { + final value = await data.value(); + print(value); + }, + ); + + await consumedThing.invokeAction('toggle', 'Hello World!'); + await consumedThing.invokeAction('toggle', 'Hello World!'); + await consumedThing.invokeAction('toggle', 'Hello World!'); + await consumedThing.invokeAction('toggle', 'Hello World!'); + await subscription.stop(); + + await consumedThing.invokeAction('toggle', 'Bye World!'); + await consumedThing.readAndPrintProperty('status'); + print('Done!'); +} + +extension ReadAndPrintExtension on ConsumedThing { + Future readAndPrintProperty(String propertyName) async { + final output = await readProperty(propertyName); + final value = await output.value(); + print(value); + } +}