MiLightHttpServer.cpp 11 KB

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