MiLightHttpServer.cpp 14 KB

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