MiLightHttpServer.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471
  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, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success.")); }, 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::serveSettings() {
  113. // Save first to set defaults
  114. settings.save();
  115. serveFile(SETTINGS_FILE, APPLICATION_JSON);
  116. }
  117. void MiLightHttpServer::applySettings(Settings& settings) {
  118. if (settings.hasAuthSettings()) {
  119. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  120. } else {
  121. server.disableAuthentication();
  122. }
  123. }
  124. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  125. this->settingsSavedHandler = handler;
  126. }
  127. void MiLightHttpServer::handleAbout() {
  128. DynamicJsonBuffer buffer;
  129. JsonObject& response = buffer.createObject();
  130. response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  131. response["variant"] = QUOTE(FIRMWARE_VARIANT);
  132. response["free_heap"] = ESP.getFreeHeap();
  133. response["arduino_version"] = ESP.getCoreVersion();
  134. response["reset_reason"] = ESP.getResetReason();
  135. String body;
  136. response.printTo(body);
  137. server.send(200, APPLICATION_JSON, body);
  138. }
  139. void MiLightHttpServer::handleGetRadioConfigs() {
  140. DynamicJsonBuffer buffer;
  141. JsonArray& arr = buffer.createArray();
  142. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  143. const MiLightRemoteConfig* config = MiLightRemoteConfig::ALL_REMOTES[i];
  144. arr.add(config->name);
  145. }
  146. String body;
  147. arr.printTo(body);
  148. server.send(200, APPLICATION_JSON, body);
  149. }
  150. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  151. const char* filename,
  152. const char* contentType,
  153. const char* defaultText) {
  154. return [this, filename, contentType, defaultText]() {
  155. if (!serveFile(filename)) {
  156. if (defaultText) {
  157. server.send(200, contentType, defaultText);
  158. } else {
  159. server.send(404);
  160. }
  161. }
  162. };
  163. }
  164. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  165. if (SPIFFS.exists(file)) {
  166. File f = SPIFFS.open(file, "r");
  167. server.streamFile(f, contentType);
  168. f.close();
  169. return true;
  170. }
  171. return false;
  172. }
  173. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  174. return [this, filename]() {
  175. HTTPUpload& upload = server.upload();
  176. if (upload.status == UPLOAD_FILE_START) {
  177. updateFile = SPIFFS.open(filename, "w");
  178. } else if(upload.status == UPLOAD_FILE_WRITE){
  179. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  180. Serial.println(F("Error updating web file"));
  181. }
  182. } else if (upload.status == UPLOAD_FILE_END) {
  183. updateFile.close();
  184. }
  185. };
  186. }
  187. void MiLightHttpServer::handleUpdateSettings() {
  188. DynamicJsonBuffer buffer;
  189. const String& rawSettings = server.arg("plain");
  190. JsonObject& parsedSettings = buffer.parse(rawSettings);
  191. if (parsedSettings.success()) {
  192. settings.patch(parsedSettings);
  193. settings.save();
  194. this->applySettings(settings);
  195. this->settingsSavedHandler();
  196. server.send(200, APPLICATION_JSON, "true");
  197. } else {
  198. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  199. }
  200. }
  201. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  202. bool available = false;
  203. bool listenAll = bindings == NULL;
  204. size_t configIx = 0;
  205. const MiLightRadioConfig* radioConfig = NULL;
  206. if (bindings != NULL) {
  207. String strType(bindings->get("type"));
  208. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromType(strType);
  209. milightClient->prepare(remoteConfig, 0, 0);
  210. radioConfig = &remoteConfig->radioConfig;
  211. }
  212. if (radioConfig == NULL && !listenAll) {
  213. server.send_P(400, TEXT_PLAIN, PSTR("Unknown device type supplied."));
  214. return;
  215. }
  216. while (!available) {
  217. if (!server.clientConnected()) {
  218. return;
  219. }
  220. if (listenAll) {
  221. radioConfig = &milightClient->switchRadio(configIx++ % milightClient->getNumRadios())->config();
  222. }
  223. if (milightClient->available()) {
  224. available = true;
  225. }
  226. yield();
  227. }
  228. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  229. size_t packetLen = milightClient->read(packet);
  230. const MiLightRemoteConfig* remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  231. *radioConfig,
  232. packet,
  233. packetLen
  234. );
  235. char response[200];
  236. char* responseBuffer = response;
  237. responseBuffer += sprintf_P(
  238. responseBuffer,
  239. PSTR("\n%s packet received (%d bytes):\n"),
  240. remoteConfig->name.c_str(),
  241. packetLen
  242. );
  243. remoteConfig->packetFormatter->format(packet, responseBuffer);
  244. server.send(200, "text/plain", response);
  245. }
  246. void MiLightHttpServer::sendGroupState(GroupState &state) {
  247. String body;
  248. StaticJsonBuffer<200> jsonBuffer;
  249. JsonObject& obj = jsonBuffer.createObject();
  250. state.applyState(obj);
  251. obj.printTo(body);
  252. server.send(200, APPLICATION_JSON, body);
  253. }
  254. void MiLightHttpServer::handleGetGroup(const UrlTokenBindings* urlBindings) {
  255. const String _deviceId = urlBindings->get("device_id");
  256. uint8_t _groupId = atoi(urlBindings->get("group_id"));
  257. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(urlBindings->get("type"));
  258. if (_remoteType == NULL) {
  259. char buffer[40];
  260. sprintf_P(buffer, PSTR("Unknown device type\n"));
  261. server.send(400, TEXT_PLAIN, buffer);
  262. return;
  263. }
  264. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  265. GroupState& state = stateStore.get(bulbId);
  266. sendGroupState(stateStore.get(bulbId));
  267. }
  268. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  269. DynamicJsonBuffer buffer;
  270. JsonObject& request = buffer.parse(server.arg("plain"));
  271. if (!request.success()) {
  272. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  273. return;
  274. }
  275. milightClient->setResendCount(
  276. settings.httpRepeatFactor * settings.packetRepeats
  277. );
  278. String _deviceIds = urlBindings->get("device_id");
  279. String _groupIds = urlBindings->get("group_id");
  280. String _remoteTypes = urlBindings->get("type");
  281. char deviceIds[_deviceIds.length()];
  282. char groupIds[_groupIds.length()];
  283. char remoteTypes[_remoteTypes.length()];
  284. strcpy(remoteTypes, _remoteTypes.c_str());
  285. strcpy(groupIds, _groupIds.c_str());
  286. strcpy(deviceIds, _deviceIds.c_str());
  287. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  288. TokenIterator groupIdItr(groupIds, _groupIds.length());
  289. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  290. BulbId foundBulbId;
  291. size_t groupCount = 0;
  292. while (remoteTypesItr.hasNext()) {
  293. const char* _remoteType = remoteTypesItr.nextToken();
  294. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  295. if (config == NULL) {
  296. char buffer[40];
  297. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  298. server.send(400, "text/plain", buffer);
  299. return;
  300. }
  301. deviceIdItr.reset();
  302. while (deviceIdItr.hasNext()) {
  303. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  304. groupIdItr.reset();
  305. while (groupIdItr.hasNext()) {
  306. const uint8_t groupId = atoi(groupIdItr.nextToken());
  307. milightClient->prepare(config, deviceId, groupId);
  308. handleRequest(request);
  309. foundBulbId = BulbId(deviceId, groupId, config->type);
  310. groupCount++;
  311. }
  312. }
  313. }
  314. if (groupCount == 1) {
  315. sendGroupState(stateStore.get(foundBulbId));
  316. } else {
  317. server.send(200, APPLICATION_JSON, "true");
  318. }
  319. }
  320. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  321. milightClient->update(request);
  322. }
  323. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  324. DynamicJsonBuffer buffer;
  325. JsonObject& request = buffer.parse(server.arg("plain"));
  326. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bindings->get("type"));
  327. if (config == NULL) {
  328. char buffer[50];
  329. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  330. server.send(400, "text/plain", buffer);
  331. return;
  332. }
  333. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  334. const String& hexPacket = request["packet"];
  335. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  336. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  337. if (request.containsKey("num_repeats")) {
  338. numRepeats = request["num_repeats"];
  339. }
  340. milightClient->prepare(config, 0, 0);
  341. for (size_t i = 0; i < numRepeats; i++) {
  342. milightClient->write(packet);
  343. }
  344. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  345. }
  346. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  347. switch (type) {
  348. case WStype_DISCONNECTED:
  349. if (numWsClients > 0) {
  350. numWsClients--;
  351. }
  352. break;
  353. case WStype_CONNECTED:
  354. numWsClients++;
  355. break;
  356. }
  357. }
  358. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  359. if (numWsClients > 0) {
  360. size_t packetLen = config.packetFormatter->getPacketLength();
  361. char buffer[packetLen*3];
  362. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  363. char formattedPacket[200];
  364. config.packetFormatter->format(packet, formattedPacket);
  365. char responseBuffer[300];
  366. sprintf_P(
  367. responseBuffer,
  368. PSTR("\n%s packet received (%d bytes):\n%s"),
  369. config.name.c_str(),
  370. packetLen,
  371. formattedPacket
  372. );
  373. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  374. }
  375. }
  376. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  377. return [this, data, length]() {
  378. server.sendHeader("Content-Encoding", "gzip");
  379. server.sendHeader("Content-Length", String(length));
  380. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  381. server.send(200, "text/html", "");
  382. server.setContentLength(length);
  383. server.sendContent_P(data, length);
  384. server.client().stop();
  385. };
  386. }