PolarAccDataLogger.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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 float timestamp;
  13. private readonly float accX;
  14. private readonly float accY;
  15. private readonly float accZ;
  16. public PolarAccDataLog(float 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("F4", 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 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. 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 = 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 void Log(PolarAccDataLog value)
  70. {
  71. Buffer.Add(value.Serialize());
  72. }
  73. public override IEnumerable<PolarAccDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
  74. {
  75. throw new System.NotImplementedException(); //TODO
  76. }
  77. private void OnDestroy()
  78. {
  79. sub?.Dispose();
  80. }
  81. }
  82. }