1
0

PolarAccDataLogger.cs 2.7 KB

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