12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using Sensors;
- using Sensors.Polar;
- using UniRx;
- namespace Logging
- {
- public readonly struct PolarSensorEcgLog
- {
- private readonly float timestamp;
- private readonly float ecg;
- public PolarSensorEcgLog(float timestamp, float ecg)
- {
- this.timestamp = timestamp;
- this.ecg = ecg;
- }
- public string[] Serialize() =>
- new[]
- {
- timestamp.ToString("F4", CultureInfo.InvariantCulture),
- ecg.ToString("F4", CultureInfo.InvariantCulture)
- };
- }
- public class PolarEcgDataLogger : SensorDataLogger<PolarSensorEcgLog>
- {
- public override string Key => "polar_ecg_data";
- private long startTime = -1;
- private TimeSync timeSync;
- private const int ECG_SAMPLE_RATE = 130;
- private IDisposable sub;
- public override void Start()
- {
- base.Start();
- timeSync = new TimeSync
- {
- StartTime = DateTime.Now,
- DifDataStreamStart = -1
- };
- var bikeSensorData = BikeSensorData.Instance;
- sub = bikeSensorData.RawEcgData?.Subscribe(data => OnData(data));
- }
- 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 = internalTimestamp + timeSync.DifDataStreamStart;
- foreach (var item in data.Values)
- {
- Log(new PolarSensorEcgLog(timestamp, item));
- timestamp += 1000 / ECG_SAMPLE_RATE;
- }
- }
- public override void Log(PolarSensorEcgLog value)
- {
- Buffer.Add(value.Serialize());
- }
- public override IEnumerable<PolarSensorEcgLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
- {
- throw new System.NotImplementedException(); //TODO
- }
- private void OnDestroy()
- {
- sub?.Dispose();
- }
- }
- }
|