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.

61 lines
2.3 KiB

  1. #pragma once
  2. #include <array>
  3. #include <stdexcept>
  4. namespace esphome {
  5. namespace rgbww {
  6. namespace yeelight_bs2 {
  7. class RGBLight
  8. {
  9. public:
  10. float red = 0;
  11. float green = 0;
  12. float blue = 0;
  13. float white = 0;
  14. void set_color(float red, float green, float blue, float brightness, float state)
  15. {
  16. // Overall, the RGB colors are very usable when simply scaling the
  17. // RGB channels with the brightness, but around the white point,
  18. // the color is a bit on the red side of the spectrum. The following
  19. // scaling was created to fix that.
  20. // These functions were created, based on actual measurements while
  21. // using the original firmware.
  22. auto b = brightness * 100.0f;
  23. auto red_w = 1.00f - (-0.0000121426 * b * b - 0.147576 * b + 93.2335) / 100.0f;
  24. auto green_w = 1.00f - (-0.0000242425 * b * b - 0.340449 * b + 88.4423) / 100.0f;
  25. auto blue_w = 1.00f - (-0.0000085869 * b * b - 0.109649 * b + 94.2026) / 100.0f;
  26. // For colors that are not around the white point, we can scale the
  27. // RGB channels with the requested brightness, resulting in a very
  28. // usable color. Not 100% the same as the original firmware, but
  29. // sometimes even better IMO.
  30. auto red_c = red * brightness;
  31. auto green_c = green * brightness;
  32. auto blue_c = blue * brightness;
  33. // The actual RGB values are a weighed mix of the above two.
  34. // The closer to the white point, the more the white point
  35. // value applies.
  36. auto level_red = (red_w * ((green+blue)/2)) + (red_c * (1-(green+blue)/2));
  37. auto level_green = (green_w * ((red+blue)/2)) + (green_c * (1-(red+blue)/2));
  38. auto level_blue = (blue_w * ((red+green)/2)) + (blue_c * (1-(red+green)/2));
  39. if (red == 1 && green == 1 && blue == 1) {
  40. level_red = red_w;
  41. level_green = green_w;
  42. level_blue = blue_w;
  43. }
  44. // Invert the signal. The LEDs in the lamp's circuit are brighter
  45. // when the pwm levels on the GPIO pins are lower.
  46. this->red = 1.0f - level_red;
  47. this->green = 1.0f - level_green;
  48. this->blue = 1.0f - level_blue;
  49. }
  50. };
  51. } // namespace yeelight_bs2
  52. } // namespace rgbww
  53. } // namespace esphome