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.

324 lines
10 KiB

  1. #pragma once
  2. #include "common.h"
  3. #include "esphome/components/i2c/i2c.h"
  4. #include "esphome/core/component.h"
  5. #include "esphome/core/esphal.h"
  6. #include <array>
  7. #include <cmath>
  8. namespace esphome {
  9. namespace xiaomi {
  10. namespace bslamp2 {
  11. static const uint8_t MSG_LEN = 7;
  12. using MSG = uint8_t[MSG_LEN];
  13. using LED = uint16_t;
  14. using EVENT = uint16_t;
  15. // clang-format off
  16. // Bit flags that are used for indicating the LEDs in the front panel.
  17. // LED_1 is the slider LED closest to the power button.
  18. // LED_10 is the one closest to the color button.
  19. enum FrontPanelLEDs {
  20. LED_ALL = 16384 + 4096 + 1023,
  21. LED_POWER = 16384,
  22. LED_COLOR = 4096,
  23. LED_1 = 512,
  24. LED_2 = 256,
  25. LED_3 = 128,
  26. LED_4 = 64,
  27. LED_5 = 32,
  28. LED_6 = 16,
  29. LED_7 = 8,
  30. LED_8 = 4,
  31. LED_9 = 2,
  32. LED_10 = 1,
  33. LED_NONE = 0,
  34. };
  35. // This I2C command is used during front panel event handling.
  36. static const MSG READY_FOR_EV = {0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01};
  37. // Bit flags that are used for specifying an event.
  38. // Events are registered using the following bit pattern
  39. // (bit 1 being the least significant bit):
  40. //
  41. // BITS INDICATE PATTERN RESULT
  42. // 1 status 0 parsing event failed
  43. // 1 parsing event successful
  44. // 2-4 part 000 part unknown
  45. // 001 power button
  46. // 010 color button
  47. // 100 slider
  48. // 5-6 type 00 type unknown
  49. // 01 touch
  50. // 10 release
  51. // 7-11 slider 00000 level known (or part is not "slider")
  52. // level 00001 level 1
  53. // ... up to
  54. // 10101 level 21
  55. //
  56. static const EVENT FLAG_INIT = 0b00000000000;
  57. static const EVENT FLAG_ERR = 0b00000000000;
  58. static const EVENT FLAG_OK = 0b00000000001;
  59. static const EVENT FLAG_PART_SHIFT = 1;
  60. static const EVENT FLAG_PART_MASK = 0b00000001110;
  61. static const EVENT FLAG_PART_UNKNOWN = 0b00000000000;
  62. static const EVENT FLAG_PART_POWER = 0b00000000010;
  63. static const EVENT FLAG_PART_COLOR = 0b00000000100;
  64. static const EVENT FLAG_PART_SLIDER = 0b00000001000;
  65. static const EVENT FLAG_TYPE_SHIFT = 4;
  66. static const EVENT FLAG_TYPE_MASK = 0b00000110000;
  67. static const EVENT FLAG_TYPE_UNKNOWN = 0b00000000000;
  68. static const EVENT FLAG_TYPE_TOUCH = 0b00000010000;
  69. static const EVENT FLAG_TYPE_RELEASE = 0b00000100000;
  70. static const EVENT FLAG_LEVEL_SHIFT = 6;
  71. static const EVENT FLAG_LEVEL_MASK = 0b11111000000;
  72. static const EVENT FLAG_LEVEL_UNKNOWN = 0b00000000000;
  73. // clang-format on
  74. /**
  75. * This class implements a parser that translates event byte codes from the
  76. * Xiaomi Mijia Bedside Lamp 2 into usable events.
  77. */
  78. class FrontPanelEventParser {
  79. public:
  80. /**
  81. * Parse the provided event byte code (7 bytes long).
  82. * Returns a unique integer event code that describes the parsed event.
  83. */
  84. EVENT parse(uint8_t *m) {
  85. EVENT ev = FLAG_INIT;
  86. // All events use the prefix [04:04:01:00].
  87. if (m[0] != 0x04 || m[1] != 0x04 || m[2] != 0x01 || m[3] != 0x00) {
  88. return error_(ev, m, "prefix is not 04:04:01:00");
  89. }
  90. // The next byte determines the part that is touched.
  91. // All remaining bytes specify the event for that part.
  92. switch (m[4]) {
  93. case 0x01: // power button
  94. case 0x02: // color button
  95. ev |= (m[4] == 0x01 ? FLAG_PART_POWER : FLAG_PART_COLOR);
  96. if (m[5] == 0x01 && m[6] == (0x02 + m[4]))
  97. ev |= FLAG_TYPE_TOUCH;
  98. else if (m[5] == 0x02 && m[6] == (0x03 + m[4]))
  99. ev |= FLAG_TYPE_RELEASE;
  100. else
  101. return error_(ev, m, "invalid event type for button");
  102. break;
  103. case 0x03: // slider touch
  104. case 0x04: // slider release
  105. ev |= FLAG_PART_SLIDER;
  106. ev |= (m[4] == 0x03 ? FLAG_TYPE_TOUCH : FLAG_TYPE_RELEASE);
  107. if ((m[6] - m[5] - m[4] - 0x01) != 0)
  108. return error_(ev, m, "invalid slider level crc");
  109. else if (m[5] > 0x16 || m[5] < 0x01)
  110. return error_(ev, m, "out of bounds slider value");
  111. else {
  112. auto level = 0x17 - m[5];
  113. ev |= (level << FLAG_LEVEL_SHIFT);
  114. }
  115. break;
  116. default:
  117. return error_(ev, m, "invalid part id");
  118. return ev;
  119. }
  120. // All parsing rules passed. This event is valid.
  121. ESP_LOGD(TAG, "Front panel I2C event parsed: code=%d", ev);
  122. ev |= FLAG_OK;
  123. return ev;
  124. }
  125. protected:
  126. bool has_(EVENT ev, EVENT mask, EVENT flag) { return (ev & mask) == flag; }
  127. EVENT error_(EVENT ev, uint8_t *m, const char *msg) {
  128. ESP_LOGE(TAG, "Front panel I2C event error:");
  129. ESP_LOGE(TAG, " Error: %s", msg);
  130. ESP_LOGE(TAG, " Event: [%02x:%02x:%02x:%02x:%02x:%02x:%02x]", m[0], m[1], m[2], m[3], m[4], m[5], m[6]);
  131. ESP_LOGE(TAG, " Parsed part: %s", format_part(ev));
  132. ESP_LOGE(TAG, " Parsed event type: %s", format_event_type(ev));
  133. if (has_(ev, FLAG_PART_MASK, FLAG_PART_SLIDER)) {
  134. auto level = (ev & FLAG_LEVEL_MASK) >> FLAG_LEVEL_SHIFT;
  135. if (level > 0) {
  136. ESP_LOGE(TAG, " Parsed slider level: %d", level);
  137. }
  138. }
  139. return ev;
  140. }
  141. const char *format_part(EVENT ev) {
  142. if (has_(ev, FLAG_PART_MASK, FLAG_PART_POWER))
  143. return "power button";
  144. if (has_(ev, FLAG_PART_MASK, FLAG_PART_COLOR))
  145. return "color button";
  146. if (has_(ev, FLAG_PART_MASK, FLAG_PART_SLIDER))
  147. return "slider";
  148. return "n/a";
  149. }
  150. const char *format_event_type(EVENT ev) {
  151. if (has_(ev, FLAG_TYPE_MASK, FLAG_TYPE_TOUCH))
  152. return "touch";
  153. if (has_(ev, FLAG_TYPE_MASK, FLAG_TYPE_RELEASE))
  154. return "release";
  155. return "n/a";
  156. }
  157. };
  158. /**
  159. * This is a hardware abstraction layer that communicates with with front
  160. * panel of the Xiaomi Mijia Bedside Lamp 2.
  161. *
  162. * It serves as a hub component for other components that implement
  163. * the actual buttons and slider components.
  164. */
  165. class FrontPanelHAL : public Component, public i2c::I2CDevice {
  166. public:
  167. FrontPanelEventParser event;
  168. /**
  169. * Set the GPIO pin that is used by the front panel to notify the ESP
  170. * that a touch/release event can be read using I2C.
  171. */
  172. void set_trigger_pin(GPIOPin *pin) { trigger_pin_ = pin; }
  173. void add_on_event_callback(std::function<void(EVENT)> &&callback) { event_callback_.add(std::move(callback)); }
  174. void setup() {
  175. ESP_LOGCONFIG(TAG, "Setting up I2C trigger pin interrupt...");
  176. trigger_pin_->setup();
  177. trigger_pin_->attach_interrupt(FrontPanelHAL::isr, this, FALLING);
  178. }
  179. void dump_config() {
  180. ESP_LOGCONFIG(TAG, "FrontPanelHAL:");
  181. LOG_PIN(" I2C interrupt pin: ", trigger_pin_);
  182. }
  183. void loop() {
  184. // Read and publish front panel events.
  185. auto current_event_id = event_id_;
  186. if (current_event_id != last_event_id_) {
  187. last_event_id_ = current_event_id;
  188. MSG message;
  189. if (write_bytes_raw(READY_FOR_EV, MSG_LEN) && read_bytes_raw(message, MSG_LEN)) {
  190. auto ev = event.parse(message);
  191. if (ev & FLAG_OK) {
  192. event_callback_.call(ev);
  193. }
  194. }
  195. }
  196. if (led_state_ != last_led_state_) {
  197. update_leds();
  198. }
  199. }
  200. /**
  201. * Turn on one or more LEDs (leaving the state of the other LEDs intact).
  202. * The input value is a bitwise OR-ed set of LED constants.
  203. * Only after a call to update_leds() (handled by default from the main loop),
  204. * the new state will be activated.
  205. */
  206. void turn_on_leds(uint16_t leds) {
  207. led_state_ = led_state_ | 0b0000110000000000 | leds;
  208. }
  209. /**
  210. * Turn off one or more LEDs (leaving the state of the other LEDs intact).
  211. * The input value is a bitwise OR-ed set of LED constants.
  212. * Only after a call to update_leds() (handled by default from the main loop),
  213. * the new state will be activated.
  214. */
  215. void turn_off_leds(uint16_t leds) {
  216. led_state_ = (led_state_ | 0b0000110000000000) & ~leds;
  217. }
  218. /**
  219. * Updates the state of the LEDs according to the provided input.
  220. * The input value is a bitwise OR-ed set of LED constants, representing the
  221. * LEDs that must be turned on. All other LEDs are turned off.
  222. * Only after a call to update_leds() (handled by default from the main loop),
  223. * the new state will be activated.
  224. */
  225. void set_leds(uint16_t leds) {
  226. turn_off_leds(LED_ALL);
  227. turn_on_leds(leds);
  228. }
  229. /**
  230. * Activate the LEDs according to the currently stored LED state. This method
  231. * will be called automatically by the main loop. You can call this method,
  232. * in case you need to update the LED state right away.
  233. */
  234. void update_leds() {
  235. led_msg_[2] = led_state_ >> 8;
  236. led_msg_[3] = led_state_ & 0xff;
  237. write_bytes_raw(led_msg_, MSG_LEN);
  238. last_led_state_ = led_state_;
  239. }
  240. /**
  241. * Sets the front panel illumination to the provided level (0.0 - 1.0).
  242. *
  243. * This implements the behavior of the original firmware for representing
  244. * the lamp's brightness.
  245. *
  246. * Level 0.0 means: turn off the front panel illumination.
  247. * The other levels are translated to one of the available levels,
  248. * represented by the level indicator (i.e. the illumination of the
  249. * slider bar.) The power and color button are also turned on.
  250. */
  251. void set_light_level(float level) {
  252. turn_off_leds(LED_ALL);
  253. if (level == 0.00f) return;
  254. turn_on_leds(LED_POWER | LED_COLOR | LED_1);
  255. if (level >= 0.15f) turn_on_leds(LED_2);
  256. if (level >= 0.25f) turn_on_leds(LED_3);
  257. if (level >= 0.35f) turn_on_leds(LED_4);
  258. if (level >= 0.45f) turn_on_leds(LED_5);
  259. if (level >= 0.55f) turn_on_leds(LED_6);
  260. if (level >= 0.65f) turn_on_leds(LED_7);
  261. if (level >= 0.75f) turn_on_leds(LED_8);
  262. if (level >= 0.85f) turn_on_leds(LED_9);
  263. if (level >= 0.95f) turn_on_leds(LED_10);
  264. }
  265. protected:
  266. GPIOPin *trigger_pin_;
  267. static void isr(FrontPanelHAL *store);
  268. volatile int event_id_ = 0;
  269. int last_event_id_ = 0;
  270. CallbackManager<void(EVENT)> event_callback_{};
  271. uint16_t led_state_ = 0;
  272. uint16_t last_led_state_ = 0;
  273. MSG led_msg_ = {0x02, 0x03, 0x00, 0x00, 0x64, 0x00, 0x00};
  274. };
  275. /**
  276. * This ISR is used to handle IRQ triggers from the front panel.
  277. *
  278. * The front panel pulls the trigger pin low for a short period of time
  279. * when a new event is available. All we do here to handle the interrupt,
  280. * is increment a simple event id counter. The main loop of the component
  281. * will take care of actually reading and processing the event.
  282. */
  283. void ICACHE_RAM_ATTR HOT FrontPanelHAL::isr(FrontPanelHAL *store) { store->event_id_++; }
  284. } // namespace bslamp2
  285. } // namespace xiaomi
  286. } // namespace esphome