MiLightHttpServer.cpp 15 KB

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