MiLightHttpServer.cpp 12 KB

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