123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657 |
- using Sensors;
- namespace SicknessReduction.Haptic
- {
- public class VibrationController : EspController
- {
- private const string TOPIC_CYCLE = "Vibration/Control/Cycle";
- private const string TOPIC_CADENCE = "Vibration/Control/Cadence";
- private const int THRES_CADENCE_CHANGE = 4;
- private const int CYCLE = 56;
- private bool initialCyclePublished;
- private int previousCadence = -1;
- protected override async void Update()
- {
- base.Update();
- if (!DoUpdate || PreviousUpdateActive) return;
- var cadence = BikeSensorData.Instance.PowermeterData?.InstantaneousCadence;
- if (!cadence.HasValue) return;
- var c = cadence.Value;
-
- PreviousUpdateActive = true; //flag to avoid concurrent updates
- //as soon as we have a cadence, we want the motors to vibrate
- if (!initialCyclePublished)
- {
- await Broker.Publish(TOPIC_CYCLE, $"{CYCLE}");
- initialCyclePublished = true;
- }
- //if the cadence changes to 0, we have to switch off vibration
- if (c == 0)
- {
- await Broker.Publish(TOPIC_CYCLE, "0");
- previousCadence = c;
- }
- //as soon as we have cadence again, we want to switch on vibration again, and then immediately set cadence again
- else if (previousCadence == 0)
- {
- await Broker.Publish(TOPIC_CYCLE, $"{CYCLE}");
- PublishCadence(c);
- }
- //if we have never set cadence, or the change of cadence is high enough, we tell the ESP to change cadence
- else if (previousCadence < 0 || c - previousCadence > THRES_CADENCE_CHANGE)
- {
- PublishCadence(c);
- }
- PreviousUpdateActive = false;
- }
- private async void PublishCadence(int cadence)
- {
- await Broker.Publish(TOPIC_CADENCE, $"{cadence}");
- previousCadence = cadence;
- }
- }
- }
|