72 lines
2.0 KiB
Dart
72 lines
2.0 KiB
Dart
import 'package:agrilink_vocpro/core/state/result_state.dart';
|
|
import 'package:mqtt_client/mqtt_client.dart';
|
|
import 'package:mqtt_client/mqtt_server_client.dart';
|
|
|
|
class MQTTService {
|
|
MqttServerClient? client;
|
|
|
|
Future<ResultState> setupMqtt() async {
|
|
client = MqttServerClient('armadillo.rmq.cloudamqp.com', '');
|
|
client!.port = 1883;
|
|
|
|
client!.connectionMessage = MqttConnectMessage()
|
|
.authenticateAs('obyskxhx:obyskxhx', 'Fe_3_tBuwmc8vMMqT2hYiboTsBlBmPz1')
|
|
.withClientIdentifier('mobile_client_controller')
|
|
.startClean() // reset session
|
|
.withWillQos(MqttQos.atLeastOnce);
|
|
|
|
try {
|
|
print('MQTT: Connecting....');
|
|
await client!.connect();
|
|
print('MQTT: Connected');
|
|
return ResultState.hasData;
|
|
} catch (e) {
|
|
print('MQTT: Error: $e');
|
|
return ResultState.error;
|
|
}
|
|
}
|
|
|
|
Future<ResultState> publishMessage(String topic, String message) async {
|
|
final bool isConnected = await isMqttConnected();
|
|
if (isConnected) {
|
|
final builder = MqttClientPayloadBuilder();
|
|
|
|
try {
|
|
builder.addString(message);
|
|
client!.publishMessage(topic, MqttQos.atLeastOnce, builder.payload!);
|
|
return ResultState.hasData;
|
|
} catch (e) {
|
|
print(e);
|
|
return ResultState.error;
|
|
}
|
|
} else {
|
|
return ResultState.error;
|
|
}
|
|
}
|
|
|
|
Future<ResultState> disconnectMqtt() async {
|
|
final bool isConnected = await isMqttConnected();
|
|
if (isConnected) {
|
|
print('Memutus koneksi dari broker...');
|
|
|
|
client!.disconnect();
|
|
|
|
await Future.delayed(const Duration(seconds: 1));
|
|
print('Koneksi telah terputus.');
|
|
return ResultState.hasData;
|
|
} else {
|
|
print('Tidak ada koneksi yang sedang aktif.');
|
|
return ResultState.error;
|
|
}
|
|
}
|
|
|
|
Future<bool> isMqttConnected() async {
|
|
if (client != null &&
|
|
client!.connectionStatus!.state == MqttConnectionState.connected) {
|
|
return true; //connected
|
|
} else {
|
|
return false; //not connected
|
|
}
|
|
}
|
|
}
|