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.

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