PolarAccDataLogger.cs 2.7 KB

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