PolarEcgDataLogger.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using Sensors;
  5. using Sensors.Polar;
  6. using UniRx;
  7. namespace Logging
  8. {
  9. public readonly struct PolarSensorEcgLog
  10. {
  11. private readonly float timestamp;
  12. private readonly float ecg;
  13. public PolarSensorEcgLog(float timestamp, float ecg)
  14. {
  15. this.timestamp = timestamp;
  16. this.ecg = ecg;
  17. }
  18. public string[] Serialize() =>
  19. new[]
  20. {
  21. timestamp.ToString("F4", CultureInfo.InvariantCulture),
  22. ecg.ToString("F4", CultureInfo.InvariantCulture)
  23. };
  24. }
  25. public class PolarEcgDataLogger : SensorDataLogger<PolarSensorEcgLog>
  26. {
  27. public override string Key => "polar_ecg_data";
  28. private long startTime = -1;
  29. private TimeSync timeSync;
  30. private const int ECG_SAMPLE_RATE = 130;
  31. private IDisposable sub;
  32. public override void Start()
  33. {
  34. base.Start();
  35. timeSync = new TimeSync
  36. {
  37. StartTime = DateTime.Now,
  38. DifDataStreamStart = -1
  39. };
  40. var bikeSensorData = BikeSensorData.Instance;
  41. sub = bikeSensorData.RawEcgData?.Subscribe(data => OnData(data));
  42. }
  43. private void OnData(in EcgData data)
  44. {
  45. if (timeSync.DifDataStreamStart < 0)
  46. {
  47. timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
  48. }
  49. if (startTime < 0)
  50. {
  51. startTime = data.Timestamp;
  52. }
  53. var internalTimestamp =
  54. (data.Timestamp - startTime) / 1000000;
  55. var timestamp = internalTimestamp + timeSync.DifDataStreamStart;
  56. foreach (var item in data.Values)
  57. {
  58. Log(new PolarSensorEcgLog(timestamp, item));
  59. timestamp += 1000 / ECG_SAMPLE_RATE;
  60. }
  61. }
  62. public override void Log(PolarSensorEcgLog value)
  63. {
  64. Buffer.Add(value.Serialize());
  65. }
  66. public override IEnumerable<PolarSensorEcgLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
  67. {
  68. throw new System.NotImplementedException(); //TODO
  69. }
  70. private void OnDestroy()
  71. {
  72. sub?.Dispose();
  73. }
  74. }
  75. }