MiLightHttpServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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 <string.h>
  8. #include <TokenIterator.h>
  9. #include <AboutStringHelper.h>
  10. #include <index.html.gz.h>
  11. void MiLightHttpServer::begin() {
  12. applySettings(settings);
  13. // set up HTTP end points to serve
  14. _handleRootPage = handleServe_P(index_html_gz, index_html_gz_len);
  15. server.onAuthenticated("/", HTTP_GET, [this]() { _handleRootPage(); });
  16. server.onAuthenticated("/settings", HTTP_GET, [this]() { serveSettings(); });
  17. server.onAuthenticated("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  18. server.onAuthenticated("/settings", HTTP_POST, [this]() { handleUpdateSettingsPost(); }, handleUpdateFile(SETTINGS_FILE));
  19. server.onAuthenticated("/remote_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  20. server.onAuthenticated("/gateway_traffic", HTTP_GET, [this]() { handleListenGateway(NULL); });
  21. server.onPatternAuthenticated("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  22. const char groupPattern[] = "/gateways/:device_id/:type/:group_id";
  23. server.onPatternAuthenticated(groupPattern, HTTP_PUT, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  24. server.onPatternAuthenticated(groupPattern, HTTP_POST, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  25. server.onPatternAuthenticated(groupPattern, HTTP_GET, [this](const UrlTokenBindings* b) { handleGetGroup(b); });
  26. server.onPatternAuthenticated("/raw_commands/:type", HTTP_ANY, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  27. server.onAuthenticated("/web", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success")); }, handleUpdateFile(WEB_INDEX_FILENAME));
  28. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  29. server.onAuthenticated("/system", HTTP_POST, [this]() { handleSystemPost(); });
  30. server.onAuthenticated("/firmware", HTTP_POST, [this]() { handleFirmwarePost(); }, [this]() { handleFirmwareUpload(); });
  31. // set up web socket server
  32. wsServer.onEvent(
  33. [this](uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  34. handleWsEvent(num, type, payload, length);
  35. }
  36. );
  37. wsServer.begin();
  38. server.begin();
  39. }
  40. void MiLightHttpServer::handleClient() {
  41. server.handleClient();
  42. wsServer.loop();
  43. }
  44. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  45. server.on(path, method, handler);
  46. }
  47. WiFiClient MiLightHttpServer::client() {
  48. return server.client();
  49. }
  50. void MiLightHttpServer::handleSystemPost() {
  51. DynamicJsonBuffer buffer;
  52. JsonObject& request = buffer.parse(server.arg("plain"));
  53. bool handled = false;
  54. if (request.containsKey("command")) {
  55. if (request["command"] == "restart") {
  56. Serial.println(F("Restarting..."));
  57. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  58. delay(100);
  59. ESP.restart();
  60. handled = true;
  61. } else if (request["command"] == "clear_wifi_config") {
  62. Serial.println(F("Resetting Wifi and then Restarting..."));
  63. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  64. delay(100);
  65. ESP.eraseConfig();
  66. delay(100);
  67. ESP.restart();
  68. handled = true;
  69. }
  70. }
  71. if (handled) {
  72. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  73. } else {
  74. server.send_P(400, TEXT_PLAIN, PSTR("{\"error\":\"Unhandled command\"}"));
  75. }
  76. }
  77. void MiLightHttpServer::serveSettings() {
  78. // Save first to set defaults
  79. settings.save();
  80. serveFile(SETTINGS_FILE, APPLICATION_JSON);
  81. }
  82. void MiLightHttpServer::applySettings(Settings& settings) {
  83. if (settings.hasAuthSettings()) {
  84. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  85. } else {
  86. server.disableAuthentication();
  87. }
  88. }
  89. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  90. this->settingsSavedHandler = handler;
  91. }
  92. void MiLightHttpServer::handleAbout() {
  93. // DynamicJsonBuffer buffer;
  94. // JsonObject& response = buffer.createObject();
  95. // response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  96. // response["variant"] = QUOTE(FIRMWARE_VARIANT);
  97. // response["free_heap"] = ESP.getFreeHeap();
  98. // response["arduino_version"] = ESP.getCoreVersion();
  99. // response["reset_reason"] = ESP.getResetReason();
  100. // String body;
  101. // response.printTo(body);
  102. server.send(200, APPLICATION_JSON, AboutStringHelper::generateAboutString());
  103. }
  104. void MiLightHttpServer::handleGetRadioConfigs() {
  105. DynamicJsonBuffer buffer;
  106. JsonArray& arr = buffer.createArray();
  107. for (size_t i = 0; i < MiLightRemoteConfig::NUM_REMOTES; i++) {
  108. const MiLightRemoteConfig* config = MiLightRemoteConfig::ALL_REMOTES[i];
  109. arr.add(config->name);
  110. }
  111. String body;
  112. arr.printTo(body);
  113. server.send(200, APPLICATION_JSON, body);
  114. }
  115. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  116. const char* filename,
  117. const char* contentType,
  118. const char* defaultText) {
  119. return [this, filename, contentType, defaultText]() {
  120. if (!serveFile(filename)) {
  121. if (defaultText) {
  122. server.send(200, contentType, defaultText);
  123. } else {
  124. server.send(404);
  125. }
  126. }
  127. };
  128. }
  129. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  130. if (SPIFFS.exists(file)) {
  131. File f = SPIFFS.open(file, "r");
  132. server.streamFile(f, contentType);
  133. f.close();
  134. return true;
  135. }
  136. return false;
  137. }
  138. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  139. return [this, filename]() {
  140. HTTPUpload& upload = server.upload();
  141. if (upload.status == UPLOAD_FILE_START) {
  142. updateFile = SPIFFS.open(filename, "w");
  143. } else if(upload.status == UPLOAD_FILE_WRITE){
  144. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  145. Serial.println(F("Error updating web file"));
  146. }
  147. } else if (upload.status == UPLOAD_FILE_END) {
  148. updateFile.close();
  149. }
  150. };
  151. }
  152. void MiLightHttpServer::handleUpdateSettings() {
  153. DynamicJsonBuffer buffer;
  154. const String& rawSettings = server.arg("plain");
  155. JsonObject& parsedSettings = buffer.parse(rawSettings);
  156. if (parsedSettings.success()) {
  157. settings.patch(parsedSettings);
  158. settings.save();
  159. this->applySettings(settings);
  160. if (this->settingsSavedHandler) {
  161. this->settingsSavedHandler();
  162. }
  163. server.send(200, APPLICATION_JSON, "true");
  164. Serial.println(F("Settings successfully updated"));
  165. } else {
  166. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  167. Serial.println(F("Settings failed to update; invalid JSON"));
  168. }
  169. }
  170. void MiLightHttpServer::handleUpdateSettingsPost() {
  171. Settings::load(settings);
  172. server.send_P(200, TEXT_PLAIN, PSTR("success."));
  173. }
  174. void MiLightHttpServer::handleFirmwarePost() {
  175. server.sendHeader("Connection", "close");
  176. server.sendHeader("Access-Control-Allow-Origin", "*");
  177. if (Update.hasError()) {
  178. server.send_P(
  179. 500,
  180. TEXT_PLAIN,
  181. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  182. );
  183. } else {
  184. server.send_P(
  185. 200,
  186. TEXT_PLAIN,
  187. PSTR("Success. Device will now reboot.")
  188. );
  189. }
  190. delay(1000);
  191. ESP.restart();
  192. }
  193. void MiLightHttpServer::handleFirmwareUpload() {
  194. HTTPUpload& upload = server.upload();
  195. if(upload.status == UPLOAD_FILE_START){
  196. WiFiUDP::stopAll();
  197. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  198. if(!Update.begin(maxSketchSpace)){//start with max available size
  199. Update.printError(Serial);
  200. }
  201. } else if(upload.status == UPLOAD_FILE_WRITE){
  202. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  203. Update.printError(Serial);
  204. }
  205. } else if(upload.status == UPLOAD_FILE_END){
  206. if(Update.end(true)){ //true to set the size to the current progress
  207. } else {
  208. Update.printError(Serial);
  209. }
  210. }
  211. yield();
  212. }
  213. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  214. bool available = false;
  215. bool listenAll = bindings == NULL;
  216. size_t configIx = 0;
  217. const MiLightRadioConfig* radioConfig = NULL;
  218. const MiLightRemoteConfig* remoteConfig = NULL;
  219. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  220. if (bindings != NULL) {
  221. String strType(bindings->get("type"));
  222. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromType(strType);
  223. milightClient->prepare(remoteConfig, 0, 0);
  224. radioConfig = &remoteConfig->radioConfig;
  225. }
  226. if (radioConfig == NULL && !listenAll) {
  227. server.send_P(400, TEXT_PLAIN, PSTR("Unknown device type supplied."));
  228. return;
  229. }
  230. while (remoteConfig == NULL) {
  231. if (!server.clientConnected()) {
  232. return;
  233. }
  234. if (listenAll) {
  235. radioConfig = &milightClient->switchRadio(configIx++ % milightClient->getNumRadios())->config();
  236. }
  237. if (milightClient->available()) {
  238. size_t packetLen = milightClient->read(packet);
  239. remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  240. *radioConfig,
  241. packet,
  242. packetLen
  243. );
  244. }
  245. yield();
  246. }
  247. char response[200];
  248. char* responseBuffer = response;
  249. responseBuffer += sprintf_P(
  250. responseBuffer,
  251. PSTR("\n%s packet received (%d bytes):\n"),
  252. remoteConfig->name.c_str(),
  253. remoteConfig->packetFormatter->getPacketLength()
  254. );
  255. remoteConfig->packetFormatter->format(packet, responseBuffer);
  256. server.send(200, "text/plain", response);
  257. }
  258. void MiLightHttpServer::sendGroupState(BulbId& bulbId, GroupState* state) {
  259. String body;
  260. StaticJsonBuffer<200> jsonBuffer;
  261. JsonObject& obj = jsonBuffer.createObject();
  262. if (state != NULL) {
  263. state->applyState(obj, bulbId, settings.groupStateFields, settings.numGroupStateFields);
  264. }
  265. obj.printTo(body);
  266. server.send(200, APPLICATION_JSON, body);
  267. }
  268. void MiLightHttpServer::handleGetGroup(const UrlTokenBindings* urlBindings) {
  269. const String _deviceId = urlBindings->get("device_id");
  270. uint8_t _groupId = atoi(urlBindings->get("group_id"));
  271. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(urlBindings->get("type"));
  272. if (_remoteType == NULL) {
  273. char buffer[40];
  274. sprintf_P(buffer, PSTR("Unknown device type\n"));
  275. server.send(400, TEXT_PLAIN, buffer);
  276. return;
  277. }
  278. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  279. GroupState* state = stateStore->get(bulbId);
  280. sendGroupState(bulbId, stateStore->get(bulbId));
  281. }
  282. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  283. DynamicJsonBuffer buffer;
  284. JsonObject& request = buffer.parse(server.arg("plain"));
  285. if (!request.success()) {
  286. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  287. return;
  288. }
  289. milightClient->setResendCount(
  290. settings.httpRepeatFactor * settings.packetRepeats
  291. );
  292. String _deviceIds = urlBindings->get("device_id");
  293. String _groupIds = urlBindings->get("group_id");
  294. String _remoteTypes = urlBindings->get("type");
  295. char deviceIds[_deviceIds.length()];
  296. char groupIds[_groupIds.length()];
  297. char remoteTypes[_remoteTypes.length()];
  298. strcpy(remoteTypes, _remoteTypes.c_str());
  299. strcpy(groupIds, _groupIds.c_str());
  300. strcpy(deviceIds, _deviceIds.c_str());
  301. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  302. TokenIterator groupIdItr(groupIds, _groupIds.length());
  303. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  304. BulbId foundBulbId;
  305. size_t groupCount = 0;
  306. while (remoteTypesItr.hasNext()) {
  307. const char* _remoteType = remoteTypesItr.nextToken();
  308. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  309. if (config == NULL) {
  310. char buffer[40];
  311. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  312. server.send(400, "text/plain", buffer);
  313. return;
  314. }
  315. deviceIdItr.reset();
  316. while (deviceIdItr.hasNext()) {
  317. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  318. groupIdItr.reset();
  319. while (groupIdItr.hasNext()) {
  320. const uint8_t groupId = atoi(groupIdItr.nextToken());
  321. milightClient->prepare(config, deviceId, groupId);
  322. handleRequest(request);
  323. foundBulbId = BulbId(deviceId, groupId, config->type);
  324. groupCount++;
  325. }
  326. }
  327. }
  328. if (groupCount == 1) {
  329. sendGroupState(foundBulbId, stateStore->get(foundBulbId));
  330. } else {
  331. server.send(200, APPLICATION_JSON, "true");
  332. }
  333. }
  334. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  335. milightClient->update(request);
  336. }
  337. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  338. DynamicJsonBuffer buffer;
  339. JsonObject& request = buffer.parse(server.arg("plain"));
  340. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bindings->get("type"));
  341. if (config == NULL) {
  342. char buffer[50];
  343. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  344. server.send(400, "text/plain", buffer);
  345. return;
  346. }
  347. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  348. const String& hexPacket = request["packet"];
  349. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  350. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  351. if (request.containsKey("num_repeats")) {
  352. numRepeats = request["num_repeats"];
  353. }
  354. milightClient->prepare(config, 0, 0);
  355. for (size_t i = 0; i < numRepeats; i++) {
  356. milightClient->write(packet);
  357. }
  358. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  359. }
  360. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  361. switch (type) {
  362. case WStype_DISCONNECTED:
  363. if (numWsClients > 0) {
  364. numWsClients--;
  365. }
  366. break;
  367. case WStype_CONNECTED:
  368. numWsClients++;
  369. break;
  370. }
  371. }
  372. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  373. if (numWsClients > 0) {
  374. size_t packetLen = config.packetFormatter->getPacketLength();
  375. char buffer[packetLen*3];
  376. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  377. char formattedPacket[200];
  378. config.packetFormatter->format(packet, formattedPacket);
  379. char responseBuffer[300];
  380. sprintf_P(
  381. responseBuffer,
  382. PSTR("\n%s packet received (%d bytes):\n%s"),
  383. config.name.c_str(),
  384. packetLen,
  385. formattedPacket
  386. );
  387. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  388. }
  389. }
  390. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  391. return [this, data, length]() {
  392. server.sendHeader("Content-Encoding", "gzip");
  393. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  394. server.send(200, "text/html", "");
  395. server.sendContent_P(data, length);
  396. server.sendContent("");
  397. server.client().stop();
  398. };
  399. }