FanController.cs 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. using System;
  2. using System.Threading.Tasks;
  3. using Controller.Bicycle;
  4. using UnityEngine;
  5. namespace SicknessReduction.Haptic
  6. {
  7. public class FanController : EspController
  8. {
  9. private const int MAX_FAN_CYCLE = 256; //for RES=8
  10. private const float MAX_CYCLE_AT_SPEED = 6.94f; //25km/h
  11. private const int THRES_CYCLE_CHANGE = 3;
  12. private const int NUM_CHANNELS = 4;
  13. private const string TOPIC = "Fan/CHANNEL_NUMBER/Control";
  14. private const string CHANNEL_NUMBER_PLACEHOLDER = "CHANNEL_NUMBER";
  15. public RbBicycleController bicycleController;
  16. private int previousFanCycle;
  17. protected override async void Update()
  18. {
  19. base.Update();
  20. if (!DoUpdate || PreviousUpdateActive) return;
  21. PreviousUpdateActive = true;
  22. var cycle = FanCycleForSpeed();
  23. await SendFanCycles(cycle);
  24. PreviousUpdateActive = false;
  25. }
  26. private async Task SendFanCycles(int cycle)
  27. {
  28. if (Math.Abs(cycle - previousFanCycle) > THRES_CYCLE_CHANGE)
  29. {
  30. previousFanCycle = cycle;
  31. for (var i = 0; i < NUM_CHANNELS; i++)
  32. await Broker.Publish(TOPIC.Replace(CHANNEL_NUMBER_PLACEHOLDER, $"{i}"), $"{cycle}");
  33. }
  34. }
  35. private int FanCycleForSpeed()
  36. {
  37. return (int) Mathf.Lerp(0f, MAX_FAN_CYCLE, bicycleController.CurrentSpeed / MAX_CYCLE_AT_SPEED);
  38. }
  39. }
  40. }