MiLightHttpServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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 available = false;
  220. bool listenAll = bindings == NULL;
  221. size_t configIx = 0;
  222. const MiLightRadioConfig* radioConfig = NULL;
  223. const MiLightRemoteConfig* remoteConfig = NULL;
  224. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  225. if (bindings != NULL) {
  226. String strType(bindings->get("type"));
  227. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromType(strType);
  228. milightClient->prepare(remoteConfig, 0, 0);
  229. radioConfig = &remoteConfig->radioConfig;
  230. }
  231. if (radioConfig == NULL && !listenAll) {
  232. server.send_P(400, TEXT_PLAIN, PSTR("Unknown device type supplied."));
  233. return;
  234. }
  235. while (remoteConfig == NULL) {
  236. if (!server.clientConnected()) {
  237. return;
  238. }
  239. if (listenAll) {
  240. radioConfig = &milightClient->switchRadio(configIx++ % milightClient->getNumRadios())->config();
  241. }
  242. if (milightClient->available()) {
  243. size_t packetLen = milightClient->read(packet);
  244. remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  245. *radioConfig,
  246. packet,
  247. packetLen
  248. );
  249. }
  250. yield();
  251. }
  252. char response[200];
  253. char* responseBuffer = response;
  254. responseBuffer += sprintf_P(
  255. responseBuffer,
  256. PSTR("\n%s packet received (%d bytes):\n"),
  257. remoteConfig->name.c_str(),
  258. remoteConfig->packetFormatter->getPacketLength()
  259. );
  260. remoteConfig->packetFormatter->format(packet, responseBuffer);
  261. server.send(200, "text/plain", response);
  262. }
  263. void MiLightHttpServer::sendGroupState(BulbId& bulbId, GroupState* state) {
  264. String body;
  265. StaticJsonBuffer<200> jsonBuffer;
  266. JsonObject& obj = jsonBuffer.createObject();
  267. if (state != NULL) {
  268. state->applyState(obj, bulbId, settings.groupStateFields, settings.numGroupStateFields);
  269. }
  270. obj.printTo(body);
  271. server.send(200, APPLICATION_JSON, body);
  272. }
  273. void MiLightHttpServer::handleGetGroup(const UrlTokenBindings* urlBindings) {
  274. const String _deviceId = urlBindings->get("device_id");
  275. uint8_t _groupId = atoi(urlBindings->get("group_id"));
  276. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(urlBindings->get("type"));
  277. if (_remoteType == NULL) {
  278. char buffer[40];
  279. sprintf_P(buffer, PSTR("Unknown device type\n"));
  280. server.send(400, TEXT_PLAIN, buffer);
  281. return;
  282. }
  283. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  284. GroupState* state = stateStore->get(bulbId);
  285. sendGroupState(bulbId, stateStore->get(bulbId));
  286. }
  287. void MiLightHttpServer::handleDeleteGroup(const UrlTokenBindings* urlBindings) {
  288. const String _deviceId = urlBindings->get("device_id");
  289. uint8_t _groupId = atoi(urlBindings->get("group_id"));
  290. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(urlBindings->get("type"));
  291. if (_remoteType == NULL) {
  292. char buffer[40];
  293. sprintf_P(buffer, PSTR("Unknown device type\n"));
  294. server.send(400, TEXT_PLAIN, buffer);
  295. return;
  296. }
  297. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  298. stateStore->clear(bulbId);
  299. server.send_P(200, APPLICATION_JSON, PSTR("true"));
  300. }
  301. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  302. DynamicJsonBuffer buffer;
  303. JsonObject& request = buffer.parse(server.arg("plain"));
  304. if (!request.success()) {
  305. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  306. return;
  307. }
  308. milightClient->setResendCount(
  309. settings.httpRepeatFactor * settings.packetRepeats
  310. );
  311. String _deviceIds = urlBindings->get("device_id");
  312. String _groupIds = urlBindings->get("group_id");
  313. String _remoteTypes = urlBindings->get("type");
  314. char deviceIds[_deviceIds.length()];
  315. char groupIds[_groupIds.length()];
  316. char remoteTypes[_remoteTypes.length()];
  317. strcpy(remoteTypes, _remoteTypes.c_str());
  318. strcpy(groupIds, _groupIds.c_str());
  319. strcpy(deviceIds, _deviceIds.c_str());
  320. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  321. TokenIterator groupIdItr(groupIds, _groupIds.length());
  322. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  323. BulbId foundBulbId;
  324. size_t groupCount = 0;
  325. while (remoteTypesItr.hasNext()) {
  326. const char* _remoteType = remoteTypesItr.nextToken();
  327. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  328. if (config == NULL) {
  329. char buffer[40];
  330. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  331. server.send(400, "text/plain", buffer);
  332. return;
  333. }
  334. deviceIdItr.reset();
  335. while (deviceIdItr.hasNext()) {
  336. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  337. groupIdItr.reset();
  338. while (groupIdItr.hasNext()) {
  339. const uint8_t groupId = atoi(groupIdItr.nextToken());
  340. milightClient->prepare(config, deviceId, groupId);
  341. handleRequest(request);
  342. foundBulbId = BulbId(deviceId, groupId, config->type);
  343. groupCount++;
  344. }
  345. }
  346. }
  347. if (groupCount == 1) {
  348. sendGroupState(foundBulbId, stateStore->get(foundBulbId));
  349. } else {
  350. server.send(200, APPLICATION_JSON, "true");
  351. }
  352. }
  353. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  354. milightClient->update(request);
  355. }
  356. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  357. DynamicJsonBuffer buffer;
  358. JsonObject& request = buffer.parse(server.arg("plain"));
  359. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bindings->get("type"));
  360. if (config == NULL) {
  361. char buffer[50];
  362. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  363. server.send(400, "text/plain", buffer);
  364. return;
  365. }
  366. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  367. const String& hexPacket = request["packet"];
  368. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  369. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  370. if (request.containsKey("num_repeats")) {
  371. numRepeats = request["num_repeats"];
  372. }
  373. milightClient->prepare(config, 0, 0);
  374. for (size_t i = 0; i < numRepeats; i++) {
  375. milightClient->write(packet);
  376. }
  377. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  378. }
  379. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  380. switch (type) {
  381. case WStype_DISCONNECTED:
  382. if (numWsClients > 0) {
  383. numWsClients--;
  384. }
  385. break;
  386. case WStype_CONNECTED:
  387. numWsClients++;
  388. break;
  389. }
  390. }
  391. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  392. if (numWsClients > 0) {
  393. size_t packetLen = config.packetFormatter->getPacketLength();
  394. char buffer[packetLen*3];
  395. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  396. char formattedPacket[200];
  397. config.packetFormatter->format(packet, formattedPacket);
  398. char responseBuffer[300];
  399. sprintf_P(
  400. responseBuffer,
  401. PSTR("\n%s packet received (%d bytes):\n%s"),
  402. config.name.c_str(),
  403. packetLen,
  404. formattedPacket
  405. );
  406. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  407. }
  408. }
  409. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  410. return [this, data, length]() {
  411. server.sendHeader("Content-Encoding", "gzip");
  412. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  413. server.send(200, "text/html", "");
  414. server.sendContent_P(data, length);
  415. server.sendContent("");
  416. server.client().stop();
  417. };
  418. }