MiLightHttpServer.cpp 13 KB

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