forked from fossasia/pslab-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathads1115_provider.dart
More file actions
249 lines (210 loc) · 6.08 KB
/
Copy pathads1115_provider.dart
File metadata and controls
249 lines (210 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:pslab/communication/peripherals/i2c.dart';
import 'package:pslab/communication/science_lab.dart';
import '../communication/sensors/ads1115.dart';
import '../l10n/app_localizations.dart';
import '../models/chart_data_points.dart';
import 'package:pslab/others/logger_service.dart';
import 'locator.dart';
class ADS1115Provider extends ChangeNotifier {
AppLocalizations get appLocalizations => getIt.get<AppLocalizations>();
ADS1115? _ads1115;
Timer? _dataTimer;
bool _isDisposed = false;
bool _isFetching = false;
double _voltage = 0.0;
String _currentGain = "GAIN_ONE";
String _currentChannel = "UNI_0";
int _currentRate = 128;
final List<ChartDataPoint> _voltageData = [];
bool _isRunning = false;
bool _isLooping = false;
int _timegapMs = 1000;
int _numberOfReadings = 100;
int _collectedReadings = 0;
double _currentTime = 0.0;
static const int maxDataPoints = 1000;
double get voltage => _voltage;
String get currentGain => _currentGain;
String get currentChannel => _currentChannel;
int get currentRate => _currentRate;
List<ChartDataPoint> get voltageData => List.unmodifiable(_voltageData);
bool get isRunning => _isRunning;
bool get isLooping => _isLooping;
int get timegapMs => _timegapMs;
int get numberOfReadings => _numberOfReadings;
int get collectedReadings => _collectedReadings;
final List<String> availableGains = [
"GAIN_TWOTHIRDS",
"GAIN_ONE",
"GAIN_TWO",
"GAIN_FOUR",
"GAIN_EIGHT",
"GAIN_SIXTEEN"
];
final List<String> availableChannels = [
"UNI_0",
"UNI_1",
"UNI_2",
"UNI_3",
"DIFF_01",
"DIFF_23"
];
final List<int> availableRates = [8, 16, 32, 64, 128, 250, 475, 860];
ADS1115Provider();
Future<void> initializeSensors({
required Function(String) onError,
required I2C? i2c,
required ScienceLab? scienceLab,
}) async {
try {
if (i2c == null || scienceLab == null) {
onError(appLocalizations.pslabNotConnected);
logger.w('I2C or ScienceLab not available');
return;
}
if (!scienceLab.isConnected()) {
onError(appLocalizations.pslabNotConnected);
logger.w("Sciencelab not connected");
return;
}
_ads1115 = await ADS1115.create(i2c, scienceLab);
_updateCurrentSettings();
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error initializing ADS1115: $e');
}
}
void _updateCurrentSettings() {
if (_ads1115 != null) {
_currentGain = _ads1115!.currentGain;
_currentChannel = _ads1115!.currentChannel;
_currentRate = _ads1115!.currentRate;
}
}
void setGain(String gain) {
if (_ads1115 != null) {
_ads1115!.setGain(gain);
_currentGain = gain;
if (!_isDisposed) notifyListeners();
}
}
void setChannel(String channel) {
if (_ads1115 != null) {
_ads1115!.setChannel(channel);
_currentChannel = channel;
if (!_isDisposed) notifyListeners();
}
}
void setRate(int rate) {
if (_ads1115 != null) {
_ads1115!.setDataRate(rate);
_currentRate = rate;
if (!_isDisposed) notifyListeners();
}
}
void toggleDataCollection() {
if (_isRunning) {
_stopDataCollection();
} else {
_startDataCollection();
}
}
void _startDataCollection() {
if (_ads1115 == null) return;
_isRunning = true;
_collectedReadings = 0;
_isFetching = false;
_dataTimer =
Timer.periodic(Duration(milliseconds: _timegapMs), (timer) async {
if (_isFetching || _isDisposed) return;
_isFetching = true;
try {
await _fetchSensorData();
_collectedReadings++;
if (!_isLooping && _collectedReadings >= _numberOfReadings) {
_stopDataCollection();
}
if (_isLooping && _voltageData.length >= maxDataPoints) {
_removeOldestDataPoints();
}
} catch (e) {
String errorMsg = e.toString();
if (errorMsg.contains("Expected")) {
logger.w('ADS1115 dropped a frame. Skipping gracefully...');
} else {
logger.e('Error fetching sensor data: $e');
}
} finally {
_isFetching = false;
}
});
if (!_isDisposed) notifyListeners();
}
void _stopDataCollection() {
_isRunning = false;
_dataTimer?.cancel();
_dataTimer = null;
if (!_isDisposed) notifyListeners();
}
Future<void> _fetchSensorData() async {
if (_ads1115 == null || _isDisposed) return;
try {
final rawData = await _ads1115!.getRawData();
_voltage = rawData['voltage'] ?? 0.0;
_currentTime += _timegapMs / 1000.0;
_addDataPoint(_voltageData, _voltage);
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error in _fetchSensorData: $e');
rethrow;
}
}
void _addDataPoint(List<ChartDataPoint> dataList, double value) {
dataList.add(ChartDataPoint(_currentTime, value));
if (dataList.length > 50) {
dataList.removeAt(0);
}
}
void _removeOldestDataPoints() {
const keepPoints = 800;
if (_voltageData.length > keepPoints) {
final removeCount = _voltageData.length - keepPoints;
_voltageData.removeRange(0, removeCount);
}
}
void toggleLooping() {
_isLooping = !_isLooping;
if (!_isDisposed) notifyListeners();
}
void setTimegap(int timegapMs) {
if (_timegapMs == timegapMs) return;
_timegapMs = timegapMs;
if (_isRunning) {
_stopDataCollection();
_startDataCollection();
}
if (!_isDisposed) notifyListeners();
}
void setNumberOfReadings(int numberOfReadings) {
_numberOfReadings = numberOfReadings;
if (!_isDisposed) notifyListeners();
}
void clearData() {
_voltageData.clear();
_voltage = 0.0;
_currentTime = 0.0;
_collectedReadings = 0;
if (!_isDisposed) notifyListeners();
}
bool get isCollectionComplete {
return !_isLooping && _collectedReadings >= _numberOfReadings;
}
@override
void dispose() {
_isDisposed = true;
_stopDataCollection();
super.dispose();
}
}