MiLightHttpServer.cpp 12 KB

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