MiLightHttpServer.cpp 14 KB

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