1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 |
- using Sensors;
- using UnityEngine;
- 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 = 128;
- 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)
- {
- Debug.Log($"Sending cycle {CYCLE}");
- await Broker.Publish(TOPIC_CYCLE, $"{CYCLE}");
- initialCyclePublished = true;
- }
- //if the cadence changes to 0, we have to switch off vibration
- if (c == 0)
- {
- Debug.Log($"Sending cycle {CYCLE}");
- 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)
- {
- Debug.Log($"Sending cycle {CYCLE}");
- 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)
- {
- Debug.Log($"Sending Cadence {cadence}");
- await Broker.Publish(TOPIC_CADENCE, $"{cadence}");
- previousCadence = cadence;
- }
- }
- }
|