DeskFanController.cs 2.1 KB

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