smartfarming-mobile/agrilink_vocpro/lib/features/control/provider/control_provider.dart

113 lines
2.9 KiB
Dart

import 'package:agrilink_vocpro/core/state/result_state.dart';
import 'package:agrilink_vocpro/domain/service/app_service.dart';
import 'package:flutter/foundation.dart';
class ControlProvider extends ChangeNotifier {
final AppService _appService = AppService();
bool _control_1 = false;
bool get control_1 => _control_1;
bool _control_2 = false;
bool get control_2 => _control_2;
ControlProvider() {
getRelayStatus();
}
// ResultState mqttState = ResultState.initial;
// ResultState subscribeState = ResultState.initial;
ResultState relayState = ResultState.initial;
// Future<void> connectMqtt() async {
// mqttState = ResultState.loading;
// subscribeState = ResultState.loading;
// notifyListeners();
// try {
// final result = await _mqttService.setupMqtt();
// if (result == ResultState.hasData) {
// mqttState = result;
// final result2 = await _mqttService.subscribeToRelayStatus();
// // if (result2 == true) {
// // subscribeState = ResultState.hasData;
// // _control_1 = true;
// // } else {
// // subscribeState = ResultState.hasData;
// // _control_1 = false;
// // }
// } else {
// mqttState = ResultState.error;
// }
// } catch (e) {
// mqttState = ResultState.error;
// print(e);
// }
// notifyListeners();
// }
Future<void> getRelayStatus() async {
relayState = ResultState.loading;
notifyListeners();
try {
if (kDebugMode) {
print('try to get relay status...');
}
final result = await _appService.getRelayStatus();
if (result.success == true) {
for (var element in result.data!) {
if (element.number == 1) {
switchControl1(element.currentStatus ?? false);
}
if (element.number == 2) {
switchControl2(element.currentStatus ?? false);
}
}
relayState = ResultState.hasData;
notifyListeners();
} else {
relayState = ResultState.error;
notifyListeners();
}
} catch (e) {
relayState = ResultState.error;
notifyListeners();
if (kDebugMode) {
print(e);
}
rethrow;
}
}
void switchControl1(bool value) {
_control_1 = value;
notifyListeners();
}
void switchControl2(bool value) {
_control_2 = value;
notifyListeners();
}
// Future<ResultState> publishMessage(String topic, String message) async {
// try {
// final result = await _mqttService.publishMessage(topic, message);
// return result;
// } catch (e) {
// print(e);
// rethrow;
// }
// }
// Future<void> subscribeToTopic(String topic) async {
// try {
// await _mqttService.subscribeToTopic(topic);
// } catch (e) {
// print(e);
// rethrow;
// }
// }
}