MiLightHttpServer.cpp 14 KB

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