PolarAccDataLogger.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. {
  25. return new KeyValuePair<long, string[]>(timestamp, new[]
  26. {
  27. accX.ToString("F4", CultureInfo.InvariantCulture),
  28. accY.ToString("F4", CultureInfo.InvariantCulture),
  29. accZ.ToString("F4", CultureInfo.InvariantCulture)
  30. });
  31. }
  32. }
  33. public class PolarAccDataLogger : SensorDataLogger<PolarAccDataLog>
  34. {
  35. private long startTimeAcc = -1;
  36. private IDisposable sub;
  37. private TimeSync timeSync;
  38. public override string Key => "polar_acc_data";
  39. public override async void Start()
  40. {
  41. base.Start();
  42. timeSync = new TimeSync
  43. {
  44. StartTime = DateTime.Now,
  45. DifDataStreamStart = -1
  46. };
  47. var bikeSensorData = BikeSensorData.Instance;
  48. await bikeSensorData.PolarReceiverAvailable;
  49. sub = bikeSensorData.RawAccData?.Subscribe(data => OnData(data));
  50. }
  51. private void OnDestroy()
  52. {
  53. sub?.Dispose();
  54. }
  55. private void OnData(in AccData data)
  56. {
  57. if (timeSync.DifDataStreamStart < 0)
  58. timeSync.DifDataStreamStart = (long) (DateTime.Now - timeSync.StartTime).TotalMilliseconds;
  59. if (startTimeAcc < 0) startTimeAcc = data.Timestamp;
  60. if (BikeSensorData.Instance.PolarConfig == null) return;
  61. var internalTimestamp =
  62. (data.Timestamp - startTimeAcc) / 1000000;
  63. var timestamp = Helpers.RoundToLong(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 IEnumerable<PolarAccDataLog> ReadLog(IEnumerable<IEnumerable<string>> lines)
  71. {
  72. throw new NotImplementedException(); //TODO
  73. }
  74. }
  75. }