You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.1 KiB

  1. #pragma once
  2. #include <cmath>
  3. #include "../common.h"
  4. #include "../front_panel_hal.h"
  5. #include "esphome/components/sensor/sensor.h"
  6. namespace esphome {
  7. namespace yeelight {
  8. namespace bs2 {
  9. /**
  10. * A sensor for the slider on the Yeelight Bedside Lamp 2.
  11. *
  12. * This sensor publishes the level at which the slider was touched, so it
  13. * can be used to implement automations. Note that it does not represent
  14. * the brightness of the LED lights (this is implemented by the light output
  15. * component), nor the level as displayed by the slider using the front
  16. * panel light (this is implemented by the slider light component).
  17. */
  18. class YeelightBS2SliderSensor : public sensor::Sensor, public Component {
  19. public:
  20. void set_parent(FrontPanelHAL *front_panel) { front_panel_ = front_panel; }
  21. void set_range_from(float from) { range_from_ = from; }
  22. void set_range_to(float to) { range_to_ = to; }
  23. void setup() {
  24. ESP_LOGCONFIG(TAG, "Setting up slider sensor ...");
  25. ESP_LOGCONFIG(TAG, " Range from: %f", range_from_);
  26. ESP_LOGCONFIG(TAG, " Range to: %f", range_to_);
  27. slope_ = (range_to_ - range_from_) / 19.0f;
  28. front_panel_->add_on_event_callback(
  29. [this](EVENT ev) {
  30. if ((ev & FLAG_PART_MASK) == FLAG_PART_SLIDER) {
  31. float level = (ev & FLAG_LEVEL_MASK) >> FLAG_LEVEL_SHIFT;
  32. // Slider level 1 is really hard to touch. It is between
  33. // the power button and the slider space, so it doesn't
  34. // look like this one was ever meant to be used, or that
  35. // the design was faulty on this. Therefore, level 1 is
  36. // ignored. The resulting range of levels is 0-19.
  37. float corrected_level = max(0.0f, level - 2.0f);
  38. float final_level = range_from_ + (slope_ * corrected_level);
  39. this->publish_state(final_level);
  40. }
  41. }
  42. );
  43. }
  44. protected:
  45. FrontPanelHAL *front_panel_;
  46. float range_from_;
  47. float range_to_;
  48. float slope_;
  49. };
  50. } // namespace bs2
  51. } // namespace yeelight
  52. } // namespace esphome