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.

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