FanController.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. {
  33. await Broker.Publish(TOPIC.Replace(CHANNEL_NUMBER_PLACEHOLDER, $"{i}"), $"{cycle}");
  34. }
  35. }
  36. }
  37. private int FanCycleForSpeed()
  38. {
  39. return (int) Mathf.Lerp(0f, MAX_FAN_CYCLE, bicycleController.CurrentSpeed / MAX_CYCLE_AT_SPEED);
  40. }
  41. }
  42. }