MiLightHttpServer.cpp 12 KB

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