MiLightHttpServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. #include <string.h>
  9. #include <TokenIterator.h>
  10. #include <ESP8266SSDP.h>
  11. void MiLightHttpServer::begin() {
  12. applySettings(settings);
  13. server.on("/", HTTP_GET, handleServeFile(WEB_INDEX_FILENAME, "text/html", DEFAULT_INDEX_PAGE));
  14. server.on("/settings", HTTP_GET, handleServeFile(SETTINGS_FILE, "application/json"));
  15. server.on("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  16. server.on("/settings", HTTP_POST, [this]() { server.send(200, "text/plain", "success"); }, handleUpdateFile(SETTINGS_FILE));
  17. server.on("/radio_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  18. server.onPattern("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  19. server.onPattern("/gateways/:device_id/:type/:group_id", HTTP_ANY, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  20. server.onPattern("/raw_commands/:type", HTTP_ANY, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  21. server.onPattern("/download_update/:component", HTTP_GET, [this](const UrlTokenBindings* b) { handleDownloadUpdate(b); });
  22. server.on("/web", HTTP_POST, [this]() { server.send(200, "text/plain", "success"); }, handleUpdateFile(WEB_INDEX_FILENAME));
  23. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  24. server.on("/latest_release", HTTP_GET, [this]() { handleGetLatestRelease(); });
  25. server.on("/system", HTTP_POST, [this]() { handleSystemPost(); });
  26. server.on("/description.xml", HTTP_GET, [this]() { SSDP.schema(server.client()); });
  27. server.on("/firmware", HTTP_POST,
  28. [this](){
  29. server.sendHeader("Connection", "close");
  30. server.sendHeader("Access-Control-Allow-Origin", "*");
  31. if (Update.hasError()) {
  32. server.send_P(
  33. 500,
  34. "text/plain",
  35. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  36. );
  37. } else {
  38. server.send_P(
  39. 200,
  40. "text/plain",
  41. PSTR("Success. Device will now reboot.")
  42. );
  43. }
  44. ESP.restart();
  45. },
  46. [this](){
  47. HTTPUpload& upload = server.upload();
  48. if(upload.status == UPLOAD_FILE_START){
  49. WiFiUDP::stopAll();
  50. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  51. if(!Update.begin(maxSketchSpace)){//start with max available size
  52. Update.printError(Serial);
  53. }
  54. } else if(upload.status == UPLOAD_FILE_WRITE){
  55. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  56. Update.printError(Serial);
  57. }
  58. } else if(upload.status == UPLOAD_FILE_END){
  59. if(Update.end(true)){ //true to set the size to the current progress
  60. } else {
  61. Update.printError(Serial);
  62. }
  63. }
  64. yield();
  65. }
  66. );
  67. server.begin();
  68. }
  69. void MiLightHttpServer::handleGetLatestRelease() {
  70. GithubClient client = GithubClient::apiClient();
  71. String path = GithubClient::buildApiRequest(
  72. MILIGHT_GITHUB_USER,
  73. MILIGHT_GITHUB_REPO,
  74. "/releases/latest"
  75. );
  76. Serial.println(path);
  77. // This is an ugly hack, but probably not worth optimizing. The nice way
  78. // to do this would be to extract the content len from GitHub's response
  79. // and stream the body to the server directly. But this would require parsing
  80. // headers in the response from GitHub, which seems like more trouble than
  81. // it's worth.
  82. const String& fsPath = "/_cv.json";
  83. size_t tries = 0;
  84. while (tries++ < MAX_DOWNLOAD_ATTEMPTS && !client.download(path, fsPath)) {
  85. Serial.println(F("Failed download attempt."));
  86. }
  87. if (!SPIFFS.exists(fsPath)) {
  88. server.send_P(500, "text/plain", PSTR("Failed to stream API request from GitHub. Check Serial logs for more information."));
  89. return;
  90. }
  91. File file = SPIFFS.open(fsPath, "r");
  92. server.streamFile(file, "application/json");
  93. SPIFFS.remove(fsPath);
  94. }
  95. void MiLightHttpServer::handleClient() {
  96. server.handleClient();
  97. }
  98. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  99. server.on(path, method, handler);
  100. }
  101. WiFiClient MiLightHttpServer::client() {
  102. return server.client();
  103. }
  104. void MiLightHttpServer::handleSystemPost() {
  105. DynamicJsonBuffer buffer;
  106. JsonObject& request = buffer.parse(server.arg("plain"));
  107. bool handled = false;
  108. if (request.containsKey("command")) {
  109. if (request["command"] == "restart") {
  110. Serial.println(F("Restarting..."));
  111. server.send(200, "text/plain", "true");
  112. delay(100);
  113. ESP.restart();
  114. }
  115. }
  116. if (handled) {
  117. server.send(200, "text/plain", "true");
  118. } else {
  119. server.send(400, "text/plain", F("{\"error\":\"Unhandled command\"}"));
  120. }
  121. }
  122. void MiLightHttpServer::handleDownloadUpdate(const UrlTokenBindings* bindings) {
  123. GithubClient downloader = GithubClient::rawDownloader();
  124. const String& component = bindings->get("component");
  125. if (component.equalsIgnoreCase("web")) {
  126. Serial.println(F("Attempting to update web UI..."));
  127. bool result = false;
  128. size_t tries = 0;
  129. while (!result && tries++ <= MAX_DOWNLOAD_ATTEMPTS) {
  130. printf("building url\n");
  131. String urlPath = GithubClient::buildRepoPath(
  132. MILIGHT_GITHUB_USER,
  133. MILIGHT_GITHUB_REPO,
  134. MILIGHT_REPO_WEB_PATH
  135. );
  136. printf("URL: %s\n", urlPath.c_str());
  137. result = downloader.download(urlPath, WEB_INDEX_FILENAME);
  138. }
  139. Serial.println(F("Download complete!"));
  140. if (result) {
  141. server.sendHeader("Location", "/");
  142. server.send(302);
  143. } else {
  144. server.send(500, "text/plain", F("Failed to download update from Github. Check serial logs for more information."));
  145. }
  146. } else {
  147. String body = String("Unknown component: ") + component;
  148. server.send(400, "text/plain", body);
  149. }
  150. }
  151. void MiLightHttpServer::applySettings(Settings& settings) {
  152. if (settings.hasAuthSettings()) {
  153. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  154. } else {
  155. server.disableAuthentication();
  156. }
  157. milightClient->setResendCount(settings.packetRepeats);
  158. }
  159. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  160. this->settingsSavedHandler = handler;
  161. }
  162. void MiLightHttpServer::handleAbout() {
  163. DynamicJsonBuffer buffer;
  164. JsonObject& response = buffer.createObject();
  165. response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  166. response["variant"] = QUOTE(FIRMWARE_VARIANT);
  167. String body;
  168. response.printTo(body);
  169. server.send(200, "application", body);
  170. }
  171. void MiLightHttpServer::handleGetRadioConfigs() {
  172. DynamicJsonBuffer buffer;
  173. JsonArray& arr = buffer.createArray();
  174. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  175. const MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[i];
  176. arr.add(config->name);
  177. }
  178. String body;
  179. arr.printTo(body);
  180. server.send(200, "application/json", body);
  181. }
  182. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  183. const char* filename,
  184. const char* contentType,
  185. const char* defaultText) {
  186. return [this, filename, contentType, defaultText]() {
  187. if (!serveFile(filename)) {
  188. if (defaultText) {
  189. server.send(200, contentType, defaultText);
  190. } else {
  191. server.send(404);
  192. }
  193. }
  194. };
  195. }
  196. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  197. if (SPIFFS.exists(file)) {
  198. File f = SPIFFS.open(file, "r");
  199. server.streamFile(f, contentType);
  200. f.close();
  201. return true;
  202. }
  203. return false;
  204. }
  205. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  206. return [this, filename]() {
  207. HTTPUpload& upload = server.upload();
  208. if (upload.status == UPLOAD_FILE_START) {
  209. updateFile = SPIFFS.open(filename, "w");
  210. } else if(upload.status == UPLOAD_FILE_WRITE){
  211. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  212. Serial.println(F("Error updating web file"));
  213. }
  214. } else if (upload.status == UPLOAD_FILE_END) {
  215. updateFile.close();
  216. }
  217. };
  218. }
  219. void MiLightHttpServer::handleUpdateSettings() {
  220. DynamicJsonBuffer buffer;
  221. const String& rawSettings = server.arg("plain");
  222. JsonObject& parsedSettings = buffer.parse(rawSettings);
  223. if (parsedSettings.success()) {
  224. settings.patch(parsedSettings);
  225. settings.save();
  226. this->applySettings(settings);
  227. this->settingsSavedHandler();
  228. server.send(200, "application/json", "true");
  229. } else {
  230. server.send(400, "application/json", "\"Invalid JSON\"");
  231. }
  232. }
  233. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  234. bool available = false;
  235. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  236. if (config == NULL) {
  237. String body = "Unknown device type: ";
  238. body += bindings->get("type");
  239. server.send(400, "text/plain", body);
  240. return;
  241. }
  242. milightClient->prepare(*config, 0, 0);
  243. while (!available) {
  244. if (!server.clientConnected()) {
  245. return;
  246. }
  247. if (milightClient->available()) {
  248. available = true;
  249. }
  250. yield();
  251. }
  252. uint8_t packet[config->getPacketLength()];
  253. milightClient->read(packet);
  254. char response[200];
  255. char* responseBuffer = response;
  256. responseBuffer += sprintf(responseBuffer, "\nPacket received (%d bytes):\n", sizeof(packet));
  257. milightClient->formatPacket(packet, responseBuffer);
  258. server.send(200, "text/plain", response);
  259. }
  260. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  261. DynamicJsonBuffer buffer;
  262. JsonObject& request = buffer.parse(server.arg("plain"));
  263. if (!request.success()) {
  264. server.send(400, "text/plain", F("Invalid JSON"));
  265. return;
  266. }
  267. milightClient->setResendCount(
  268. settings.httpRepeatFactor * settings.packetRepeats
  269. );
  270. String _deviceIds = urlBindings->get("device_id");
  271. String _groupIds = urlBindings->get("group_id");
  272. String _radioTypes = urlBindings->get("type");
  273. char deviceIds[_deviceIds.length()];
  274. char groupIds[_groupIds.length()];
  275. char radioTypes[_radioTypes.length()];
  276. strcpy(radioTypes, _radioTypes.c_str());
  277. strcpy(groupIds, _groupIds.c_str());
  278. strcpy(deviceIds, _deviceIds.c_str());
  279. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  280. TokenIterator groupIdItr(groupIds, _groupIds.length());
  281. TokenIterator radioTypesItr(radioTypes, _radioTypes.length());
  282. while (radioTypesItr.hasNext()) {
  283. const char* _radioType = radioTypesItr.nextToken();
  284. MiLightRadioConfig* config = MiLightRadioConfig::fromString(_radioType);
  285. if (config == NULL) {
  286. String body = "Unknown device type: ";
  287. body += String(_radioType);
  288. server.send(400, "text/plain", body);
  289. return;
  290. }
  291. deviceIdItr.reset();
  292. while (deviceIdItr.hasNext()) {
  293. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  294. groupIdItr.reset();
  295. while (groupIdItr.hasNext()) {
  296. const uint8_t groupId = atoi(groupIdItr.nextToken());
  297. milightClient->prepare(*config, deviceId, groupId);
  298. handleRequest(request);
  299. }
  300. }
  301. }
  302. server.send(200, "application/json", "true");
  303. }
  304. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  305. if (request.containsKey("status")) {
  306. const String& statusStr = request.get<String>("status");
  307. MiLightStatus status = (statusStr == "on" || statusStr == "true") ? ON : OFF;
  308. milightClient->updateStatus(status);
  309. }
  310. if (request.containsKey("command")) {
  311. if (request["command"] == "unpair") {
  312. milightClient->unpair();
  313. }
  314. if (request["command"] == "pair") {
  315. milightClient->pair();
  316. }
  317. if (request["command"] == "set_white") {
  318. milightClient->updateColorWhite();
  319. }
  320. if (request["command"] == "night_mode") {
  321. milightClient->enableNightMode();
  322. }
  323. if (request["command"] == "level_up") {
  324. milightClient->increaseBrightness();
  325. }
  326. if (request["command"] == "level_down") {
  327. milightClient->decreaseBrightness();
  328. }
  329. if (request["command"] == "temperature_up") {
  330. milightClient->increaseTemperature();
  331. }
  332. if (request["command"] == "temperature_down") {
  333. milightClient->decreaseTemperature();
  334. }
  335. if (request["command"] == "next_mode") {
  336. milightClient->nextMode();
  337. }
  338. if (request["command"] == "previous_mode") {
  339. milightClient->previousMode();
  340. }
  341. if (request["command"] == "mode_speed_down") {
  342. milightClient->modeSpeedDown();
  343. }
  344. if (request["command"] == "mode_speed_up") {
  345. milightClient->modeSpeedUp();
  346. }
  347. }
  348. if (request.containsKey("hue")) {
  349. milightClient->updateHue(request["hue"]);
  350. }
  351. if (request.containsKey("level")) {
  352. milightClient->updateBrightness(request["level"]);
  353. }
  354. if (request.containsKey("temperature")) {
  355. milightClient->updateTemperature(request["temperature"]);
  356. }
  357. if (request.containsKey("saturation")) {
  358. milightClient->updateSaturation(request["saturation"]);
  359. }
  360. if (request.containsKey("mode")) {
  361. milightClient->updateMode(request["mode"]);
  362. }
  363. milightClient->setResendCount(settings.packetRepeats);
  364. }
  365. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  366. DynamicJsonBuffer buffer;
  367. JsonObject& request = buffer.parse(server.arg("plain"));
  368. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  369. if (config == NULL) {
  370. String body = "Unknown device type: ";
  371. body += bindings->get("type");
  372. server.send(400, "text/plain", body);
  373. return;
  374. }
  375. uint8_t packet[config->getPacketLength()];
  376. const String& hexPacket = request["packet"];
  377. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  378. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  379. if (request.containsKey("num_repeats")) {
  380. numRepeats = request["num_repeats"];
  381. }
  382. milightClient->prepare(*config, 0, 0);
  383. for (size_t i = 0; i < numRepeats; i++) {
  384. milightClient->write(packet);
  385. }
  386. server.send(200, "text/plain", "true");
  387. }