MiLightHttpServer.cpp 11 KB

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