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.

70 lines
2.2 KiB

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