MiLightHttpServer.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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 MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[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. uint8_t configIx = 0;
  200. MiLightRadioConfig* currentConfig =
  201. listenAll
  202. ? MiLightRadioConfig::ALL_CONFIGS[0]
  203. : MiLightRadioConfig::fromString(bindings->get("type"));
  204. if (currentConfig == NULL && bindings != NULL) {
  205. String body = "Unknown device type: ";
  206. body += bindings->get("type");
  207. server.send(400, "text/plain", body);
  208. return;
  209. }
  210. while (!available) {
  211. if (!server.clientConnected()) {
  212. return;
  213. }
  214. if (listenAll) {
  215. currentConfig = MiLightRadioConfig::ALL_CONFIGS[
  216. configIx++ % MiLightRadioConfig::NUM_CONFIGS
  217. ];
  218. }
  219. milightClient->prepare(*currentConfig, 0, 0);
  220. if (milightClient->available()) {
  221. available = true;
  222. }
  223. yield();
  224. }
  225. uint8_t packet[currentConfig->getPacketLength()];
  226. milightClient->read(packet);
  227. char response[200];
  228. char* responseBuffer = response;
  229. responseBuffer += sprintf_P(
  230. responseBuffer,
  231. PSTR("\n%s packet received (%d bytes):\n"),
  232. currentConfig->name,
  233. sizeof(packet)
  234. );
  235. milightClient->formatPacket(packet, responseBuffer);
  236. server.send(200, "text/plain", response);
  237. }
  238. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  239. DynamicJsonBuffer buffer;
  240. JsonObject& request = buffer.parse(server.arg("plain"));
  241. if (!request.success()) {
  242. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  243. return;
  244. }
  245. milightClient->setResendCount(
  246. settings.httpRepeatFactor * settings.packetRepeats
  247. );
  248. String _deviceIds = urlBindings->get("device_id");
  249. String _groupIds = urlBindings->get("group_id");
  250. String _radioTypes = urlBindings->get("type");
  251. char deviceIds[_deviceIds.length()];
  252. char groupIds[_groupIds.length()];
  253. char radioTypes[_radioTypes.length()];
  254. strcpy(radioTypes, _radioTypes.c_str());
  255. strcpy(groupIds, _groupIds.c_str());
  256. strcpy(deviceIds, _deviceIds.c_str());
  257. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  258. TokenIterator groupIdItr(groupIds, _groupIds.length());
  259. TokenIterator radioTypesItr(radioTypes, _radioTypes.length());
  260. while (radioTypesItr.hasNext()) {
  261. const char* _radioType = radioTypesItr.nextToken();
  262. MiLightRadioConfig* config = MiLightRadioConfig::fromString(_radioType);
  263. if (config == NULL) {
  264. char buffer[40];
  265. sprintf_P(buffer, PSTR("Unknown device type: %s"), _radioType);
  266. server.send(400, "text/plain", buffer);
  267. return;
  268. }
  269. deviceIdItr.reset();
  270. while (deviceIdItr.hasNext()) {
  271. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  272. groupIdItr.reset();
  273. while (groupIdItr.hasNext()) {
  274. const uint8_t groupId = atoi(groupIdItr.nextToken());
  275. milightClient->prepare(*config, deviceId, groupId);
  276. handleRequest(request);
  277. }
  278. }
  279. }
  280. server.send(200, APPLICATION_JSON, "true");
  281. }
  282. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  283. milightClient->update(request);
  284. }
  285. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  286. DynamicJsonBuffer buffer;
  287. JsonObject& request = buffer.parse(server.arg("plain"));
  288. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  289. if (config == NULL) {
  290. char buffer[50];
  291. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  292. server.send(400, "text/plain", buffer);
  293. return;
  294. }
  295. uint8_t packet[config->getPacketLength()];
  296. const String& hexPacket = request["packet"];
  297. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  298. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  299. if (request.containsKey("num_repeats")) {
  300. numRepeats = request["num_repeats"];
  301. }
  302. milightClient->prepare(*config, 0, 0);
  303. for (size_t i = 0; i < numRepeats; i++) {
  304. milightClient->write(packet);
  305. }
  306. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  307. }
  308. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  309. switch (type) {
  310. case WStype_DISCONNECTED:
  311. if (numWsClients > 0) {
  312. numWsClients--;
  313. }
  314. break;
  315. case WStype_CONNECTED:
  316. numWsClients++;
  317. break;
  318. }
  319. }
  320. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRadioConfig& config) {
  321. if (numWsClients > 0) {
  322. size_t packetLen = config.packetFormatter->getPacketLength();
  323. char buffer[packetLen*3];
  324. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  325. char formattedPacket[200];
  326. config.packetFormatter->format(packet, formattedPacket);
  327. char responseBuffer[300];
  328. sprintf_P(
  329. responseBuffer,
  330. PSTR("\n%s packet received (%d bytes):\n%s"),
  331. config.name,
  332. sizeof(packet),
  333. formattedPacket
  334. );
  335. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  336. }
  337. }
  338. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  339. return [this, data, length]() {
  340. server.sendHeader("Content-Encoding", "gzip");
  341. server.sendHeader("Content-Length", String(length));
  342. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  343. server.send(200, "text/html", "");
  344. server.setContentLength(length);
  345. server.sendContent_P(data, length);
  346. server.client().stop();
  347. };
  348. }