MiLightHttpServer.cpp 13 KB

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