2025-02-22 20:45:01 +03:00
|
|
|
import 'dart:async';
|
|
|
|
|
|
2025-02-22 19:50:05 +03:00
|
|
|
import 'package:flutter/material.dart';
|
|
|
|
|
import 'sensor_data.dart';
|
|
|
|
|
import 'sensor_service.dart';
|
|
|
|
|
|
|
|
|
|
class SensorProvider with ChangeNotifier {
|
|
|
|
|
final SensorService _service = SensorService();
|
|
|
|
|
SensorData? _sensorData;
|
|
|
|
|
|
2025-02-22 20:45:01 +03:00
|
|
|
Exception? _exception;
|
2025-02-22 19:50:05 +03:00
|
|
|
|
|
|
|
|
SensorData? get sensorData => _sensorData;
|
|
|
|
|
|
2025-02-22 20:45:01 +03:00
|
|
|
Exception? get exception => _exception;
|
|
|
|
|
|
|
|
|
|
Timer? _timer;
|
2025-02-22 19:50:05 +03:00
|
|
|
|
|
|
|
|
Future<void> fetchData() async {
|
|
|
|
|
try {
|
|
|
|
|
_sensorData = await _service.fetchSensorData();
|
2025-02-22 20:45:01 +03:00
|
|
|
} on Exception catch (e) {
|
|
|
|
|
_exception = e;
|
|
|
|
|
_sensorData = null;
|
2025-02-22 19:50:05 +03:00
|
|
|
}
|
|
|
|
|
notifyListeners();
|
|
|
|
|
}
|
2025-02-22 20:45:01 +03:00
|
|
|
|
|
|
|
|
void startAutoFetch(Duration interval) {
|
|
|
|
|
_timer = Timer.periodic(interval, (timer) async {
|
|
|
|
|
await fetchData();
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Stop auto-fetching
|
|
|
|
|
void stopAutoFetch() {
|
|
|
|
|
_timer?.cancel();
|
|
|
|
|
_timer = null;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Dispose the timer when the provider is disposed
|
|
|
|
|
@override
|
|
|
|
|
void dispose() {
|
|
|
|
|
_timer?.cancel();
|
|
|
|
|
super.dispose();
|
|
|
|
|
}
|
|
|
|
|
}
|