12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using Logging.Base;
- using Sensors;
- using Sensors.Bluetooth;
- using Sensors.Polar;
- using UniRx;
- namespace Logging.Data
- {
- public readonly struct PolarSensorEcgLog : ISerializable
- {
- private readonly long timestamp;
- private readonly float ecg;
- public PolarSensorEcgLog(long timestamp, float ecg)
- {
- this.timestamp = timestamp;
- this.ecg = ecg;
- }
- public KeyValuePair<long, string[]> Serialize()
- {
- return new KeyValuePair<long, string[]>(timestamp, new[]
- {
- ecg.ToString("F4", CultureInfo.InvariantCulture)
- });
- }
- }
- public class PolarEcgDataLogger : SensorDataLogger<PolarSensorEcgLog>
- {
- private const int ECG_SAMPLE_RATE = 130;
- private long startTime = -1;
- private IDisposable sub;
- private TimeSync timeSync;
- public override string Key => "polar_ecg_data";
- public override async void Start()
- {
- base.Start();
- timeSync = new TimeSync
- {
- StartTime = DateTime.Now,
- DifDataStreamStart = -1
- };
- var bikeSensorData = BikeSensorData.Instance;
- await bikeSensorData.PolarReceiverAvailable;
- sub = bikeSensorData.RawEcgData?.Subscribe(data => OnData(data));
- }
- private void OnDestroy()
- {
- sub?.Dispose();
- }
- private void OnData(in EcgData data)
- {
- if (timeSync.DifDataStreamStart < 0)
- timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
- if (startTime < 0) startTime = data.Timestamp;
- var internalTimestamp =
- (data.Timestamp - startTime) / 1000000;
- var timestamp = Helpers.RoundToLong(internalTimestamp + timeSync.DifDataStreamStart);
- foreach (var item in data.Values)
- {
- Log(new PolarSensorEcgLog(timestamp, item));
- timestamp += 1000 / ECG_SAMPLE_RATE;
- }
- }
- public override IEnumerable<PolarSensorEcgLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
- {
- throw new NotImplementedException(); //TODO
- }
- }
- }
|