MiLightHttpServer.cpp 12 KB

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