Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions lib/communication/packet_handler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,10 +79,8 @@ class PacketHandler {
return "";
}

Future<Uint8List> queryScpiBinary(String command) async {
Uint8List data =
await rust_api.queryScpiBinaryRust(command: command, timeoutMs: 1000);
return data;
Future<void> sendScpiRaw(Uint8List command) async {
rust_api.sendScpiRawRust(command: command);
}

void sendByte(int val) {
Expand Down Expand Up @@ -236,4 +234,21 @@ class PacketHandler {
_mCommunicationHandler.write(data, _timeout);
}
}

Future<Uint8List> queryScpiBinary(String command) async {
Uint8List data =
await rust_api.queryScpiBinaryRust(command: command, timeoutMs: 1000);
return data;
}

void sendScpiRawCmd(Uint8List command) {
rust_api.sendScpiRawRust(command: command);
}

Future<Uint8List> queryScpiBinaryRawCmd(Uint8List command,
{int timeoutMs = 1000}) async {
final result = await rust_api.queryScpiBinaryRawRust(
command: command, timeoutMs: timeoutMs);
return Uint8List.fromList(result);
}
}
43 changes: 34 additions & 9 deletions lib/communication/peripherals/i2c.dart
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,22 @@ class I2C {
buffer = List.filled(10000, 0);
commandsProto = CommandsProto();
}

String _buildScpiBlock(String prefix, List<int> data) {
Uint8List _buildScpiBlockBytes(String prefix, List<int> data,
{String suffix = ""}) {
String dataLen = data.length.toString();
String numDigits = dataLen.length.toString();
String header = "$prefix #$numDigits$dataLen";
return header + String.fromCharCodes(data);

List<int> cmdBytes = header.codeUnits.toList();
cmdBytes.addAll(data);

if (suffix.isNotEmpty) {
cmdBytes.addAll(suffix.codeUnits);
}

Uint8List finalBytes = Uint8List.fromList(cmdBytes);
logger.i("SCPI COMMAND BUILT -> Raw array: $finalBytes");
return finalBytes;
}

Future<void> init() async {
Expand Down Expand Up @@ -159,11 +169,25 @@ class I2C {
int deviceAddress, int registerAddress, int bytesToRead) async {
if (PacketHandler.boardType == BoardType.scpi) {
await packetHandler.sendScpi("BUS:I2C:CONF:ADDR $deviceAddress");
String blockCmd = "${_buildScpiBlock("BUS:I2C:TRAN?", [
registerAddress
])}, $bytesToRead";
Comment thread
rahul31124 marked this conversation as resolved.
await Future.delayed(const Duration(milliseconds: 2));

String prefix = "BUS:I2C:TRAN? $bytesToRead,";
Uint8List blockCmd = _buildScpiBlockBytes(prefix, [registerAddress]);

int attempts = 0;
Uint8List rxData = Uint8List(0);

while (attempts < 5) {
rxData = await packetHandler.queryScpiBinaryRawCmd(blockCmd);
Comment thread
rahul31124 marked this conversation as resolved.

if (rxData.length == bytesToRead) {
return rxData.toList();
}

attempts++;
await Future.delayed(const Duration(milliseconds: 10));
Comment thread
rahul31124 marked this conversation as resolved.
}

Uint8List rxData = await packetHandler.queryScpiBinary(blockCmd);
return rxData.toList();
}

