MiLightHttpServer.cpp 13 KB

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