RgbwPacketFormatter.cpp 1.8 KB

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