import 'dart:async'; import 'package:flutter/foundation.dart'; import '../models/wifi_network.dart'; import '../models/wifi_status.dart'; import '../services/http_api_service.dart'; import '../services/web_socket_service.dart'; class WifiProvider extends ChangeNotifier { WifiProvider({ required HttpApiService httpApiService, required WebSocketService webSocketService, }) : _httpApiService = httpApiService, _webSocketService = webSocketService { _wifiSubscription = _webSocketService.onWifiUpdate.listen((payload) { _status = WifiStatus.fromJson(payload); notifyListeners(); }); } final HttpApiService _httpApiService; final WebSocketService _webSocketService; late final StreamSubscription> _wifiSubscription; WifiStatus _status = WifiStatus.disconnected(); List _networks = const []; bool _isLoading = false; String? _errorMessage; bool _hotspotEnabled = false; WifiStatus get status => _status; List get networks => _networks; bool get isLoading => _isLoading; String? get errorMessage => _errorMessage; bool get hotspotEnabled => _hotspotEnabled; Future bootstrap() async { _setLoading(true); try { final results = await Future.wait([ _httpApiService.getWifiStatus(), _httpApiService.scanWifi(), ]); _status = results[0] as WifiStatus; _networks = results[1] as List; _errorMessage = null; } catch (error) { _errorMessage = error.toString(); } finally { _setLoading(false); } } Future refreshStatus() async { try { _status = await _httpApiService.getWifiStatus(); notifyListeners(); } catch (error) { _errorMessage = error.toString(); notifyListeners(); } } Future scanNetworks() async { _setLoading(true); try { _networks = await _httpApiService.scanWifi(); _errorMessage = null; } catch (error) { _errorMessage = error.toString(); } finally { _setLoading(false); } } Future connect({required String ssid, required String password}) async { _setLoading(true); try { await _httpApiService.connectWifi(ssid, password); await refreshStatus(); _hotspotEnabled = false; _errorMessage = null; } catch (error) { _errorMessage = error.toString(); notifyListeners(); } finally { _setLoading(false); } } Future startHotspot({String? ssid, String? password}) async { _setLoading(true); try { await _httpApiService.startAP(ssid, password); _hotspotEnabled = true; _errorMessage = null; notifyListeners(); } catch (error) { _errorMessage = error.toString(); notifyListeners(); } finally { _setLoading(false); } } Future stopHotspot() async { _setLoading(true); try { await _httpApiService.stopAP(); _hotspotEnabled = false; _errorMessage = null; notifyListeners(); } catch (error) { _errorMessage = error.toString(); notifyListeners(); } finally { _setLoading(false); } } void _setLoading(bool value) { _isLoading = value; notifyListeners(); } @override void dispose() { unawaited(_wifiSubscription.cancel()); super.dispose(); } }