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