DeskFanController.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Threading.Tasks;
  2. using Controller.Bicycle;
  3. using UnityEngine;
  4. namespace SicknessReduction.Haptic
  5. {
  6. [RequireComponent(typeof(DynamicReductionSource))]
  7. public class DeskFanController : EspController
  8. {
  9. private const int MAX_FAN_VALUE = 95; //in %. Sometimes 100% doesn't work correctly
  10. private const int
  11. MIN_FAN_VALUE =
  12. 25; //everything below 35 will not be enough to let the fan spin; a bit of buffer for not starting to high
  13. private const string TOPIC = "DeskFan/Control";
  14. public float maxValueAtSpeed = 6.94f; //25km/h
  15. public float speedUntilNoFan = 1.94f; //2kmh
  16. public RbBicycleController bicycleController;
  17. public bool useReductionSource = true;
  18. private int previousFanValue;
  19. private DynamicReductionSource reductionSource;
  20. protected override void Start()
  21. {
  22. base.Start();
  23. reductionSource = GetComponent<DynamicReductionSource>();
  24. }
  25. protected override async void Update()
  26. {
  27. base.Update();
  28. if (!DoUpdate || PreviousUpdateActive) return;
  29. PreviousUpdateActive = true;
  30. var cycle = useReductionSource ? FanCycleForReductionSource() : FanCycleForSpeed();
  31. await SendFanValue(cycle);
  32. PreviousUpdateActive = false;
  33. }
  34. private int FanCycleForReductionSource()
  35. {
  36. var reductionValue = reductionSource.CurrentValue;
  37. return (int) Mathf.Lerp(MIN_FAN_VALUE, MAX_FAN_VALUE, reductionValue);
  38. }
  39. private async Task SendFanValue(int value)
  40. {
  41. if (previousFanValue != value)
  42. {
  43. previousFanValue = value;
  44. await Broker.Publish(TOPIC, $"{value}");
  45. }
  46. }
  47. private int FanCycleForSpeed()
  48. {
  49. var speed = bicycleController.CurrentSpeed;
  50. if (speed <= speedUntilNoFan) return 0;
  51. return (int) Mathf.Lerp(MIN_FAN_VALUE, MAX_FAN_VALUE, speed / maxValueAtSpeed);
  52. }
  53. }
  54. }