Skip to content

Commit

Permalink
use broadcast stream for OpenEarable sensors
Browse files Browse the repository at this point in the history
  • Loading branch information
DennisMoschina committed Jan 20, 2025
1 parent 7d2b1b5 commit 40dbc09
Showing 1 changed file with 23 additions and 5 deletions.
28 changes: 23 additions & 5 deletions lib/src/models/devices/open_earable_factory.dart
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,10 @@ class _OpenEarableSensor extends Sensor {

StreamSubscription? _dataSubscription;

int _listenersCount = 0;

final StreamController<SensorValue> _streamController = StreamController.broadcast();

_OpenEarableSensor({
required int sensorId,
required String sensorName,
Expand All @@ -235,7 +239,22 @@ class _OpenEarableSensor extends Sensor {
sensorName: sensorName,
chartTitle: chartTitle,
shortChartTitle: shortChartTitle,
);
) {
_streamController.onListen = () {
_listenersCount++;
logger.t("Sensor stream listener added from $sensorName, $_listenersCount listeners");
if (_listenersCount > 0) {
_dataSubscription?.resume();
}
};
_streamController.onCancel = () {
_listenersCount--;
logger.t("Sensor stream listener removed from $sensorName, $_listenersCount listeners");
if (_listenersCount == 0) {
_dataSubscription?.pause();
}
};
}

@override
List<String> get axisNames => _axisNames;
Expand Down Expand Up @@ -283,15 +302,14 @@ class _OpenEarableSensor extends Sensor {
}

Stream<SensorValue> _createSingleDataSubscription(String componentName) {
StreamController<SensorValue> streamController = StreamController.broadcast();

_dataSubscription?.cancel();
_dataSubscription = _sensorManager.subscribeToSensorData(_sensorId).listen((data) {
int timestamp = data["timestamp"];
logger.t("SensorData: $data");

logger.t("componentData of $componentName: ${data[componentName]}");

//TODO: use int for integer based values
List<double> values = [];
for (var entry in (data[componentName] as Map).entries) {
if (entry.key == 'units') {
Expand All @@ -306,10 +324,10 @@ class _OpenEarableSensor extends Sensor {
timestamp: timestamp,
);

streamController.add(sensorValue);
_streamController.add(sensorValue);
});

return streamController.stream;
return _streamController.stream;
}

@override
Expand Down

0 comments on commit 40dbc09

Please sign in to comment.