RgbwPacketFormatter.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. #include <RgbwPacketFormatter.h>
  2. #include <MiLightButtons.h>
  3. #define STATUS_COMMAND(status, groupId) ( RGBW_GROUP_1_ON + ((groupId - 1)*2) + status )
  4. void RgbwPacketFormatter::initializePacket(uint8_t* packet) {
  5. size_t packetPtr = 0;
  6. packet[packetPtr++] = RGBW;
  7. packet[packetPtr++] = deviceId >> 8;
  8. packet[packetPtr++] = deviceId & 0xFF;
  9. packet[packetPtr++] = 0;
  10. packet[packetPtr++] = (groupId & 0x07);
  11. packet[packetPtr++] = 0;
  12. packet[packetPtr++] = sequenceNum++;
  13. }
  14. void RgbwPacketFormatter::unpair() {
  15. PacketFormatter::updateStatus(ON);
  16. updateColorWhite();
  17. }
  18. void RgbwPacketFormatter::modeSpeedDown() {
  19. command(RGBW_SPEED_DOWN, 0);
  20. }
  21. void RgbwPacketFormatter::modeSpeedUp() {
  22. command(RGBW_SPEED_UP, 0);
  23. }
  24. void RgbwPacketFormatter::nextMode() {
  25. command(RGBW_DISCO_MODE, 0);
  26. }
  27. void RgbwPacketFormatter::updateMode(uint8_t mode) {
  28. command(RGBW_DISCO_MODE, 0);
  29. currentPacket[0] = RGBW | mode;
  30. }
  31. void RgbwPacketFormatter::updateStatus(MiLightStatus status, uint8_t groupId) {
  32. command(STATUS_COMMAND(status, groupId), 0);
  33. }
  34. void RgbwPacketFormatter::updateBrightness(uint8_t value) {
  35. // Expect an input value in [0, 100]. Map it down to [0, 25].
  36. const uint8_t adjustedBrightness = rescale(value, 25, 100);
  37. // The actual protocol uses a bizarre range where min is 16, max is 23:
  38. // [16, 15, ..., 0, 31, ..., 23]
  39. const uint8_t packetBrightnessValue = (
  40. ((31 - adjustedBrightness) + 17) % 32
  41. );
  42. command(RGBW_BRIGHTNESS, 0);
  43. currentPacket[RGBW_BRIGHTNESS_GROUP_INDEX] |= (packetBrightnessValue << 3);
  44. }
  45. void RgbwPacketFormatter::command(uint8_t command, uint8_t arg) {
  46. pushPacket();
  47. if (held) {
  48. command |= 0x80;
  49. }
  50. currentPacket[RGBW_COMMAND_INDEX] = command;
  51. }
  52. void RgbwPacketFormatter::updateHue(uint16_t value) {
  53. const int16_t remappedColor = (value + 40) % 360;
  54. updateColorRaw(rescale(remappedColor, 255, 360));
  55. }
  56. void RgbwPacketFormatter::updateColorRaw(uint8_t value) {
  57. command(RGBW_COLOR, 0);
  58. currentPacket[RGBW_COLOR_INDEX] = value;
  59. }
  60. void RgbwPacketFormatter::updateColorWhite() {
  61. uint8_t button = RGBW_GROUP_1_MAX_LEVEL + ((groupId - 1)*2);
  62. command(button, 0);
  63. }
  64. void RgbwPacketFormatter::enableNightMode() {
  65. uint8_t button = STATUS_COMMAND(ON, groupId);
  66. command(button, 0);
  67. command(button | 0x10, 0);
  68. }
  69. void RgbwPacketFormatter::format(uint8_t const* packet, char* buffer) {
  70. PacketFormatter::formatV1Packet(packet, buffer);
  71. }