MiLightHttpServer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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 <GithubClient.h>
  8. #include <string.h>
  9. #include <TokenIterator.h>
  10. #include <index.html.gz.h>
  11. void MiLightHttpServer::begin() {
  12. applySettings(settings);
  13. server.on("/", HTTP_GET, handleServe_P(index_html_gz, index_html_gz_len));
  14. server.on("/settings", HTTP_GET, handleServeFile(SETTINGS_FILE, APPLICATION_JSON));
  15. server.on("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  16. server.on("/settings", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success. rebooting")); ESP.restart(); }, handleUpdateFile(SETTINGS_FILE));
  17. server.on("/radio_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  18. server.on("/gateway_traffic", HTTP_GET, [this]() { handleListenGateway(NULL); });
  19. server.onPattern("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  20. server.onPattern("/gateways/:device_id/:type/:group_id", HTTP_ANY, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  21. server.onPattern("/raw_commands/:type", HTTP_ANY, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  22. server.onPattern("/download_update/:component", HTTP_GET, [this](const UrlTokenBindings* b) { handleDownloadUpdate(b); });
  23. server.on("/web", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success")); }, handleUpdateFile(WEB_INDEX_FILENAME));
  24. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  25. server.on("/latest_release", HTTP_GET, [this]() { handleGetLatestRelease(); });
  26. server.on("/system", HTTP_POST, [this]() { handleSystemPost(); });
  27. server.on("/firmware", HTTP_POST,
  28. [this](){
  29. server.sendHeader("Connection", "close");
  30. server.sendHeader("Access-Control-Allow-Origin", "*");
  31. if (Update.hasError()) {
  32. server.send_P(
  33. 500,
  34. TEXT_PLAIN,
  35. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  36. );
  37. } else {
  38. server.send_P(
  39. 200,
  40. TEXT_PLAIN,
  41. PSTR("Success. Device will now reboot.")
  42. );
  43. }
  44. ESP.restart();
  45. },
  46. [this](){
  47. HTTPUpload& upload = server.upload();
  48. if(upload.status == UPLOAD_FILE_START){
  49. WiFiUDP::stopAll();
  50. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  51. if(!Update.begin(maxSketchSpace)){//start with max available size
  52. Update.printError(Serial);
  53. }
  54. } else if(upload.status == UPLOAD_FILE_WRITE){
  55. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  56. Update.printError(Serial);
  57. }
  58. } else if(upload.status == UPLOAD_FILE_END){
  59. if(Update.end(true)){ //true to set the size to the current progress
  60. } else {
  61. Update.printError(Serial);
  62. }
  63. }
  64. yield();
  65. }
  66. );
  67. server.begin();
  68. }
  69. void MiLightHttpServer::handleGetLatestRelease() {
  70. GithubClient client = GithubClient::apiClient();
  71. String path = GithubClient::buildApiRequest(
  72. MILIGHT_GITHUB_USER,
  73. MILIGHT_GITHUB_REPO,
  74. "/releases/latest"
  75. );
  76. // This is an ugly hack, but probably not worth optimizing. The nice way
  77. // to do this would be to extract the content len from GitHub's response
  78. // and stream the body to the server directly. But this would require parsing
  79. // headers in the response from GitHub, which seems like more trouble than
  80. // it's worth.
  81. const String& fsPath = "/_cv.json";
  82. size_t tries = 0;
  83. while (tries++ < MAX_DOWNLOAD_ATTEMPTS && !client.download(path, fsPath)) {
  84. Serial.println(F("Failed download attempt."));
  85. }
  86. if (!SPIFFS.exists(fsPath)) {
  87. server.send_P(500, TEXT_PLAIN, PSTR("Failed to stream API request from GitHub. Check Serial logs for more information."));
  88. return;
  89. }
  90. File file = SPIFFS.open(fsPath, "r");
  91. server.streamFile(file, APPLICATION_JSON);
  92. SPIFFS.remove(fsPath);
  93. }
  94. void MiLightHttpServer::handleClient() {
  95. server.handleClient();
  96. }
  97. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  98. server.on(path, method, handler);
  99. }
  100. WiFiClient MiLightHttpServer::client() {
  101. return server.client();
  102. }
  103. void MiLightHttpServer::handleSystemPost() {
  104. DynamicJsonBuffer buffer;
  105. JsonObject& request = buffer.parse(server.arg("plain"));
  106. bool handled = false;
  107. if (request.containsKey("command")) {
  108. if (request["command"] == "restart") {
  109. Serial.println(F("Restarting..."));
  110. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  111. delay(100);
  112. ESP.restart();
  113. handled = true;
  114. } else if (request["command"] == "clear_wifi_config") {
  115. Serial.println(F("Resetting Wifi and then Restarting..."));
  116. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  117. delay(100);
  118. ESP.eraseConfig();
  119. delay(100);
  120. ESP.restart();
  121. handled = true;
  122. }
  123. }
  124. if (handled) {
  125. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  126. } else {
  127. server.send_P(400, TEXT_PLAIN, PSTR("{\"error\":\"Unhandled command\"}"));
  128. }
  129. }
  130. void MiLightHttpServer::handleDownloadUpdate(const UrlTokenBindings* bindings) {
  131. GithubClient downloader = GithubClient::rawDownloader();
  132. const String& component = bindings->get("component");
  133. if (component.equalsIgnoreCase("web")) {
  134. Serial.println(F("Attempting to update web UI..."));
  135. bool result = false;
  136. size_t tries = 0;
  137. while (!result && tries++ <= MAX_DOWNLOAD_ATTEMPTS) {
  138. Serial.println(F("building url\n"));
  139. String urlPath = GithubClient::buildRepoPath(
  140. MILIGHT_GITHUB_USER,
  141. MILIGHT_GITHUB_REPO,
  142. MILIGHT_REPO_WEB_PATH
  143. );
  144. printf_P(PSTR("URL: %s\n"), urlPath.c_str());
  145. result = downloader.download(urlPath, WEB_INDEX_FILENAME);
  146. }
  147. Serial.println(F("Download complete!"));
  148. if (result) {
  149. server.sendHeader("Location", "/");
  150. server.send(302);
  151. } else {
  152. server.send_P(500, TEXT_PLAIN, PSTR("Failed to download update from Github. Check serial logs for more information."));
  153. }
  154. } else {
  155. String body = String("Unknown component: ") + component;
  156. server.send(400, "text/plain", body);
  157. }
  158. }
  159. void MiLightHttpServer::applySettings(Settings& settings) {
  160. if (settings.hasAuthSettings()) {
  161. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  162. } else {
  163. server.disableAuthentication();
  164. }
  165. milightClient->setResendCount(settings.packetRepeats);
  166. }
  167. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  168. this->settingsSavedHandler = handler;
  169. }
  170. void MiLightHttpServer::handleAbout() {
  171. DynamicJsonBuffer buffer;
  172. JsonObject& response = buffer.createObject();
  173. response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  174. response["variant"] = QUOTE(FIRMWARE_VARIANT);
  175. response["free_heap"] = ESP.getFreeHeap();
  176. String body;
  177. response.printTo(body);
  178. server.send(200, "application", body);
  179. }
  180. void MiLightHttpServer::handleGetRadioConfigs() {
  181. DynamicJsonBuffer buffer;
  182. JsonArray& arr = buffer.createArray();
  183. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  184. const MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[i];
  185. arr.add(config->name);
  186. }
  187. String body;
  188. arr.printTo(body);
  189. server.send(200, APPLICATION_JSON, body);
  190. }
  191. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  192. const char* filename,
  193. const char* contentType,
  194. const char* defaultText) {
  195. return [this, filename, contentType, defaultText]() {
  196. if (!serveFile(filename)) {
  197. if (defaultText) {
  198. server.send(200, contentType, defaultText);
  199. } else {
  200. server.send(404);
  201. }
  202. }
  203. };
  204. }
  205. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  206. if (SPIFFS.exists(file)) {
  207. File f = SPIFFS.open(file, "r");
  208. server.streamFile(f, contentType);
  209. f.close();
  210. return true;
  211. }
  212. return false;
  213. }
  214. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  215. return [this, filename]() {
  216. HTTPUpload& upload = server.upload();
  217. if (upload.status == UPLOAD_FILE_START) {
  218. updateFile = SPIFFS.open(filename, "w");
  219. } else if(upload.status == UPLOAD_FILE_WRITE){
  220. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  221. Serial.println(F("Error updating web file"));
  222. }
  223. } else if (upload.status == UPLOAD_FILE_END) {
  224. updateFile.close();
  225. }
  226. };
  227. }
  228. void MiLightHttpServer::handleUpdateSettings() {
  229. DynamicJsonBuffer buffer;
  230. const String& rawSettings = server.arg("plain");
  231. JsonObject& parsedSettings = buffer.parse(rawSettings);
  232. if (parsedSettings.success()) {
  233. settings.patch(parsedSettings);
  234. settings.save();
  235. this->applySettings(settings);
  236. this->settingsSavedHandler();
  237. server.send(200, APPLICATION_JSON, "true");
  238. } else {
  239. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  240. }
  241. }
  242. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  243. bool available = false;
  244. bool listenAll = bindings == NULL;
  245. uint8_t configIx = 0;
  246. MiLightRadioConfig* currentConfig =
  247. listenAll
  248. ? MiLightRadioConfig::ALL_CONFIGS[0]
  249. : MiLightRadioConfig::fromString(bindings->get("type"));
  250. if (currentConfig == NULL && bindings != NULL) {
  251. String body = "Unknown device type: ";
  252. body += bindings->get("type");
  253. server.send(400, "text/plain", body);
  254. return;
  255. }
  256. while (!available) {
  257. if (!server.clientConnected()) {
  258. return;
  259. }
  260. if (listenAll) {
  261. currentConfig = MiLightRadioConfig::ALL_CONFIGS[
  262. configIx++ % MiLightRadioConfig::NUM_CONFIGS
  263. ];
  264. }
  265. milightClient->prepare(*currentConfig, 0, 0);
  266. if (milightClient->available()) {
  267. available = true;
  268. }
  269. yield();
  270. }
  271. uint8_t packet[currentConfig->getPacketLength()];
  272. milightClient->read(packet);
  273. char response[200];
  274. char* responseBuffer = response;
  275. responseBuffer += sprintf_P(
  276. responseBuffer,
  277. PSTR("\n%s packet received (%d bytes):\n"),
  278. currentConfig->name,
  279. sizeof(packet)
  280. );
  281. milightClient->formatPacket(packet, responseBuffer);
  282. server.send(200, "text/plain", response);
  283. }
  284. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  285. DynamicJsonBuffer buffer;
  286. JsonObject& request = buffer.parse(server.arg("plain"));
  287. if (!request.success()) {
  288. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  289. return;
  290. }
  291. milightClient->setResendCount(
  292. settings.httpRepeatFactor * settings.packetRepeats
  293. );
  294. String _deviceIds = urlBindings->get("device_id");
  295. String _groupIds = urlBindings->get("group_id");
  296. String _radioTypes = urlBindings->get("type");
  297. char deviceIds[_deviceIds.length()];
  298. char groupIds[_groupIds.length()];
  299. char radioTypes[_radioTypes.length()];
  300. strcpy(radioTypes, _radioTypes.c_str());
  301. strcpy(groupIds, _groupIds.c_str());
  302. strcpy(deviceIds, _deviceIds.c_str());
  303. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  304. TokenIterator groupIdItr(groupIds, _groupIds.length());
  305. TokenIterator radioTypesItr(radioTypes, _radioTypes.length());
  306. while (radioTypesItr.hasNext()) {
  307. const char* _radioType = radioTypesItr.nextToken();
  308. MiLightRadioConfig* config = MiLightRadioConfig::fromString(_radioType);
  309. if (config == NULL) {
  310. String body = "Unknown device type: ";
  311. body += String(_radioType);
  312. server.send(400, "text/plain", body);
  313. return;
  314. }
  315. deviceIdItr.reset();
  316. while (deviceIdItr.hasNext()) {
  317. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  318. groupIdItr.reset();
  319. while (groupIdItr.hasNext()) {
  320. const uint8_t groupId = atoi(groupIdItr.nextToken());
  321. milightClient->prepare(*config, deviceId, groupId);
  322. handleRequest(request);
  323. }
  324. }
  325. }
  326. server.send(200, APPLICATION_JSON, "true");
  327. }
  328. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  329. milightClient->update(request);
  330. }
  331. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  332. DynamicJsonBuffer buffer;
  333. JsonObject& request = buffer.parse(server.arg("plain"));
  334. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  335. if (config == NULL) {
  336. String body = "Unknown device type: ";
  337. body += bindings->get("type");
  338. server.send(400, "text/plain", body);
  339. return;
  340. }
  341. uint8_t packet[config->getPacketLength()];
  342. const String& hexPacket = request["packet"];
  343. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  344. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  345. if (request.containsKey("num_repeats")) {
  346. numRepeats = request["num_repeats"];
  347. }
  348. milightClient->prepare(*config, 0, 0);
  349. for (size_t i = 0; i < numRepeats; i++) {
  350. milightClient->write(packet);
  351. }
  352. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  353. }
  354. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  355. return [this, data, length]() {
  356. server.sendHeader("Content-Encoding", "gzip");
  357. server.sendHeader("Content-Length", String(length));
  358. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  359. server.send(200, "text/html", "");
  360. server.setContentLength(length);
  361. server.sendContent_P(data, length);
  362. server.client().stop();
  363. };
  364. }