MiLightHttpServer.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. response["arduino_version"] = ESP.getCoreVersion();
  177. response["reset_reason"] = ESP.getResetReason();
  178. String body;
  179. response.printTo(body);
  180. server.send(200, APPLICATION_JSON, body);
  181. }
  182. void MiLightHttpServer::handleGetRadioConfigs() {
  183. DynamicJsonBuffer buffer;
  184. JsonArray& arr = buffer.createArray();
  185. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  186. const MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[i];
  187. arr.add(config->name);
  188. }
  189. String body;
  190. arr.printTo(body);
  191. server.send(200, APPLICATION_JSON, body);
  192. }
  193. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  194. const char* filename,
  195. const char* contentType,
  196. const char* defaultText) {
  197. return [this, filename, contentType, defaultText]() {
  198. if (!serveFile(filename)) {
  199. if (defaultText) {
  200. server.send(200, contentType, defaultText);
  201. } else {
  202. server.send(404);
  203. }
  204. }
  205. };
  206. }
  207. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  208. if (SPIFFS.exists(file)) {
  209. File f = SPIFFS.open(file, "r");
  210. server.streamFile(f, contentType);
  211. f.close();
  212. return true;
  213. }
  214. return false;
  215. }
  216. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  217. return [this, filename]() {
  218. HTTPUpload& upload = server.upload();
  219. if (upload.status == UPLOAD_FILE_START) {
  220. updateFile = SPIFFS.open(filename, "w");
  221. } else if(upload.status == UPLOAD_FILE_WRITE){
  222. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  223. Serial.println(F("Error updating web file"));
  224. }
  225. } else if (upload.status == UPLOAD_FILE_END) {
  226. updateFile.close();
  227. }
  228. };
  229. }
  230. void MiLightHttpServer::handleUpdateSettings() {
  231. DynamicJsonBuffer buffer;
  232. const String& rawSettings = server.arg("plain");
  233. JsonObject& parsedSettings = buffer.parse(rawSettings);
  234. if (parsedSettings.success()) {
  235. settings.patch(parsedSettings);
  236. settings.save();
  237. this->applySettings(settings);
  238. this->settingsSavedHandler();
  239. server.send(200, APPLICATION_JSON, "true");
  240. } else {
  241. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  242. }
  243. }
  244. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  245. bool available = false;
  246. bool listenAll = bindings == NULL;
  247. uint8_t configIx = 0;
  248. MiLightRadioConfig* currentConfig =
  249. listenAll
  250. ? MiLightRadioConfig::ALL_CONFIGS[0]
  251. : MiLightRadioConfig::fromString(bindings->get("type"));
  252. if (currentConfig == NULL && bindings != NULL) {
  253. String body = "Unknown device type: ";
  254. body += bindings->get("type");
  255. server.send(400, "text/plain", body);
  256. return;
  257. }
  258. while (!available) {
  259. if (!server.clientConnected()) {
  260. return;
  261. }
  262. if (listenAll) {
  263. currentConfig = MiLightRadioConfig::ALL_CONFIGS[
  264. configIx++ % MiLightRadioConfig::NUM_CONFIGS
  265. ];
  266. }
  267. milightClient->prepare(*currentConfig, 0, 0);
  268. if (milightClient->available()) {
  269. available = true;
  270. }
  271. yield();
  272. }
  273. uint8_t packet[currentConfig->getPacketLength()];
  274. milightClient->read(packet);
  275. char response[200];
  276. char* responseBuffer = response;
  277. responseBuffer += sprintf_P(
  278. responseBuffer,
  279. PSTR("\n%s packet received (%d bytes):\n"),
  280. currentConfig->name,
  281. sizeof(packet)
  282. );
  283. milightClient->formatPacket(packet, responseBuffer);
  284. server.send(200, "text/plain", response);
  285. }
  286. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  287. DynamicJsonBuffer buffer;
  288. JsonObject& request = buffer.parse(server.arg("plain"));
  289. if (!request.success()) {
  290. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  291. return;
  292. }
  293. milightClient->setResendCount(
  294. settings.httpRepeatFactor * settings.packetRepeats
  295. );
  296. String _deviceIds = urlBindings->get("device_id");
  297. String _groupIds = urlBindings->get("group_id");
  298. String _radioTypes = urlBindings->get("type");
  299. char deviceIds[_deviceIds.length()];
  300. char groupIds[_groupIds.length()];
  301. char radioTypes[_radioTypes.length()];
  302. strcpy(radioTypes, _radioTypes.c_str());
  303. strcpy(groupIds, _groupIds.c_str());
  304. strcpy(deviceIds, _deviceIds.c_str());
  305. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  306. TokenIterator groupIdItr(groupIds, _groupIds.length());
  307. TokenIterator radioTypesItr(radioTypes, _radioTypes.length());
  308. while (radioTypesItr.hasNext()) {
  309. const char* _radioType = radioTypesItr.nextToken();
  310. MiLightRadioConfig* config = MiLightRadioConfig::fromString(_radioType);
  311. if (config == NULL) {
  312. String body = "Unknown device type: ";
  313. body += String(_radioType);
  314. server.send(400, "text/plain", body);
  315. return;
  316. }
  317. deviceIdItr.reset();
  318. while (deviceIdItr.hasNext()) {
  319. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  320. groupIdItr.reset();
  321. while (groupIdItr.hasNext()) {
  322. const uint8_t groupId = atoi(groupIdItr.nextToken());
  323. milightClient->prepare(*config, deviceId, groupId);
  324. handleRequest(request);
  325. }
  326. }
  327. }
  328. server.send(200, APPLICATION_JSON, "true");
  329. }
  330. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  331. milightClient->update(request);
  332. }
  333. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  334. DynamicJsonBuffer buffer;
  335. JsonObject& request = buffer.parse(server.arg("plain"));
  336. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  337. if (config == NULL) {
  338. String body = "Unknown device type: ";
  339. body += bindings->get("type");
  340. server.send(400, "text/plain", body);
  341. return;
  342. }
  343. uint8_t packet[config->getPacketLength()];
  344. const String& hexPacket = request["packet"];
  345. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  346. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  347. if (request.containsKey("num_repeats")) {
  348. numRepeats = request["num_repeats"];
  349. }
  350. milightClient->prepare(*config, 0, 0);
  351. for (size_t i = 0; i < numRepeats; i++) {
  352. milightClient->write(packet);
  353. }
  354. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  355. }
  356. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  357. return [this, data, length]() {
  358. server.sendHeader("Content-Encoding", "gzip");
  359. server.sendHeader("Content-Length", String(length));
  360. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  361. server.send(200, "text/html", "");
  362. server.setContentLength(length);
  363. server.sendContent_P(data, length);
  364. server.client().stop();
  365. };
  366. }