import 'package:agrilink_vocpro/core/state/result_state.dart'; import 'package:agrilink_vocpro/domain/service/mqtt_service.dart'; import 'package:flutter/material.dart'; class ControlProvider extends ChangeNotifier { final MQTTService _mqttService = MQTTService(); bool _control_1 = false; bool get control_1 => _control_1; ControlProvider() { connectMqtt(); } ResultState mqttState = ResultState.initial; ResultState subscribeState = ResultState.initial; Future 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.subscribeToTopic('relay1'); 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 disconnectMqtt() async { try { await _mqttService.disconnectMqtt(); } catch (e) { print(e); rethrow; } notifyListeners(); } @override void dispose() { disconnectMqtt(); super.dispose(); } void switchControl1() { _control_1 = !_control_1; notifyListeners(); } Future publishMessage(String topic, String message) async { try { final result = await _mqttService.publishMessage(topic, message); return result; } catch (e) { print(e); rethrow; } } Future subscribeToTopic(String topic) async { try { await _mqttService.subscribeToTopic(topic); } catch (e) { print(e); rethrow; } } }