VibrationController.cs 2.3 KB

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