PolarAccDataLogger.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 PolarAccDataLog
  11. {
  12. private readonly int timestamp;
  13. private readonly float accX;
  14. private readonly float accY;
  15. private readonly float accZ;
  16. public PolarAccDataLog(int 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 string[] Serialize() =>
  24. new[]
  25. {
  26. timestamp.ToString("D", CultureInfo.InvariantCulture),
  27. accX.ToString("F4", CultureInfo.InvariantCulture),
  28. accY.ToString("F4", CultureInfo.InvariantCulture),
  29. accZ.ToString("F4", CultureInfo.InvariantCulture),
  30. };
  31. }
  32. public class PolarAccDataLogger : SensorDataLogger<PolarAccDataLog>
  33. {
  34. public override string Key => "polar_acc_data";
  35. private long startTimeAcc = -1;
  36. private TimeSync timeSync;
  37. private IDisposable sub;
  38. public override async void Start()
  39. {
  40. base.Start();
  41. timeSync = new TimeSync
  42. {
  43. StartTime = DateTime.Now,
  44. DifDataStreamStart = -1
  45. };
  46. var bikeSensorData = BikeSensorData.Instance;
  47. await bikeSensorData.PolarReceiverAvailable;
  48. sub = bikeSensorData.RawAccData?.Subscribe(data => OnData(data));
  49. }
  50. private void OnData(in AccData data)
  51. {
  52. if (timeSync.DifDataStreamStart < 0)
  53. {
  54. timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
  55. }
  56. if (startTimeAcc < 0)
  57. {
  58. startTimeAcc = data.Timestamp;
  59. }
  60. if (BikeSensorData.Instance.PolarConfig == null) return;
  61. var internalTimestamp =
  62. (data.Timestamp - startTimeAcc) / 1000000;
  63. var timestamp = Mathf.RoundToInt(internalTimestamp + timeSync.DifDataStreamStart);
  64. foreach (var item in data.Values)
  65. {
  66. Log(new PolarAccDataLog(timestamp, item.x, item.y, item.z));
  67. timestamp += 1000 / BikeSensorData.Instance.PolarConfig.Value.accSampleRate;
  68. }
  69. }
  70. public override void Log(PolarAccDataLog value)
  71. {
  72. Buffer.Add(value.Serialize());
  73. }
  74. public override IEnumerable<PolarAccDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
  75. {
  76. throw new System.NotImplementedException(); //TODO
  77. }
  78. private void OnDestroy()
  79. {
  80. sub?.Dispose();
  81. }
  82. }
  83. }