MiLightHttpServer.cpp 13 KB

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