Expand Down Expand Up @@ -202,8 +226,9 @@ class I2C {
Future<void> writeBulk(int deviceAddress, List<int> data) async {
if (PacketHandler.boardType == BoardType.scpi) {
await packetHandler.sendScpi("BUS:I2C:CONF:ADDR $deviceAddress");
String blockCmd = _buildScpiBlock("BUS:I2C:WRIT", data);
await packetHandler.sendScpi(blockCmd);
await Future.delayed(const Duration(milliseconds: 5));
Uint8List blockCmd = _buildScpiBlockBytes("BUS:I2C:WRIT", data);
packetHandler.sendScpiRawCmd(blockCmd);
return;
}

Expand Down
48 changes: 32 additions & 16 deletions lib/providers/ads1115_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ class ADS1115Provider extends ChangeNotifier {

ADS1115? _ads1115;
Timer? _dataTimer;

bool _isDisposed = false;
bool _isFetching = false;

double _voltage = 0.0;
String _currentGain = "GAIN_ONE";
String _currentChannel = "UNI_0";
Expand Down Expand Up @@ -82,7 +86,7 @@ class ADS1115Provider extends ChangeNotifier {

_ads1115 = await ADS1115.create(i2c, scienceLab);
_updateCurrentSettings();
notifyListeners();
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error initializing ADS1115: $e');
}
Expand All @@ -100,23 +104,23 @@ class ADS1115Provider extends ChangeNotifier {
if (_ads1115 != null) {
_ads1115!.setGain(gain);
_currentGain = gain;
notifyListeners();
if (!_isDisposed) notifyListeners();
}
}

void setChannel(String channel) {
if (_ads1115 != null) {
_ads1115!.setChannel(channel);
_currentChannel = channel;
notifyListeners();
if (!_isDisposed) notifyListeners();
}
}

void setRate(int rate) {
if (_ads1115 != null) {
_ads1115!.setDataRate(rate);
_currentRate = rate;
notifyListeners();
if (!_isDisposed) notifyListeners();
}
}

Expand All @@ -133,8 +137,13 @@ class ADS1115Provider extends ChangeNotifier {

_isRunning = true;
_collectedReadings = 0;
_isFetching = false;

_dataTimer =
Timer.periodic(Duration(milliseconds: _timegapMs), (timer) async {
if (_isFetching || _isDisposed) return;
_isFetching = true;

try {
await _fetchSensorData();
_collectedReadings++;
Expand All @@ -147,29 +156,36 @@ class ADS1115Provider extends ChangeNotifier {
_removeOldestDataPoints();
}
} catch (e) {
logger.e('Error fetching sensor data: $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;
}
});
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void _stopDataCollection() {
_isRunning = false;
_dataTimer?.cancel();
_dataTimer = null;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

Future<void> _fetchSensorData() async {
if (_ads1115 == null) return;
if (_ads1115 == null || _isDisposed) return;

try {
final rawData = await _ads1115!.getRawData();
_voltage = rawData['voltage'] ?? 0.0;
_currentTime += _timegapMs / 1000.0;

_addDataPoint(_voltageData, _voltage);
notifyListeners();
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error in _fetchSensorData: $e');
rethrow;
Expand All @@ -193,32 +209,31 @@ class ADS1115Provider extends ChangeNotifier {

void toggleLooping() {
_isLooping = !_isLooping;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void setTimegap(int timegapMs) {
if (_timegapMs == timegapMs) {
return;
}
if (_timegapMs == timegapMs) return;

_timegapMs = timegapMs;
if (_isRunning) {
_stopDataCollection();
_startDataCollection();
}
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void setNumberOfReadings(int numberOfReadings) {
_numberOfReadings = numberOfReadings;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void clearData() {
_voltageData.clear();
_voltage = 0.0;
_currentTime = 0.0;
_collectedReadings = 0;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

bool get isCollectionComplete {
Expand All @@ -227,6 +242,7 @@ class ADS1115Provider extends ChangeNotifier {

@override
void dispose() {
_isDisposed = true;
_stopDataCollection();
super.dispose();
}
Expand Down
37 changes: 26 additions & 11 deletions lib/providers/apds9960_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ class APDS9960Provider extends ChangeNotifier {
APDS9960? _apds9960;
Timer? _dataTimer;

bool _isDisposed = false;
bool _isFetching = false;

int _red = 0;
int _green = 0;
int _blue = 0;
Expand Down Expand Up @@ -76,7 +79,7 @@ class APDS9960Provider extends ChangeNotifier {
}

_apds9960 = await APDS9960.create(i2c, scienceLab);
notifyListeners();
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error initializing APDS9960: $e');
}
Expand All @@ -96,7 +99,7 @@ class APDS9960Provider extends ChangeNotifier {
_gestureString = '';
}

notifyListeners();
if (!_isDisposed) notifyListeners();
}
}

Expand All @@ -113,9 +116,13 @@ class APDS9960Provider extends ChangeNotifier {

_isRunning = true;
_collectedReadings = 0;
_isFetching = false;
Comment thread
rahul31124 marked this conversation as resolved.

_dataTimer =
Timer.periodic(Duration(milliseconds: _timegapMs), (timer) async {
if (_isFetching || _isDisposed) return;
_isFetching = true;

try {
await _fetchSensorData();
_collectedReadings++;
Expand All @@ -128,21 +135,28 @@ class APDS9960Provider extends ChangeNotifier {
_removeOldestDataPoints();
}
} catch (e) {
logger.e('Error fetching sensor data: $e');
String errorMsg = e.toString();
if (errorMsg.contains("Expected")) {
logger.w('APDS9960 dropped a frame. Skipping gracefully...');
} else {
logger.e('Error fetching sensor data: $e');
}
} finally {
_isFetching = false;
}
});
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void _stopDataCollection() {
_isRunning = false;
_dataTimer?.cancel();
_dataTimer = null;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

Future<void> _fetchSensorData() async {
if (_apds9960 == null) return;
if (_apds9960 == null || _isDisposed) return;

try {
final rawData = await _apds9960!.getRawData(_mode);
Expand All @@ -168,7 +182,7 @@ class APDS9960Provider extends ChangeNotifier {
_gestureString = _apds9960!.getGestureString(_gesture);
}

notifyListeners();
if (!_isDisposed) notifyListeners();
} catch (e) {
logger.e('Error in _fetchSensorData: $e');
rethrow;
Expand All @@ -194,7 +208,7 @@ class APDS9960Provider extends ChangeNotifier {

void toggleLooping() {
_isLooping = !_isLooping;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void setTimegap(int timegapMs) {
Expand All @@ -205,12 +219,12 @@ class APDS9960Provider extends ChangeNotifier {
_startDataCollection();
}

notifyListeners();
if (!_isDisposed) notifyListeners();
}

void setNumberOfReadings(int numberOfReadings) {
_numberOfReadings = numberOfReadings;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

void clearData() {
Expand All @@ -226,7 +240,7 @@ class APDS9960Provider extends ChangeNotifier {
_gestureString = '';
_currentTime = 0.0;
_collectedReadings = 0;
notifyListeners();
if (!_isDisposed) notifyListeners();
}

bool get isCollectionComplete {
Expand All @@ -235,6 +249,7 @@ class APDS9960Provider extends ChangeNotifier {

@override
void dispose() {
_isDisposed = true;
_stopDataCollection();
super.dispose();
}
Expand Down
Loading
Loading