main.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. #include <SPI.h>
  2. #include <WiFiManager.h>
  3. #include <ArduinoJson.h>
  4. #include <stdlib.h>
  5. #include <FS.h>
  6. #include <IntParsing.h>
  7. #include <Size.h>
  8. #include <LinkedList.h>
  9. #include <GroupStateStore.h>
  10. #include <MiLightRadioConfig.h>
  11. #include <MiLightRemoteConfig.h>
  12. #include <MiLightHttpServer.h>
  13. #include <Settings.h>
  14. #include <MiLightUdpServer.h>
  15. #include <ESP8266mDNS.h>
  16. #include <ESP8266SSDP.h>
  17. #include <MqttClient.h>
  18. #include <RGBConverter.h>
  19. #include <MiLightDiscoveryServer.h>
  20. #include <MiLightClient.h>
  21. #include <BulbStateUpdater.h>
  22. WiFiManager wifiManager;
  23. Settings settings;
  24. MiLightClient* milightClient = NULL;
  25. MiLightRadioFactory* radioFactory = NULL;
  26. MiLightHttpServer *httpServer = NULL;
  27. MqttClient* mqttClient = NULL;
  28. MiLightDiscoveryServer* discoveryServer = NULL;
  29. uint8_t currentRadioType = 0;
  30. // For tracking and managing group state
  31. GroupStateStore* stateStore = NULL;
  32. BulbStateUpdater* bulbStateUpdater = NULL;
  33. int numUdpServers = 0;
  34. MiLightUdpServer** udpServers = NULL;
  35. WiFiUDP udpSeder;
  36. /**
  37. * Set up UDP servers (both v5 and v6). Clean up old ones if necessary.
  38. */
  39. void initMilightUdpServers() {
  40. if (udpServers) {
  41. for (int i = 0; i < numUdpServers; i++) {
  42. if (udpServers[i]) {
  43. delete udpServers[i];
  44. }
  45. }
  46. delete udpServers;
  47. }
  48. udpServers = new MiLightUdpServer*[settings.numGatewayConfigs];
  49. numUdpServers = settings.numGatewayConfigs;
  50. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  51. GatewayConfig* config = settings.gatewayConfigs[i];
  52. MiLightUdpServer* server = MiLightUdpServer::fromVersion(
  53. config->protocolVersion,
  54. milightClient,
  55. config->port,
  56. config->deviceId
  57. );
  58. if (server == NULL) {
  59. Serial.print(F("Error creating UDP server with protocol version: "));
  60. Serial.println(config->protocolVersion);
  61. } else {
  62. udpServers[i] = server;
  63. udpServers[i]->begin();
  64. }
  65. }
  66. }
  67. /**
  68. * Milight RF packet handler.
  69. *
  70. * Called both when a packet is sent locally, and when an intercepted packet
  71. * is read.
  72. */
  73. void onPacketSentHandler(uint8_t* packet, const MiLightRemoteConfig& config) {
  74. StaticJsonBuffer<200> buffer;
  75. JsonObject& result = buffer.createObject();
  76. BulbId bulbId = config.packetFormatter->parsePacket(packet, result, stateStore);
  77. if (&bulbId == &DEFAULT_BULB_ID) {
  78. Serial.println(F("Skipping packet handler because packet was not decoded"));
  79. return;
  80. }
  81. const MiLightRemoteConfig& remoteConfig =
  82. *MiLightRemoteConfig::fromType(bulbId.deviceType);
  83. GroupState& groupState = stateStore->get(bulbId);
  84. groupState.patch(result);
  85. stateStore->set(bulbId, groupState);
  86. if (mqttClient) {
  87. // Sends the state delta derived from the raw packet
  88. char output[200];
  89. result.printTo(output);
  90. mqttClient->sendUpdate(remoteConfig, bulbId.deviceId, bulbId.groupId, output);
  91. // Sends the entire state
  92. bulbStateUpdater->enqueueUpdate(bulbId, groupState);
  93. }
  94. httpServer->handlePacketSent(packet, remoteConfig);
  95. }
  96. /**
  97. * Listen for packets on one radio config. Cycles through all configs as its
  98. * called.
  99. */
  100. void handleListen() {
  101. if (! settings.listenRepeats) {
  102. return;
  103. }
  104. MiLightRadio* radio = milightClient->switchRadio(currentRadioType++ % milightClient->getNumRadios());
  105. for (size_t i = 0; i < settings.listenRepeats; i++) {
  106. if (milightClient->available()) {
  107. uint8_t readPacket[MILIGHT_MAX_PACKET_LENGTH];
  108. size_t packetLen = milightClient->read(readPacket);
  109. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  110. radio->config(),
  111. readPacket,
  112. packetLen
  113. );
  114. if (remoteConfig == NULL) {
  115. // This can happen under normal circumstances, so not an error condition
  116. #ifdef DEBUG_PRINTF
  117. Serial.println(F("WARNING: Couldn't find remote for received packet"));
  118. #endif
  119. return;
  120. }
  121. onPacketSentHandler(readPacket, *remoteConfig);
  122. }
  123. }
  124. }
  125. /**
  126. * Apply what's in the Settings object.
  127. */
  128. void applySettings() {
  129. if (milightClient) {
  130. delete milightClient;
  131. }
  132. if (radioFactory) {
  133. delete radioFactory;
  134. }
  135. if (mqttClient) {
  136. delete mqttClient;
  137. delete bulbStateUpdater;
  138. }
  139. if (stateStore) {
  140. delete stateStore;
  141. }
  142. radioFactory = MiLightRadioFactory::fromSettings(settings);
  143. if (radioFactory == NULL) {
  144. Serial.println(F("ERROR: unable to construct radio factory"));
  145. }
  146. stateStore = new GroupStateStore(MILIGHT_MAX_STATE_ITEMS, settings.stateFlushInterval);
  147. milightClient = new MiLightClient(
  148. radioFactory,
  149. *stateStore,
  150. settings.packetRepeatThrottleThreshold,
  151. settings.packetRepeatThrottleSensitivity,
  152. settings.packetRepeatMinimum
  153. );
  154. milightClient->begin();
  155. milightClient->onPacketSent(onPacketSentHandler);
  156. milightClient->setResendCount(settings.packetRepeats);
  157. if (settings.mqttServer().length() > 0) {
  158. mqttClient = new MqttClient(settings, milightClient);
  159. mqttClient->begin();
  160. bulbStateUpdater = new BulbStateUpdater(settings, *mqttClient, *stateStore);
  161. }
  162. initMilightUdpServers();
  163. if (discoveryServer) {
  164. delete discoveryServer;
  165. discoveryServer = NULL;
  166. }
  167. if (settings.discoveryPort != 0) {
  168. discoveryServer = new MiLightDiscoveryServer(settings);
  169. discoveryServer->begin();
  170. }
  171. }
  172. /**
  173. *
  174. */
  175. bool shouldRestart() {
  176. if (! settings.isAutoRestartEnabled()) {
  177. return false;
  178. }
  179. return settings.getAutoRestartPeriod()*60*1000 < millis();
  180. }
  181. void setup() {
  182. Serial.begin(9600);
  183. String ssid = "ESP" + String(ESP.getChipId());
  184. wifiManager.setConfigPortalTimeout(180);
  185. wifiManager.autoConnect(ssid.c_str(), "milightHub");
  186. SPIFFS.begin();
  187. Settings::load(settings);
  188. applySettings();
  189. if (! MDNS.begin("milight-hub")) {
  190. Serial.println(F("Error setting up MDNS responder"));
  191. }
  192. MDNS.addService("http", "tcp", 80);
  193. SSDP.setSchemaURL("description.xml");
  194. SSDP.setHTTPPort(80);
  195. SSDP.setName("ESP8266 MiLight Gateway");
  196. SSDP.setSerialNumber(ESP.getChipId());
  197. SSDP.setURL("/");
  198. SSDP.setDeviceType("upnp:rootdevice");
  199. SSDP.begin();
  200. httpServer = new MiLightHttpServer(settings, milightClient, stateStore);
  201. httpServer->onSettingsSaved(applySettings);
  202. httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); });
  203. httpServer->begin();
  204. Serial.println(F("Setup complete"));
  205. }
  206. void loop() {
  207. httpServer->handleClient();
  208. if (mqttClient) {
  209. mqttClient->handleClient();
  210. bulbStateUpdater->loop();
  211. }
  212. if (udpServers) {
  213. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  214. udpServers[i]->handleClient();
  215. }
  216. }
  217. if (discoveryServer) {
  218. discoveryServer->handleClient();
  219. }
  220. handleListen();
  221. stateStore->limitedFlush();
  222. if (shouldRestart()) {
  223. Serial.println(F("Auto-restart triggered. Restarting..."));
  224. ESP.restart();
  225. }
  226. }