MiLightHttpServer.cpp 15 KB

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