RgbwPacketFormatter.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #include <RgbwPacketFormatter.h>
  2. #include <MiLightButtons.h>
  3. void RgbwPacketFormatter::initializePacket(uint8_t* packet) {
  4. size_t packetPtr = 0;
  5. packet[packetPtr++] = RGBW;
  6. packet[packetPtr++] = deviceId >> 8;
  7. packet[packetPtr++] = deviceId & 0xFF;
  8. packet[packetPtr++] = 0;
  9. packet[packetPtr++] = (groupId & 0x07);
  10. packet[packetPtr++] = 0;
  11. packet[packetPtr++] = sequenceNum++;
  12. }
  13. void RgbwPacketFormatter::unpair() {
  14. PacketFormatter::updateStatus(ON);
  15. updateColorWhite();
  16. }
  17. void RgbwPacketFormatter::modeSpeedDown() {
  18. command(RGBW_SPEED_DOWN, 0);
  19. }
  20. void RgbwPacketFormatter::modeSpeedUp() {
  21. command(RGBW_SPEED_UP, 0);
  22. }
  23. void RgbwPacketFormatter::nextMode() {
  24. command(RGBW_DISCO_MODE, 0);
  25. }
  26. void RgbwPacketFormatter::updateMode(uint8_t mode) {
  27. command(RGBW_DISCO_MODE, 0);
  28. currentPacket[0] = RGBW | mode;
  29. }
  30. void RgbwPacketFormatter::updateStatus(MiLightStatus status, uint8_t groupId) {
  31. uint8_t button = RGBW_GROUP_1_ON + ((groupId - 1)*2) + status;
  32. command(button, 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::format(uint8_t const* packet, char* buffer) {
  65. PacketFormatter::formatV1Packet(packet, buffer);
  66. }