MiLightHttpServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. #include <FS.h>
  2. #include <WiFiUdp.h>
  3. #include <IntParsing.h>
  4. #include <Settings.h>
  5. #include <MiLightHttpServer.h>
  6. #include <MiLightRadioConfig.h>
  7. #include <string.h>
  8. #include <TokenIterator.h>
  9. #include <index.html.gz.h>
  10. void MiLightHttpServer::begin() {
  11. applySettings(settings);
  12. // set up HTTP end points to serve
  13. _handleRootPage = handleServe_P(index_html_gz, index_html_gz_len);
  14. server.onAuthenticated("/", HTTP_GET, [this]() { _handleRootPage(); });
  15. server.onAuthenticated("/settings", HTTP_GET, [this]() { serveSettings(); });
  16. server.onAuthenticated("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  17. server.onAuthenticated("/settings", HTTP_POST, [this]() { handleUpdateSettingsPost(); }, handleUpdateFile(SETTINGS_FILE));
  18. server.onAuthenticated("/radio_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  19. server.onAuthenticated("/gateway_traffic", HTTP_GET, [this]() { handleListenGateway(NULL); });
  20. server.onPatternAuthenticated("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  21. const char groupPattern[] = "/gateways/:device_id/:type/:group_id";
  22. server.onPatternAuthenticated(groupPattern, HTTP_PUT, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  23. server.onPatternAuthenticated(groupPattern, HTTP_POST, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  24. server.onPatternAuthenticated(groupPattern, HTTP_GET, [this](const UrlTokenBindings* b) { handleGetGroup(b); });
  25. server.onPatternAuthenticated("/raw_commands/:type", HTTP_ANY, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  26. server.onAuthenticated("/web", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success")); }, handleUpdateFile(WEB_INDEX_FILENAME));
  27. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  28. server.onAuthenticated("/system", HTTP_POST, [this]() { handleSystemPost(); });
  29. server.onAuthenticated("/firmware", HTTP_POST, [this]() { handleFirmwarePost(); }, [this]() { handleFirmwareUpload(); });
  30. // set up web socket server
  31. wsServer.onEvent(
  32. [this](uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  33. handleWsEvent(num, type, payload, length);
  34. }
  35. );
  36. wsServer.begin();
  37. server.begin();
  38. }
  39. void MiLightHttpServer::handleClient() {
  40. server.handleClient();
  41. wsServer.loop();
  42. }
  43. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  44. server.on(path, method, handler);
  45. }
  46. WiFiClient MiLightHttpServer::client() {
  47. return server.client();
  48. }
  49. void MiLightHttpServer::handleSystemPost() {
  50. DynamicJsonBuffer buffer;
  51. JsonObject& request = buffer.parse(server.arg("plain"));
  52. bool handled = false;
  53. if (request.containsKey("command")) {
  54. if (request["command"] == "restart") {
  55. Serial.println(F("Restarting..."));
  56. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  57. delay(100);
  58. ESP.restart();
  59. handled = true;
  60. } else if (request["command"] == "clear_wifi_config") {
  61. Serial.println(F("Resetting Wifi and then Restarting..."));
  62. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  63. delay(100);
  64. ESP.eraseConfig();
  65. delay(100);
  66. ESP.restart();
  67. handled = true;
  68. }
  69. }
  70. if (handled) {
  71. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  72. } else {
  73. server.send_P(400, TEXT_PLAIN, PSTR("{\"error\":\"Unhandled command\"}"));
  74. }
  75. }
  76. void MiLightHttpServer::serveSettings() {
  77. // Save first to set defaults
  78. settings.save();
  79. serveFile(SETTINGS_FILE, APPLICATION_JSON);
  80. }
  81. void MiLightHttpServer::applySettings(Settings& settings) {
  82. if (settings.hasAuthSettings()) {
  83. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  84. } else {
  85. server.disableAuthentication();
  86. }
  87. }
  88. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  89. this->settingsSavedHandler = handler;
  90. }
  91. void MiLightHttpServer::handleAbout() {
  92. DynamicJsonBuffer buffer;
  93. JsonObject& response = buffer.createObject();
  94. response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  95. response["variant"] = QUOTE(FIRMWARE_VARIANT);
  96. response["free_heap"] = ESP.getFreeHeap();
  97. response["arduino_version"] = ESP.getCoreVersion();
  98. response["reset_reason"] = ESP.getResetReason();
  99. String body;
  100. response.printTo(body);
  101. server.send(200, APPLICATION_JSON, body);
  102. }
  103. void MiLightHttpServer::handleGetRadioConfigs() {
  104. DynamicJsonBuffer buffer;
  105. JsonArray& arr = buffer.createArray();
  106. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  107. const MiLightRemoteConfig* config = MiLightRemoteConfig::ALL_REMOTES[i];
  108. arr.add(config->name);
  109. }
  110. String body;
  111. arr.printTo(body);
  112. server.send(200, APPLICATION_JSON, body);
  113. }
  114. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  115. const char* filename,
  116. const char* contentType,
  117. const char* defaultText) {
  118. return [this, filename, contentType, defaultText]() {
  119. if (!serveFile(filename)) {
  120. if (defaultText) {
  121. server.send(200, contentType, defaultText);
  122. } else {
  123. server.send(404);
  124. }
  125. }
  126. };
  127. }
  128. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  129. if (SPIFFS.exists(file)) {
  130. File f = SPIFFS.open(file, "r");
  131. server.streamFile(f, contentType);
  132. f.close();
  133. return true;
  134. }
  135. return false;
  136. }
  137. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  138. return [this, filename]() {
  139. HTTPUpload& upload = server.upload();
  140. if (upload.status == UPLOAD_FILE_START) {
  141. updateFile = SPIFFS.open(filename, "w");
  142. } else if(upload.status == UPLOAD_FILE_WRITE){
  143. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  144. Serial.println(F("Error updating web file"));
  145. }
  146. } else if (upload.status == UPLOAD_FILE_END) {
  147. updateFile.close();
  148. }
  149. };
  150. }
  151. void MiLightHttpServer::handleUpdateSettings() {
  152. DynamicJsonBuffer buffer;
  153. const String& rawSettings = server.arg("plain");
  154. JsonObject& parsedSettings = buffer.parse(rawSettings);
  155. if (parsedSettings.success()) {
  156. settings.patch(parsedSettings);
  157. settings.save();
  158. this->applySettings(settings);
  159. if (this->settingsSavedHandler) {
  160. this->settingsSavedHandler();
  161. }
  162. server.send(200, APPLICATION_JSON, "true");
  163. Serial.println(F("Settings successfully updated"));
  164. } else {
  165. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  166. Serial.println(F("Settings failed to update; invalid JSON"));
  167. }
  168. }
  169. void MiLightHttpServer::handleUpdateSettingsPost() {
  170. Settings::load(settings);
  171. server.send_P(200, TEXT_PLAIN, PSTR("success."));
  172. }
  173. void MiLightHttpServer::handleFirmwarePost() {
  174. server.sendHeader("Connection", "close");
  175. server.sendHeader("Access-Control-Allow-Origin", "*");
  176. if (Update.hasError()) {
  177. server.send_P(
  178. 500,
  179. TEXT_PLAIN,
  180. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  181. );
  182. } else {
  183. server.send_P(
  184. 200,
  185. TEXT_PLAIN,
  186. PSTR("Success. Device will now reboot.")
  187. );
  188. }
  189. delay(1000);
  190. ESP.restart();
  191. }
  192. void MiLightHttpServer::handleFirmwareUpload() {
  193. HTTPUpload& upload = server.upload();
  194. if(upload.status == UPLOAD_FILE_START){
  195. WiFiUDP::stopAll();
  196. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  197. if(!Update.begin(maxSketchSpace)){//start with max available size
  198. Update.printError(Serial);
  199. }
  200. } else if(upload.status == UPLOAD_FILE_WRITE){
  201. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  202. Update.printError(Serial);
  203. }
  204. } else if(upload.status == UPLOAD_FILE_END){
  205. if(Update.end(true)){ //true to set the size to the current progress
  206. } else {
  207. Update.printError(Serial);
  208. }
  209. }
  210. yield();
  211. }
  212. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  213. bool available = false;
  214. bool listenAll = bindings == NULL;
  215. size_t configIx = 0;
  216. const MiLightRadioConfig* radioConfig = NULL;
  217. const MiLightRemoteConfig* remoteConfig = NULL;
  218. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  219. if (bindings != NULL) {
  220. String strType(bindings->get("type"));
  221. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromType(strType);
  222. milightClient->prepare(remoteConfig, 0, 0);
  223. radioConfig = &remoteConfig->radioConfig;
  224. }
  225. if (radioConfig == NULL && !listenAll) {
  226. server.send_P(400, TEXT_PLAIN, PSTR("Unknown device type supplied."));
  227. return;
  228. }
  229. while (remoteConfig == NULL) {
  230. if (!server.clientConnected()) {
  231. return;
  232. }
  233. if (listenAll) {
  234. radioConfig = &milightClient->switchRadio(configIx++ % milightClient->getNumRadios())->config();
  235. }
  236. if (milightClient->available()) {
  237. size_t packetLen = milightClient->read(packet);
  238. remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  239. *radioConfig,
  240. packet,
  241. packetLen
  242. );
  243. }
  244. yield();
  245. }
  246. char response[200];
  247. char* responseBuffer = response;
  248. responseBuffer += sprintf_P(
  249. responseBuffer,
  250. PSTR("\n%s packet received (%d bytes):\n"),
  251. remoteConfig->name.c_str(),
  252. remoteConfig->packetFormatter->getPacketLength()
  253. );
  254. remoteConfig->packetFormatter->format(packet, responseBuffer);
  255. server.send(200, "text/plain", response);
  256. }
  257. void MiLightHttpServer::sendGroupState(BulbId& bulbId, GroupState* state) {
  258. String body;
  259. StaticJsonBuffer<200> jsonBuffer;
  260. JsonObject& obj = jsonBuffer.createObject();
  261. if (state != NULL) {
  262. state->applyState(obj, bulbId, settings.groupStateFields, settings.numGroupStateFields);
  263. }
  264. obj.printTo(body);
  265. server.send(200, APPLICATION_JSON, body);
  266. }
  267. void MiLightHttpServer::handleGetGroup(const UrlTokenBindings* urlBindings) {
  268. const String _deviceId = urlBindings->get("device_id");
  269. uint8_t _groupId = atoi(urlBindings->get("group_id"));
  270. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(urlBindings->get("type"));
  271. if (_remoteType == NULL) {
  272. char buffer[40];
  273. sprintf_P(buffer, PSTR("Unknown device type\n"));
  274. server.send(400, TEXT_PLAIN, buffer);
  275. return;
  276. }
  277. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  278. GroupState* state = stateStore->get(bulbId);
  279. sendGroupState(bulbId, stateStore->get(bulbId));
  280. }
  281. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  282. DynamicJsonBuffer buffer;
  283. JsonObject& request = buffer.parse(server.arg("plain"));
  284. if (!request.success()) {
  285. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  286. return;
  287. }
  288. milightClient->setResendCount(
  289. settings.httpRepeatFactor * settings.packetRepeats
  290. );
  291. String _deviceIds = urlBindings->get("device_id");
  292. String _groupIds = urlBindings->get("group_id");
  293. String _remoteTypes = urlBindings->get("type");
  294. char deviceIds[_deviceIds.length()];
  295. char groupIds[_groupIds.length()];
  296. char remoteTypes[_remoteTypes.length()];
  297. strcpy(remoteTypes, _remoteTypes.c_str());
  298. strcpy(groupIds, _groupIds.c_str());
  299. strcpy(deviceIds, _deviceIds.c_str());
  300. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  301. TokenIterator groupIdItr(groupIds, _groupIds.length());
  302. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  303. BulbId foundBulbId;
  304. size_t groupCount = 0;
  305. while (remoteTypesItr.hasNext()) {
  306. const char* _remoteType = remoteTypesItr.nextToken();
  307. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  308. if (config == NULL) {
  309. char buffer[40];
  310. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  311. server.send(400, "text/plain", buffer);
  312. return;
  313. }
  314. deviceIdItr.reset();
  315. while (deviceIdItr.hasNext()) {
  316. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  317. groupIdItr.reset();
  318. while (groupIdItr.hasNext()) {
  319. const uint8_t groupId = atoi(groupIdItr.nextToken());
  320. milightClient->prepare(config, deviceId, groupId);
  321. handleRequest(request);
  322. foundBulbId = BulbId(deviceId, groupId, config->type);
  323. groupCount++;
  324. }
  325. }
  326. }
  327. if (groupCount == 1) {
  328. sendGroupState(foundBulbId, stateStore->get(foundBulbId));
  329. } else {
  330. server.send(200, APPLICATION_JSON, "true");
  331. }
  332. }
  333. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  334. milightClient->update(request);
  335. }
  336. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  337. DynamicJsonBuffer buffer;
  338. JsonObject& request = buffer.parse(server.arg("plain"));
  339. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bindings->get("type"));
  340. if (config == NULL) {
  341. char buffer[50];
  342. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  343. server.send(400, "text/plain", buffer);
  344. return;
  345. }
  346. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  347. const String& hexPacket = request["packet"];
  348. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  349. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  350. if (request.containsKey("num_repeats")) {
  351. numRepeats = request["num_repeats"];
  352. }
  353. milightClient->prepare(config, 0, 0);
  354. for (size_t i = 0; i < numRepeats; i++) {
  355. milightClient->write(packet);
  356. }
  357. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  358. }
  359. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  360. switch (type) {
  361. case WStype_DISCONNECTED:
  362. if (numWsClients > 0) {
  363. numWsClients--;
  364. }
  365. break;
  366. case WStype_CONNECTED:
  367. numWsClients++;
  368. break;
  369. }
  370. }
  371. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  372. if (numWsClients > 0) {
  373. size_t packetLen = config.packetFormatter->getPacketLength();
  374. char buffer[packetLen*3];
  375. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  376. char formattedPacket[200];
  377. config.packetFormatter->format(packet, formattedPacket);
  378. char responseBuffer[300];
  379. sprintf_P(
  380. responseBuffer,
  381. PSTR("\n%s packet received (%d bytes):\n%s"),
  382. config.name.c_str(),
  383. packetLen,
  384. formattedPacket
  385. );
  386. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  387. }
  388. }
  389. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  390. return [this, data, length]() {
  391. server.sendHeader("Content-Encoding", "gzip");
  392. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  393. server.send(200, "text/html", "");
  394. server.sendContent_P(data, length);
  395. server.sendContent("");
  396. server.client().stop();
  397. };
  398. }