BikeSensorData.cs 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Data;
  3. using System.Threading.Tasks;
  4. using JetBrains.Annotations;
  5. using Sensors.ANT;
  6. using Sensors.Polar;
  7. namespace Sensors
  8. {
  9. public sealed class BikeSensorData
  10. {
  11. #region signleton
  12. private static readonly Lazy<BikeSensorData>
  13. lazy =
  14. new Lazy<BikeSensorData>
  15. (() => new BikeSensorData());
  16. public static BikeSensorData Instance => lazy.Value;
  17. #endregion
  18. [CanBeNull] private PowerMeterReceiver powerMeterReceiver;
  19. [CanBeNull] private SpeedSensorReceiver speedSensorReceiver;
  20. [CanBeNull] private HrReceiver hrReceiver;
  21. [CanBeNull] private PolarReceiver polarReceiver;
  22. public SpeedSensorData? SpeedData => speedSensorReceiver?.SensorData;
  23. public PowermeterSensorData? PowermeterData => powerMeterReceiver?.SensorData;
  24. public HrSensorData? HrData => hrReceiver?.SensorData;
  25. public PolarSensorData? PolarData => polarReceiver?.SensorData;
  26. private BikeSensorData()
  27. {
  28. }
  29. public async Task StartListening(SpeedSensorConfig? speedSensorConfig = null,
  30. PolarSensorConfig? polarSensorConfig = null, int? powermeterId = null, int? hrAntId = null)
  31. {
  32. if (speedSensorConfig != null)
  33. {
  34. if(speedSensorReceiver != null)
  35. {
  36. throw new InvalidConstraintException(
  37. "BikeSensorData: Already listening to Speed Sensor");
  38. }
  39. speedSensorReceiver = new SpeedSensorReceiver(speedSensorConfig.Value);
  40. speedSensorReceiver.StartScan();
  41. }
  42. if (hrAntId != null)
  43. {
  44. if(hrReceiver != null)
  45. {
  46. throw new InvalidConstraintException(
  47. "BikeSensorData: Already listening to HR Sensor");
  48. }
  49. hrReceiver = new HrReceiver(hrAntId.Value);
  50. hrReceiver.StartScan();
  51. }
  52. if (powermeterId != null)
  53. {
  54. if (powerMeterReceiver != null)
  55. {
  56. throw new InvalidConstraintException(
  57. "BikeSensorData: Already listening to Power Sensor");
  58. }
  59. powerMeterReceiver = new PowerMeterReceiver(powermeterId.Value);
  60. powerMeterReceiver.StartScan();
  61. }
  62. if (polarSensorConfig != null)
  63. {
  64. if (polarReceiver != null)
  65. {
  66. throw new InvalidConstraintException(
  67. "BikeSensorData: Already listening to Polar Sensor");
  68. }
  69. polarReceiver = new PolarReceiver(polarSensorConfig.Value); //automatically starts listening
  70. await polarReceiver.StartListening();
  71. }
  72. }
  73. public void Dispose()
  74. {
  75. polarReceiver?.Dispose();
  76. //TODO: also dispose ANT sensors?
  77. polarReceiver = null;
  78. speedSensorReceiver = null;
  79. powerMeterReceiver = null;
  80. hrReceiver = null;
  81. }
  82. }
  83. }