attach method
Attach this RxIMU to the Frame's dataResponse characteristic stream.
Implementation
Stream<IMUData> attach(Stream<List<int>> dataResponse) {
// TODO check for illegal state - attach() already called on this RxIMU etc?
// might be possible though after a clean close(), do I want to prevent it?
// the subscription to the underlying data stream
StreamSubscription<List<int>>? dataResponseSubs;
// Our stream controller that transforms the dataResponse elements into IMUData events
_controller = StreamController();
_controller!.onListen = () {
dataResponseSubs = dataResponse
.where((data) => data[0] == imuFlag)
.listen((data) {
Uint8List bytes = Uint8List.fromList(data);
// reinterpret the bytes after offset 2 as signed 16-bit integers
Int16List s16 = bytes.buffer.asInt16List(2);
// Get raw values
var rawCompass = (s16[0], s16[1], s16[2]);
var rawAccel = (s16[3], s16[4], s16[5]);
// Add to buffers
_compassBuffer.add(rawCompass);
_accelBuffer.add(rawAccel);
_controller!.add(IMUData(
compass: _compassBuffer.average,
accel: _accelBuffer.average,
raw: IMURawData(
compass: rawCompass,
accel: rawAccel,
),
));
}, onDone: _controller!.close, onError: _controller!.addError);
_log.fine('ImuDataResponse stream subscribed');
};
_controller!.onCancel = () {
_log.fine('ImuDataResponse stream unsubscribed');
dataResponseSubs?.cancel();
_controller!.close();
};
return _controller!.stream;
}