PolarEcgDataLogger.cs 2.3 KB

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