MiLightUdpServer.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include <MiLightUdpServer.h>
  2. MiLightUdpServer::MiLightUdpServer(MiLightClient*& client, uint16_t port, uint16_t deviceId)
  3. : client(client),
  4. port(port),
  5. deviceId(deviceId),
  6. lastGroup(0)
  7. { }
  8. MiLightUdpServer::~MiLightUdpServer() {
  9. stop();
  10. }
  11. void MiLightUdpServer::begin() {
  12. socket.begin(this->port);
  13. }
  14. void MiLightUdpServer::stop() {
  15. socket.stop();
  16. }
  17. void MiLightUdpServer::handleClient() {
  18. const size_t packetSize = socket.parsePacket();
  19. if (packetSize) {
  20. if (packetSize == 3) {
  21. socket.read(packetBuffer, packetSize);
  22. handleCommand(packetBuffer[0], packetBuffer[1]);
  23. } else {
  24. Serial.print("Error, unexpected packet length (should always be 3, was: ");
  25. Serial.println(packetSize);
  26. }
  27. }
  28. }
  29. void MiLightUdpServer::handleCommand(uint8_t command, uint8_t commandArg) {
  30. if (command >= UDP_GROUP_1_ON && command <= UDP_GROUP_4_OFF) {
  31. const MiLightStatus status = (command % 2) == 1 ? ON : OFF;
  32. const uint8_t groupId = (command - UDP_GROUP_1_ON + 2)/2;
  33. client->updateStatus(deviceId, groupId, status);
  34. this->lastGroup = groupId;
  35. } else if (command >= UDP_GROUP_ALL_WHITE && command <= UDP_GROUP_4_WHITE) {
  36. const uint8_t groupId = (command - UDP_GROUP_ALL_WHITE)/2;
  37. client->updateColorWhite(deviceId, groupId);
  38. this->lastGroup = groupId;
  39. } else {
  40. // Group on/off
  41. switch (command) {
  42. case UDP_ALL_ON:
  43. client->allOn(deviceId);
  44. break;
  45. case UDP_ALL_OFF:
  46. client->allOff(deviceId);
  47. break;
  48. case UDP_COLOR:
  49. client->updateColorRaw(deviceId, this->lastGroup, commandArg);
  50. break;
  51. case UDP_DISCO_MODE:
  52. pressButton(this->lastGroup, DISCO_MODE);
  53. break;
  54. case UDP_SPEED_DOWN:
  55. pressButton(this->lastGroup, SPEED_DOWN);
  56. break;
  57. case UDP_SPEED_UP:
  58. pressButton(this->lastGroup, SPEED_UP);
  59. break;
  60. case UDP_BRIGHTNESS:
  61. // map [2, 27] --> [0, 100]
  62. client->updateBrightness(
  63. deviceId,
  64. this->lastGroup,
  65. round(((commandArg - 2) / 25.0)*100)
  66. );
  67. break;
  68. default:
  69. Serial.print("MiLightUdpServer - Unhandled command: ");
  70. Serial.println(command);
  71. }
  72. }
  73. }
  74. void MiLightUdpServer::pressButton(uint8_t group, MiLightButton button) {
  75. client->write(deviceId, 0, 0, group, button);
  76. }