mirror of
https://bitbucket.org/FransoletThomas/tablet-app.git
synced 2025-12-06 00:21:19 +00:00
74 lines
2.6 KiB
Dart
74 lines
2.6 KiB
Dart
import 'package:mqtt_client/mqtt_client.dart';
|
|
import 'package:mqtt_client/mqtt_server_client.dart';
|
|
import 'package:unique_identifier/unique_identifier.dart';
|
|
|
|
class MQTTHelper {
|
|
MQTTHelper._privateConstructor();
|
|
static final MQTTHelper instance = MQTTHelper._privateConstructor();
|
|
|
|
void onConnected(dynamic tabletAppContext) {
|
|
print('Connected !!!!!!!!!!!! ----------------------------------');
|
|
|
|
tabletAppContext.clientMQTT.updates.listen((List<MqttReceivedMessage<MqttMessage>> c) {
|
|
final MqttPublishMessage message = c[0].payload;
|
|
final payload = MqttPublishPayload.bytesToStringAsString(message.payload.message);
|
|
print('Received message:$payload from topic: ${c[0].topic}');
|
|
});
|
|
}
|
|
|
|
// unconnected
|
|
void onDisconnected() {
|
|
print('Disconnected');
|
|
}
|
|
|
|
// subscribe to topic succeeded
|
|
void onSubscribed(String topic) {
|
|
print('Subscribed topic: $topic');
|
|
}
|
|
|
|
// subscribe to topic failed
|
|
void onSubscribeFail(String topic) {
|
|
print('Failed to subscribe $topic');
|
|
}
|
|
|
|
// unsubscribe succeeded
|
|
void onUnsubscribed(String topic) {
|
|
print('Unsubscribed topic: $topic');
|
|
}
|
|
|
|
Future<MqttServerClient> connect(dynamic tabletAppContext) async {
|
|
var identifier = await UniqueIdentifier.serial;
|
|
tabletAppContext.clientMQTT = MqttServerClient.withPort(tabletAppContext.host.replaceAll('http://', ''), 'tablet_app_'+identifier, 1883);
|
|
|
|
tabletAppContext.clientMQTT.logging(on: false);
|
|
tabletAppContext.clientMQTT.keepAlivePeriod = 20;
|
|
tabletAppContext.clientMQTT.onDisconnected = onDisconnected;
|
|
tabletAppContext.clientMQTT.onConnected = () => onConnected(tabletAppContext);
|
|
tabletAppContext.clientMQTT.onSubscribed = onSubscribed;
|
|
|
|
final connMessage = MqttConnectMessage().authenticateAs('admin', 'mdlf2021!') // TODO ONLINE
|
|
.keepAliveFor(60)
|
|
.withWillTopic('willtopic')
|
|
.withWillMessage('Will message')
|
|
.withClientIdentifier('tablet_app_'+identifier)
|
|
.startClean()
|
|
.withWillQos(MqttQos.atLeastOnce);
|
|
|
|
tabletAppContext.clientMQTT.connectionMessage = connMessage;
|
|
tabletAppContext.clientMQTT.autoReconnect = true;
|
|
try {
|
|
await tabletAppContext.clientMQTT.connect();
|
|
tabletAppContext.clientMQTT.subscribe("#", MqttQos.atLeastOnce);
|
|
|
|
const pubTopic = 'player/status';
|
|
final builder = MqttClientPayloadBuilder();
|
|
builder.addString('tablet_app_'+identifier);
|
|
tabletAppContext.clientMQTT.publishMessage(pubTopic, MqttQos.atLeastOnce, builder.payload);
|
|
} catch (e) {
|
|
print('Exception: $e');
|
|
tabletAppContext.clientMQTT.disconnect();
|
|
}
|
|
|
|
return tabletAppContext.clientMQTT;
|
|
}
|
|
} |