MiLightHttpServer.cpp 12 KB

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