PolarEcgDataLogger.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using Sensors;
  5. using Sensors.Polar;
  6. using UniRx;
  7. using UnityEngine;
  8. namespace Logging
  9. {
  10. public readonly struct PolarSensorEcgLog : ISerializable
  11. {
  12. private readonly long timestamp;
  13. private readonly float ecg;
  14. public PolarSensorEcgLog(int timestamp, float ecg)
  15. {
  16. this.timestamp = timestamp;
  17. this.ecg = ecg;
  18. }
  19. public KeyValuePair<long, string[]> Serialize() =>
  20. new KeyValuePair<long, string[]>(timestamp, new[]
  21. {
  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 async 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. await bikeSensorData.PolarReceiverAvailable;
  42. sub = bikeSensorData.RawEcgData?.Subscribe(data => OnData(data));
  43. }
  44. private void OnData(in EcgData data)
  45. {
  46. if (timeSync.DifDataStreamStart < 0)
  47. {
  48. timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
  49. }
  50. if (startTime < 0)
  51. {
  52. startTime = data.Timestamp;
  53. }
  54. var internalTimestamp =
  55. (data.Timestamp - startTime) / 1000000;
  56. var timestamp = Mathf.RoundToInt(internalTimestamp + timeSync.DifDataStreamStart);
  57. foreach (var item in data.Values)
  58. {
  59. Log(new PolarSensorEcgLog(timestamp, item));
  60. timestamp += 1000 / ECG_SAMPLE_RATE;
  61. }
  62. }
  63. public override IEnumerable<PolarSensorEcgLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
  64. {
  65. throw new System.NotImplementedException(); //TODO
  66. }
  67. private void OnDestroy()
  68. {
  69. sub?.Dispose();
  70. }
  71. }
  72. }