MiLightHttpServer.cpp 11 KB

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