MiLightHttpServer.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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.onAuthenticated("/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. this->applySettings(settings);
  173. if (this->settingsSavedHandler) {
  174. this->settingsSavedHandler();
  175. }
  176. server.send_P(200, TEXT_PLAIN, PSTR("success."));
  177. }
  178. void MiLightHttpServer::handleFirmwarePost() {
  179. server.sendHeader("Connection", "close");
  180. server.sendHeader("Access-Control-Allow-Origin", "*");
  181. if (Update.hasError()) {
  182. server.send_P(
  183. 500,
  184. TEXT_PLAIN,
  185. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  186. );
  187. } else {
  188. server.send_P(
  189. 200,
  190. TEXT_PLAIN,
  191. PSTR("Success. Device will now reboot.")
  192. );
  193. }
  194. delay(1000);
  195. ESP.restart();
  196. }
  197. void MiLightHttpServer::handleFirmwareUpload() {
  198. HTTPUpload& upload = server.upload();
  199. if(upload.status == UPLOAD_FILE_START){
  200. WiFiUDP::stopAll();
  201. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  202. if(!Update.begin(maxSketchSpace)){//start with max available size
  203. Update.printError(Serial);
  204. }
  205. } else if(upload.status == UPLOAD_FILE_WRITE){
  206. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  207. Update.printError(Serial);
  208. }
  209. } else if(upload.status == UPLOAD_FILE_END){
  210. if(Update.end(true)){ //true to set the size to the current progress
  211. } else {
  212. Update.printError(Serial);
  213. }
  214. }
  215. yield();
  216. }
  217. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  218. bool available = false;
  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. GroupState* state = stateStore->get(bulbId);
  284. sendGroupState(bulbId, stateStore->get(bulbId));
  285. }
  286. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  287. DynamicJsonBuffer buffer;
  288. JsonObject& request = buffer.parse(server.arg("plain"));
  289. if (!request.success()) {
  290. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  291. return;
  292. }
  293. milightClient->setResendCount(
  294. settings.httpRepeatFactor * settings.packetRepeats
  295. );
  296. String _deviceIds = urlBindings->get("device_id");
  297. String _groupIds = urlBindings->get("group_id");
  298. String _remoteTypes = urlBindings->get("type");
  299. char deviceIds[_deviceIds.length()];
  300. char groupIds[_groupIds.length()];
  301. char remoteTypes[_remoteTypes.length()];
  302. strcpy(remoteTypes, _remoteTypes.c_str());
  303. strcpy(groupIds, _groupIds.c_str());
  304. strcpy(deviceIds, _deviceIds.c_str());
  305. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  306. TokenIterator groupIdItr(groupIds, _groupIds.length());
  307. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  308. BulbId foundBulbId;
  309. size_t groupCount = 0;
  310. while (remoteTypesItr.hasNext()) {
  311. const char* _remoteType = remoteTypesItr.nextToken();
  312. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  313. if (config == NULL) {
  314. char buffer[40];
  315. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  316. server.send(400, "text/plain", buffer);
  317. return;
  318. }
  319. deviceIdItr.reset();
  320. while (deviceIdItr.hasNext()) {
  321. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  322. groupIdItr.reset();
  323. while (groupIdItr.hasNext()) {
  324. const uint8_t groupId = atoi(groupIdItr.nextToken());
  325. milightClient->prepare(config, deviceId, groupId);
  326. handleRequest(request);
  327. foundBulbId = BulbId(deviceId, groupId, config->type);
  328. groupCount++;
  329. }
  330. }
  331. }
  332. if (groupCount == 1) {
  333. sendGroupState(foundBulbId, stateStore->get(foundBulbId));
  334. } else {
  335. server.send(200, APPLICATION_JSON, "true");
  336. }
  337. }
  338. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  339. milightClient->update(request);
  340. }
  341. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  342. DynamicJsonBuffer buffer;
  343. JsonObject& request = buffer.parse(server.arg("plain"));
  344. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bindings->get("type"));
  345. if (config == NULL) {
  346. char buffer[50];
  347. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  348. server.send(400, "text/plain", buffer);
  349. return;
  350. }
  351. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  352. const String& hexPacket = request["packet"];
  353. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  354. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  355. if (request.containsKey("num_repeats")) {
  356. numRepeats = request["num_repeats"];
  357. }
  358. milightClient->prepare(config, 0, 0);
  359. for (size_t i = 0; i < numRepeats; i++) {
  360. milightClient->write(packet);
  361. }
  362. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  363. }
  364. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  365. switch (type) {
  366. case WStype_DISCONNECTED:
  367. if (numWsClients > 0) {
  368. numWsClients--;
  369. }
  370. break;
  371. case WStype_CONNECTED:
  372. numWsClients++;
  373. break;
  374. }
  375. }
  376. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  377. if (numWsClients > 0) {
  378. size_t packetLen = config.packetFormatter->getPacketLength();
  379. char buffer[packetLen*3];
  380. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  381. char formattedPacket[200];
  382. config.packetFormatter->format(packet, formattedPacket);
  383. char responseBuffer[300];
  384. sprintf_P(
  385. responseBuffer,
  386. PSTR("\n%s packet received (%d bytes):\n%s"),
  387. config.name.c_str(),
  388. packetLen,
  389. formattedPacket
  390. );
  391. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  392. }
  393. }
  394. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  395. return [this, data, length]() {
  396. server.sendHeader("Content-Encoding", "gzip");
  397. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  398. server.send(200, "text/html", "");
  399. server.sendContent_P(data, length);
  400. server.sendContent("");
  401. server.client().stop();
  402. };
  403. }