MiLightHttpServer.cpp 16 KB

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