MiLightUdpServer.cpp 2.3 KB

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