Skip to content

Commit

Permalink
mqtt-client: dart example added
Browse files Browse the repository at this point in the history
  • Loading branch information
Jan Bartnitsky committed Jun 4, 2024
1 parent 2ab1171 commit a40e1fc
Show file tree
Hide file tree
Showing 5 changed files with 131 additions and 0 deletions.
31 changes: 31 additions & 0 deletions mqtt-client/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,34 @@ Example source code is located at [./browser/](./browser/)
You may run the example [in your browser from GitHub Pages](https://flespi-software.github.io/examples/mqtt-client/browser/example.html) or open the example.html file from your local file system.

This example uses the [browser-version of the mqtt.js](https://github.com/mqttjs/MQTT.js#browser) library.

## dart

Example source code is located at [./dart/](./dart/)

### Setup and Run

1. **Navigate to the Dart project directory**:
```sh
cd dart
```

2. **Ensure you have Dart SDK installed, then initialize the project**:
```sh
dart pub get
```

3. **Set the Flespi token environment variable**:
On Linux/macOS:
```sh
export FlespiToken=your_flespi_token
```
On Windows:
```cmd
set FlespiToken=your_flespi_token
```

4. **Run the Dart script**:
```sh
dart run lib/example.dart
```
4 changes: 4 additions & 0 deletions mqtt-client/dart/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.dart_tool/
.packages
.pub/
build/
3 changes: 3 additions & 0 deletions mqtt-client/dart/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# lua MQTT Client example

Please [refer here](../#dart) for complete README
79 changes: 79 additions & 0 deletions mqtt-client/dart/lib/example.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import 'package:mqtt5_client/mqtt5_client.dart';
import 'package:mqtt5_client/mqtt5_server_client.dart';
import 'dart:async';
import 'dart:io';
import 'package:typed_data/typed_data.dart';

void main() async {
// Retrieve Flespi token from environment variable
final flespiToken = Platform.environment['FlespiToken'];
if (flespiToken == null || flespiToken.isEmpty) {
print('Flespi token is not set in the environment variables.');
return;
}

// Create an MQTT client instance
print('mqtt client created, connecting...');
final client = MqttServerClient.withPort('wss://mqtt.flespi.io', '', 443);

// Configure the client for WebSocket
client.useWebSocket = true;
client.websocketProtocolString = ['mqtt'];

// Set the client identifier
client.clientIdentifier = 'dart_mqtt_client';

// Set the username with the Flespi token (no password in this example)
final connMessage = MqttConnectMessage()
.withClientIdentifier('dart_mqtt_client')
.authenticateAs(flespiToken, '');

client.connectionMessage = connMessage;

// Connect to the MQTT broker
try {
await client.connect();
} on Exception catch (e) {
print('Connection failed: $e');
client.disconnect();
return;
}

// Check if we are connected
if (client.connectionStatus?.state == MqttConnectionState.connected) {
print('connected, subscribing to "test" topic...');
} else {
print('Connection failed: ${client.connectionStatus}');
return;
}

// Subscribe to the "test" topic
const topic = 'test';
client.subscribe(topic, MqttQos.atMostOnce);
print('subscribed to "test" topic, publishing message...');

// Handle incoming messages
client.updates?.listen((List<MqttReceivedMessage<MqttMessage>> c) {
final MqttPublishMessage message = c[0].payload as MqttPublishMessage;
final Uint8Buffer? payloadBuffer = message.payload.message;

if (payloadBuffer != null) {
final payload = String.fromCharCodes(payloadBuffer);
print('received message in topic "test": "$payload"');
} else {
print('Received null payload from topic: "${c[0].topic}"');
}
});

// Publish a message to the "test" topic
final builder = MqttPayloadBuilder();
builder.addString('hello from flespi mqtt client example script!');
client.publishMessage(topic, MqttQos.atMostOnce, builder.payload!);

// Keep the connection alive
await Future.delayed(Duration(seconds: 5)); // Give some time to receive the message

print('disconnecting...');
client.disconnect();
print('disconnected');
}
14 changes: 14 additions & 0 deletions mqtt-client/dart/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
name: example
description: A sample Dart application demonstrating MQTT client functionality.
version: 1.0.0

environment:
sdk: '>=2.12.0 <3.0.0'

dependencies:
mqtt_client: ^9.6.1
mqtt5_client: ^4.2.5

dev_dependencies:
lints: ^3.0.0
test: ^1.24.0

0 comments on commit a40e1fc

Please sign in to comment.