MiLightHttpServer.cpp 12 KB

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