VibrationController.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Sensors;
  2. namespace SicknessReduction.Haptic
  3. {
  4. public class VibrationController : EspController
  5. {
  6. private const string TOPIC_CYCLE = "Vibration/Control/Cycle";
  7. private const string TOPIC_CADENCE = "Vibration/Control/Cadence";
  8. private const int THRES_CADENCE_CHANGE = 4;
  9. private const int CYCLE = 56;
  10. private bool initialCyclePublished;
  11. private int previousCadence = -1;
  12. protected override async void Update()
  13. {
  14. base.Update();
  15. if (!DoUpdate || PreviousUpdateActive) return;
  16. var cadence = BikeSensorData.Instance.PowermeterData?.InstantaneousCadence;
  17. if (!cadence.HasValue) return;
  18. var c = cadence.Value;
  19. PreviousUpdateActive = true; //flag to avoid concurrent updates
  20. //as soon as we have a cadence, we want the motors to vibrate
  21. if (!initialCyclePublished)
  22. {
  23. await Broker.Publish(TOPIC_CYCLE, $"{CYCLE}");
  24. initialCyclePublished = true;
  25. }
  26. //if the cadence changes to 0, we have to switch off vibration
  27. if (c == 0)
  28. {
  29. await Broker.Publish(TOPIC_CYCLE, "0");
  30. previousCadence = c;
  31. }
  32. //as soon as we have cadence again, we want to switch on vibration again, and then immediately set cadence again
  33. else if (previousCadence == 0)
  34. {
  35. await Broker.Publish(TOPIC_CYCLE, $"{CYCLE}");
  36. PublishCadence(c);
  37. }
  38. //if we have never set cadence, or the change of cadence is high enough, we tell the ESP to change cadence
  39. else if (previousCadence < 0 || c - previousCadence > THRES_CADENCE_CHANGE)
  40. {
  41. PublishCadence(c);
  42. }
  43. PreviousUpdateActive = false;
  44. }
  45. private async void PublishCadence(int cadence)
  46. {
  47. await Broker.Publish(TOPIC_CADENCE, $"{cadence}");
  48. previousCadence = cadence;
  49. }
  50. }
  51. }