MiLightHttpServer.cpp 12 KB

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