MiLightHttpServer.cpp 11 KB

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