RgbwPacketFormatter.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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::updateStatus(MiLightStatus status, uint8_t groupId) {
  14. uint8_t button = RGBW_GROUP_1_ON + ((groupId - 1)*2) + status;
  15. command(button, 0);
  16. }
  17. void RgbwPacketFormatter::updateBrightness(uint8_t value) {
  18. // Expect an input value in [0, 100]. Map it down to [0, 25].
  19. const uint8_t adjustedBrightness = rescale(value, 25, 100);
  20. // The actual protocol uses a bizarre range where min is 16, max is 23:
  21. // [16, 15, ..., 0, 31, ..., 23]
  22. const uint8_t packetBrightnessValue = (
  23. ((31 - adjustedBrightness) + 17) % 32
  24. );
  25. command(RGBW_BRIGHTNESS, 0);
  26. currentPacket[RGBW_BRIGHTNESS_GROUP_INDEX] |= (packetBrightnessValue << 3);
  27. }
  28. void RgbwPacketFormatter::command(uint8_t command, uint8_t arg) {
  29. pushPacket();
  30. currentPacket[RGBW_COMMAND_INDEX] = command;
  31. }
  32. void RgbwPacketFormatter::updateHue(uint16_t value) {
  33. const int16_t remappedColor = (value + 40) % 360;
  34. updateColorRaw(rescale(remappedColor, 255, 360));
  35. }
  36. void RgbwPacketFormatter::updateColorRaw(uint8_t value) {
  37. currentPacket[RGBW_COLOR_INDEX] = value;
  38. command(RGBW_COLOR, 0);
  39. }
  40. void RgbwPacketFormatter::updateColorWhite() {
  41. uint8_t button = RGBW_GROUP_1_MAX_LEVEL + ((groupId - 1)*2);
  42. command(button, 0);
  43. }
  44. void RgbwPacketFormatter::format(uint8_t const* packet, char* buffer) {
  45. PacketFormatter::formatV1Packet(packet, buffer);
  46. }