main.cpp 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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. #include <LEDStatus.h>
  23. WiFiManager wifiManager;
  24. static LEDStatus *ledStatus;
  25. Settings settings;
  26. MiLightClient* milightClient = NULL;
  27. MiLightRadioFactory* radioFactory = NULL;
  28. MiLightHttpServer *httpServer = NULL;
  29. MqttClient* mqttClient = NULL;
  30. MiLightDiscoveryServer* discoveryServer = NULL;
  31. uint8_t currentRadioType = 0;
  32. // For tracking and managing group state
  33. GroupStateStore* stateStore = NULL;
  34. BulbStateUpdater* bulbStateUpdater = NULL;
  35. int numUdpServers = 0;
  36. MiLightUdpServer** udpServers = NULL;
  37. WiFiUDP udpSeder;
  38. /**
  39. * Set up UDP servers (both v5 and v6). Clean up old ones if necessary.
  40. */
  41. void initMilightUdpServers() {
  42. if (udpServers) {
  43. for (int i = 0; i < numUdpServers; i++) {
  44. if (udpServers[i]) {
  45. delete udpServers[i];
  46. }
  47. }
  48. delete udpServers;
  49. }
  50. udpServers = new MiLightUdpServer*[settings.numGatewayConfigs];
  51. numUdpServers = settings.numGatewayConfigs;
  52. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  53. GatewayConfig* config = settings.gatewayConfigs[i];
  54. MiLightUdpServer* server = MiLightUdpServer::fromVersion(
  55. config->protocolVersion,
  56. milightClient,
  57. config->port,
  58. config->deviceId
  59. );
  60. if (server == NULL) {
  61. Serial.print(F("Error creating UDP server with protocol version: "));
  62. Serial.println(config->protocolVersion);
  63. } else {
  64. udpServers[i] = server;
  65. udpServers[i]->begin();
  66. }
  67. }
  68. }
  69. /**
  70. * Milight RF packet handler.
  71. *
  72. * Called both when a packet is sent locally, and when an intercepted packet
  73. * is read.
  74. */
  75. void onPacketSentHandler(uint8_t* packet, const MiLightRemoteConfig& config) {
  76. StaticJsonBuffer<200> buffer;
  77. JsonObject& result = buffer.createObject();
  78. BulbId bulbId = config.packetFormatter->parsePacket(packet, result);
  79. // set LED mode for a packet movement
  80. ledStatus->oneshot(settings.ledModePacket, settings.ledModePacketCount);
  81. if (&bulbId == &DEFAULT_BULB_ID) {
  82. Serial.println(F("Skipping packet handler because packet was not decoded"));
  83. return;
  84. }
  85. const MiLightRemoteConfig& remoteConfig =
  86. *MiLightRemoteConfig::fromType(bulbId.deviceType);
  87. // update state to reflect changes from this packet
  88. GroupState& groupState = stateStore->get(bulbId);
  89. groupState.patch(result);
  90. stateStore->set(bulbId, groupState);
  91. if (mqttClient) {
  92. // Sends the state delta derived from the raw packet
  93. char output[200];
  94. result.printTo(output);
  95. mqttClient->sendUpdate(remoteConfig, bulbId.deviceId, bulbId.groupId, output);
  96. // Sends the entire state
  97. bulbStateUpdater->enqueueUpdate(bulbId, groupState);
  98. }
  99. httpServer->handlePacketSent(packet, remoteConfig);
  100. }
  101. /**
  102. * Listen for packets on one radio config. Cycles through all configs as its
  103. * called.
  104. */
  105. void handleListen() {
  106. if (! settings.listenRepeats) {
  107. return;
  108. }
  109. MiLightRadio* radio = milightClient->switchRadio(currentRadioType++ % milightClient->getNumRadios());
  110. for (size_t i = 0; i < settings.listenRepeats; i++) {
  111. if (milightClient->available()) {
  112. uint8_t readPacket[MILIGHT_MAX_PACKET_LENGTH];
  113. size_t packetLen = milightClient->read(readPacket);
  114. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  115. radio->config(),
  116. readPacket,
  117. packetLen
  118. );
  119. if (remoteConfig == NULL) {
  120. // This can happen under normal circumstances, so not an error condition
  121. #ifdef DEBUG_PRINTF
  122. Serial.println(F("WARNING: Couldn't find remote for received packet"));
  123. #endif
  124. return;
  125. }
  126. // update state to reflect this packet
  127. onPacketSentHandler(readPacket, *remoteConfig);
  128. }
  129. }
  130. }
  131. /**
  132. * Called when MqttClient#update is first being processed. Stop sending updates
  133. * and aggregate state changes until the update is finished.
  134. */
  135. void onUpdateBegin() {
  136. if (bulbStateUpdater) {
  137. bulbStateUpdater->disable();
  138. }
  139. }
  140. /**
  141. * Called when MqttClient#update is finished processing. Re-enable state
  142. * updates, which will flush accumulated state changes.
  143. */
  144. void onUpdateEnd() {
  145. if (bulbStateUpdater) {
  146. bulbStateUpdater->enable();
  147. }
  148. }
  149. /**
  150. * Apply what's in the Settings object.
  151. */
  152. void applySettings() {
  153. if (milightClient) {
  154. delete milightClient;
  155. }
  156. if (radioFactory) {
  157. delete radioFactory;
  158. }
  159. if (mqttClient) {
  160. delete mqttClient;
  161. delete bulbStateUpdater;
  162. mqttClient = NULL;
  163. bulbStateUpdater = NULL;
  164. }
  165. if (stateStore) {
  166. delete stateStore;
  167. }
  168. radioFactory = MiLightRadioFactory::fromSettings(settings);
  169. if (radioFactory == NULL) {
  170. Serial.println(F("ERROR: unable to construct radio factory"));
  171. }
  172. stateStore = new GroupStateStore(MILIGHT_MAX_STATE_ITEMS, settings.stateFlushInterval);
  173. milightClient = new MiLightClient(
  174. radioFactory,
  175. stateStore,
  176. &settings
  177. );
  178. milightClient->begin();
  179. milightClient->onPacketSent(onPacketSentHandler);
  180. milightClient->onUpdateBegin(onUpdateBegin);
  181. milightClient->onUpdateEnd(onUpdateEnd);
  182. milightClient->setResendCount(settings.packetRepeats);
  183. if (settings.mqttServer().length() > 0) {
  184. mqttClient = new MqttClient(settings, milightClient);
  185. mqttClient->begin();
  186. bulbStateUpdater = new BulbStateUpdater(settings, *mqttClient, *stateStore);
  187. }
  188. initMilightUdpServers();
  189. if (discoveryServer) {
  190. delete discoveryServer;
  191. discoveryServer = NULL;
  192. }
  193. if (settings.discoveryPort != 0) {
  194. discoveryServer = new MiLightDiscoveryServer(settings);
  195. discoveryServer->begin();
  196. }
  197. // update LED pin and operating mode
  198. if (ledStatus) {
  199. ledStatus->changePin(settings.ledPin);
  200. ledStatus->continuous(settings.ledModeOperating);
  201. }
  202. }
  203. /**
  204. *
  205. */
  206. bool shouldRestart() {
  207. if (! settings.isAutoRestartEnabled()) {
  208. return false;
  209. }
  210. return settings.getAutoRestartPeriod()*60*1000 < millis();
  211. }
  212. // give a bit of time to update the status LED
  213. void handleLED() {
  214. ledStatus->handle();
  215. }
  216. void setup() {
  217. Serial.begin(9600);
  218. String ssid = "ESP" + String(ESP.getChipId());
  219. // load up our persistent settings from the file system
  220. SPIFFS.begin();
  221. Settings::load(settings);
  222. applySettings();
  223. // set up the LED status for wifi configuration
  224. ledStatus = new LEDStatus(settings.ledPin);
  225. ledStatus->continuous(settings.ledModeWifiConfig);
  226. // start up the wifi manager
  227. if (! MDNS.begin("milight-hub")) {
  228. Serial.println(F("Error setting up MDNS responder"));
  229. }
  230. // tell Wifi manager to call us during the setup. Note that this "setSetupLoopCallback" is an addition
  231. // made to Wifi manager in a private fork. As of this writing, WifiManager has a new feature coming that
  232. // allows the "autoConnect" method to be non-blocking which can implement this same functionality. However,
  233. // that change is only on the development branch so we are going to continue to use this fork until
  234. // that is merged and ready.
  235. wifiManager.setSetupLoopCallback(handleLED);
  236. wifiManager.setConfigPortalTimeout(180);
  237. if (wifiManager.autoConnect(ssid.c_str(), "milightHub")) {
  238. // set LED mode for successful operation
  239. ledStatus->continuous(settings.ledModeOperating);
  240. Serial.println(F("Wifi connected succesfully\n"));
  241. // if the config portal was started, make sure to turn off the config AP
  242. WiFi.mode(WIFI_STA);
  243. } else {
  244. // set LED mode for Wifi failed
  245. ledStatus->continuous(settings.ledModeWifiFailed);
  246. Serial.println(F("Wifi failed. Restarting in 10 seconds.\n"));
  247. delay(10000);
  248. ESP.restart();
  249. }
  250. MDNS.addService("http", "tcp", 80);
  251. SSDP.setSchemaURL("description.xml");
  252. SSDP.setHTTPPort(80);
  253. SSDP.setName("ESP8266 MiLight Gateway");
  254. SSDP.setSerialNumber(ESP.getChipId());
  255. SSDP.setURL("/");
  256. SSDP.setDeviceType("upnp:rootdevice");
  257. SSDP.begin();
  258. httpServer = new MiLightHttpServer(settings, milightClient, stateStore);
  259. httpServer->onSettingsSaved(applySettings);
  260. httpServer->on("/description.xml", HTTP_GET, []() { SSDP.schema(httpServer->client()); });
  261. httpServer->begin();
  262. Serial.printf_P(PSTR("Setup complete (version %s)\n"), QUOTE(MILIGHT_HUB_VERSION));
  263. }
  264. void loop() {
  265. httpServer->handleClient();
  266. if (mqttClient) {
  267. mqttClient->handleClient();
  268. bulbStateUpdater->loop();
  269. }
  270. if (udpServers) {
  271. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  272. udpServers[i]->handleClient();
  273. }
  274. }
  275. if (discoveryServer) {
  276. discoveryServer->handleClient();
  277. }
  278. handleListen();
  279. stateStore->limitedFlush();
  280. // update LED with status
  281. ledStatus->handle();
  282. if (shouldRestart()) {
  283. Serial.println(F("Auto-restart triggered. Restarting..."));
  284. ESP.restart();
  285. }
  286. }