MiLightHttpServer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  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 <AboutHelper.h>
  10. #include <index.html.gz.h>
  11. using namespace std::placeholders;
  12. void MiLightHttpServer::begin() {
  13. // set up HTTP end points to serve
  14. server
  15. .buildHandler("/")
  16. .onSimple(HTTP_GET, std::bind(&MiLightHttpServer::handleServe_P, this, index_html_gz, index_html_gz_len));
  17. server
  18. .buildHandler("/settings")
  19. .on(HTTP_GET, std::bind(&MiLightHttpServer::serveSettings, this))
  20. .on(HTTP_PUT, std::bind(&MiLightHttpServer::handleUpdateSettings, this, _1))
  21. .on(
  22. HTTP_POST,
  23. std::bind(&MiLightHttpServer::handleUpdateSettingsPost, this, _1),
  24. std::bind(&MiLightHttpServer::handleUpdateFile, this, SETTINGS_FILE)
  25. );
  26. server
  27. .buildHandler("/remote_configs")
  28. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleGetRadioConfigs, this, _1));
  29. server
  30. .buildHandler("/gateway_traffic")
  31. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleListenGateway, this, _1));
  32. server
  33. .buildHandler("/gateway_traffic/:type")
  34. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleListenGateway, this, _1));
  35. server
  36. .buildHandler("/gateways/:device_id/:type/:group_id")
  37. .on(HTTP_PUT, std::bind(&MiLightHttpServer::handleUpdateGroup, this, _1))
  38. .on(HTTP_POST, std::bind(&MiLightHttpServer::handleUpdateGroup, this, _1))
  39. .on(HTTP_DELETE, std::bind(&MiLightHttpServer::handleDeleteGroup, this, _1))
  40. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleGetGroup, this, _1));
  41. server
  42. .buildHandler("/gateways/:device_alias")
  43. .on(HTTP_PUT, std::bind(&MiLightHttpServer::handleUpdateGroupAlias, this, _1))
  44. .on(HTTP_POST, std::bind(&MiLightHttpServer::handleUpdateGroupAlias, this, _1))
  45. .on(HTTP_DELETE, std::bind(&MiLightHttpServer::handleDeleteGroupAlias, this, _1))
  46. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleGetGroupAlias, this, _1));
  47. server
  48. .buildHandler("/raw_commands/:type")
  49. .on(HTTP_ANY, std::bind(&MiLightHttpServer::handleSendRaw, this, _1));
  50. server
  51. .buildHandler("/about")
  52. .on(HTTP_GET, std::bind(&MiLightHttpServer::handleAbout, this, _1));
  53. server
  54. .buildHandler("/system")
  55. .on(HTTP_POST, std::bind(&MiLightHttpServer::handleSystemPost, this, _1));
  56. server
  57. .buildHandler("/firmware")
  58. .handleOTA();
  59. server.clearBuilders();
  60. // set up web socket server
  61. wsServer.onEvent(
  62. [this](uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
  63. handleWsEvent(num, type, payload, length);
  64. }
  65. );
  66. wsServer.begin();
  67. server.begin();
  68. }
  69. void MiLightHttpServer::handleClient() {
  70. server.handleClient();
  71. wsServer.loop();
  72. }
  73. WiFiClient MiLightHttpServer::client() {
  74. return server.client();
  75. }
  76. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  77. server.on(path, method, handler);
  78. }
  79. void MiLightHttpServer::handleSystemPost(RequestContext& request) {
  80. JsonObject requestBody = request.getJsonBody().as<JsonObject>();
  81. bool handled = false;
  82. if (requestBody.containsKey("command")) {
  83. if (requestBody["command"] == "restart") {
  84. Serial.println(F("Restarting..."));
  85. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  86. delay(100);
  87. ESP.restart();
  88. handled = true;
  89. } else if (requestBody["command"] == "clear_wifi_config") {
  90. Serial.println(F("Resetting Wifi and then Restarting..."));
  91. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  92. delay(100);
  93. ESP.eraseConfig();
  94. delay(100);
  95. ESP.restart();
  96. handled = true;
  97. }
  98. }
  99. if (handled) {
  100. request.response.json["success"] = true;
  101. } else {
  102. request.response.json["success"] = false;
  103. request.response.json["error"] = "Unhandled command";
  104. request.response.setCode(400);
  105. }
  106. }
  107. void MiLightHttpServer::serveSettings() {
  108. // Save first to set defaults
  109. settings.save();
  110. serveFile(SETTINGS_FILE, APPLICATION_JSON);
  111. }
  112. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  113. this->settingsSavedHandler = handler;
  114. }
  115. void MiLightHttpServer::onGroupDeleted(GroupDeletedHandler handler) {
  116. this->groupDeletedHandler = handler;
  117. }
  118. void MiLightHttpServer::handleAbout(RequestContext& request) {
  119. AboutHelper::generateAboutObject(request.response.json);
  120. JsonObject queueStats = request.response.json.createNestedObject("queue_stats");
  121. queueStats[F("length")] = packetSender->queueLength();
  122. queueStats[F("dropped_packets")] = packetSender->droppedPackets();
  123. }
  124. void MiLightHttpServer::handleGetRadioConfigs(RequestContext& request) {
  125. JsonArray arr = request.response.json.to<JsonArray>();
  126. for (size_t i = 0; i < MiLightRemoteConfig::NUM_REMOTES; i++) {
  127. const MiLightRemoteConfig* config = MiLightRemoteConfig::ALL_REMOTES[i];
  128. arr.add(config->name);
  129. }
  130. }
  131. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  132. if (SPIFFS.exists(file)) {
  133. File f = SPIFFS.open(file, "r");
  134. server.streamFile(f, contentType);
  135. f.close();
  136. return true;
  137. }
  138. return false;
  139. }
  140. void MiLightHttpServer::handleUpdateFile(const char* filename) {
  141. HTTPUpload& upload = server.upload();
  142. if (upload.status == UPLOAD_FILE_START) {
  143. updateFile = SPIFFS.open(filename, "w");
  144. } else if(upload.status == UPLOAD_FILE_WRITE){
  145. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  146. Serial.println(F("Error updating web file"));
  147. }
  148. } else if (upload.status == UPLOAD_FILE_END) {
  149. updateFile.close();
  150. }
  151. }
  152. void MiLightHttpServer::handleUpdateSettings(RequestContext& request) {
  153. JsonObject parsedSettings = request.getJsonBody().as<JsonObject>();
  154. if (! parsedSettings.isNull()) {
  155. settings.patch(parsedSettings);
  156. settings.save();
  157. if (this->settingsSavedHandler) {
  158. this->settingsSavedHandler();
  159. }
  160. request.response.json["success"] = true;
  161. Serial.println(F("Settings successfully updated"));
  162. }
  163. }
  164. void MiLightHttpServer::handleUpdateSettingsPost(RequestContext& request) {
  165. Settings::load(settings);
  166. if (this->settingsSavedHandler) {
  167. this->settingsSavedHandler();
  168. }
  169. request.response.json["success"] = true;
  170. }
  171. void MiLightHttpServer::handleFirmwarePost() {
  172. server.sendHeader("Connection", "close");
  173. server.sendHeader("Access-Control-Allow-Origin", "*");
  174. if (Update.hasError()) {
  175. server.send_P(
  176. 500,
  177. TEXT_PLAIN,
  178. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  179. );
  180. } else {
  181. server.send_P(
  182. 200,
  183. TEXT_PLAIN,
  184. PSTR("Success. Device will now reboot.")
  185. );
  186. }
  187. delay(1000);
  188. ESP.restart();
  189. }
  190. void MiLightHttpServer::handleFirmwareUpload() {
  191. HTTPUpload& upload = server.upload();
  192. if(upload.status == UPLOAD_FILE_START){
  193. WiFiUDP::stopAll();
  194. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  195. if(!Update.begin(maxSketchSpace)){//start with max available size
  196. Update.printError(Serial);
  197. }
  198. } else if(upload.status == UPLOAD_FILE_WRITE){
  199. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  200. Update.printError(Serial);
  201. }
  202. } else if(upload.status == UPLOAD_FILE_END){
  203. if(Update.end(true)){ //true to set the size to the current progress
  204. } else {
  205. Update.printError(Serial);
  206. }
  207. }
  208. yield();
  209. }
  210. void MiLightHttpServer::handleListenGateway(RequestContext& request) {
  211. bool listenAll = !request.pathVariables.hasBinding("type");
  212. size_t configIx = 0;
  213. std::shared_ptr<MiLightRadio> radio = NULL;
  214. const MiLightRemoteConfig* remoteConfig = NULL;
  215. const MiLightRemoteConfig* tmpRemoteConfig = NULL;
  216. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  217. if (!listenAll) {
  218. String strType(request.pathVariables.get("type"));
  219. tmpRemoteConfig = MiLightRemoteConfig::fromType(strType);
  220. milightClient->prepare(tmpRemoteConfig, 0, 0);
  221. }
  222. if (tmpRemoteConfig == NULL && !listenAll) {
  223. request.response.setCode(400);
  224. request.response.json["error"] = "Unknown device type supplied";
  225. return;
  226. }
  227. if (tmpRemoteConfig != NULL) {
  228. radio = radios->switchRadio(tmpRemoteConfig);
  229. }
  230. while (remoteConfig == NULL) {
  231. if (!server.client().connected()) {
  232. return;
  233. }
  234. if (listenAll) {
  235. radio = radios->switchRadio(configIx++ % radios->getNumRadios());
  236. } else {
  237. radio->configure();
  238. }
  239. if (radios->available()) {
  240. size_t packetLen = radios->read(packet);
  241. remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  242. radio->config(),
  243. packet,
  244. packetLen
  245. );
  246. }
  247. yield();
  248. }
  249. char responseBody[200];
  250. char* responseBuffer = responseBody;
  251. responseBuffer += sprintf_P(
  252. responseBuffer,
  253. PSTR("\n%s packet received (%d bytes):\n"),
  254. remoteConfig->name.c_str(),
  255. remoteConfig->packetFormatter->getPacketLength()
  256. );
  257. remoteConfig->packetFormatter->format(packet, responseBuffer);
  258. request.response.json["packet_info"] = responseBody;
  259. }
  260. void MiLightHttpServer::sendGroupState(BulbId& bulbId, GroupState* state, RichHttp::Response& response) {
  261. bool blockOnQueue = server.arg("blockOnQueue").equalsIgnoreCase("true");
  262. // Wait for packet queue to flush out. State will not have been updated before that.
  263. // Bit hacky to call loop outside of main loop, but should be fine.
  264. while (blockOnQueue && packetSender->isSending()) {
  265. packetSender->loop();
  266. }
  267. JsonObject obj = response.json.to<JsonObject>();
  268. if (state != NULL) {
  269. state->applyState(obj, bulbId, settings.groupStateFields);
  270. state->debugState("test");
  271. }
  272. }
  273. void MiLightHttpServer::_handleGetGroup(BulbId bulbId, RequestContext& request) {
  274. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  275. }
  276. void MiLightHttpServer::handleGetGroupAlias(RequestContext& request) {
  277. const String alias = request.pathVariables.get("device_alias");
  278. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  279. if (it == settings.groupIdAliases.end()) {
  280. request.response.setCode(404);
  281. request.response.json[F("error")] = F("Device alias not found");
  282. return;
  283. }
  284. _handleGetGroup(it->second, request);
  285. }
  286. void MiLightHttpServer::handleGetGroup(RequestContext& request) {
  287. const String _deviceId = request.pathVariables.get("device_id");
  288. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  289. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  290. if (_remoteType == NULL) {
  291. char buffer[40];
  292. sprintf_P(buffer, PSTR("Unknown device type\n"));
  293. request.response.setCode(400);
  294. request.response.json["error"] = buffer;
  295. return;
  296. }
  297. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  298. _handleGetGroup(bulbId, request);
  299. }
  300. void MiLightHttpServer::handleDeleteGroup(RequestContext& request) {
  301. const String _deviceId = request.pathVariables.get("device_id");
  302. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  303. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  304. if (_remoteType == NULL) {
  305. char buffer[40];
  306. sprintf_P(buffer, PSTR("Unknown device type\n"));
  307. request.response.setCode(400);
  308. request.response.json["error"] = buffer;
  309. return;
  310. }
  311. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  312. _handleDeleteGroup(bulbId, request);
  313. }
  314. void MiLightHttpServer::handleDeleteGroupAlias(RequestContext& request) {
  315. const String alias = request.pathVariables.get("device_alias");
  316. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  317. if (it == settings.groupIdAliases.end()) {
  318. request.response.setCode(404);
  319. request.response.json[F("error")] = F("Device alias not found");
  320. return;
  321. }
  322. _handleDeleteGroup(it->second, request);
  323. }
  324. void MiLightHttpServer::_handleDeleteGroup(BulbId bulbId, RequestContext& request) {
  325. stateStore->clear(bulbId);
  326. if (groupDeletedHandler != NULL) {
  327. this->groupDeletedHandler(bulbId);
  328. }
  329. request.response.json["success"] = true;
  330. }
  331. void MiLightHttpServer::handleUpdateGroupAlias(RequestContext& request) {
  332. const String alias = request.pathVariables.get("device_alias");
  333. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  334. if (it == settings.groupIdAliases.end()) {
  335. request.response.setCode(404);
  336. request.response.json[F("error")] = F("Device alias not found");
  337. return;
  338. }
  339. BulbId& bulbId = it->second;
  340. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bulbId.deviceType);
  341. if (config == NULL) {
  342. char buffer[40];
  343. sprintf_P(buffer, PSTR("Unknown device type: %s"), bulbId.deviceType);
  344. request.response.setCode(400);
  345. request.response.json["error"] = buffer;
  346. return;
  347. }
  348. milightClient->prepare(config, bulbId.deviceId, bulbId.groupId);
  349. handleRequest(request.getJsonBody().as<JsonObject>());
  350. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  351. }
  352. void MiLightHttpServer::handleUpdateGroup(RequestContext& request) {
  353. JsonObject reqObj = request.getJsonBody().as<JsonObject>();
  354. String _deviceIds = request.pathVariables.get("device_id");
  355. String _groupIds = request.pathVariables.get("group_id");
  356. String _remoteTypes = request.pathVariables.get("type");
  357. char deviceIds[_deviceIds.length()];
  358. char groupIds[_groupIds.length()];
  359. char remoteTypes[_remoteTypes.length()];
  360. strcpy(remoteTypes, _remoteTypes.c_str());
  361. strcpy(groupIds, _groupIds.c_str());
  362. strcpy(deviceIds, _deviceIds.c_str());
  363. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  364. TokenIterator groupIdItr(groupIds, _groupIds.length());
  365. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  366. BulbId foundBulbId;
  367. size_t groupCount = 0;
  368. while (remoteTypesItr.hasNext()) {
  369. const char* _remoteType = remoteTypesItr.nextToken();
  370. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  371. if (config == NULL) {
  372. char buffer[40];
  373. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  374. request.response.setCode(400);
  375. request.response.json["error"] = buffer;
  376. return;
  377. }
  378. deviceIdItr.reset();
  379. while (deviceIdItr.hasNext()) {
  380. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  381. groupIdItr.reset();
  382. while (groupIdItr.hasNext()) {
  383. const uint8_t groupId = atoi(groupIdItr.nextToken());
  384. milightClient->prepare(config, deviceId, groupId);
  385. handleRequest(reqObj);
  386. foundBulbId = BulbId(deviceId, groupId, config->type);
  387. groupCount++;
  388. }
  389. }
  390. }
  391. if (groupCount == 1) {
  392. sendGroupState(foundBulbId, stateStore->get(foundBulbId), request.response);
  393. } else {
  394. request.response.json["success"] = true;
  395. }
  396. }
  397. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  398. milightClient->setRepeatsOverride(
  399. settings.httpRepeatFactor * settings.packetRepeats
  400. );
  401. milightClient->update(request);
  402. milightClient->clearRepeatsOverride();
  403. }
  404. void MiLightHttpServer::handleSendRaw(RequestContext& request) {
  405. JsonObject requestBody = request.getJsonBody().as<JsonObject>();
  406. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  407. if (config == NULL) {
  408. char buffer[50];
  409. sprintf_P(buffer, PSTR("Unknown device type: %s"), request.pathVariables.get("type"));
  410. request.response.setCode(400);
  411. request.response.json["error"] = buffer;
  412. return;
  413. }
  414. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  415. const String& hexPacket = requestBody["packet"];
  416. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  417. size_t numRepeats = settings.packetRepeats;
  418. if (requestBody.containsKey("num_repeats")) {
  419. numRepeats = requestBody["num_repeats"];
  420. }
  421. packetSender->enqueue(packet, config, numRepeats);
  422. // To make this response synchronous, wait for packet to be flushed
  423. while (packetSender->isSending()) {
  424. packetSender->loop();
  425. }
  426. request.response.json["success"] = true;
  427. }
  428. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  429. switch (type) {
  430. case WStype_DISCONNECTED:
  431. if (numWsClients > 0) {
  432. numWsClients--;
  433. }
  434. break;
  435. case WStype_CONNECTED:
  436. numWsClients++;
  437. break;
  438. default:
  439. Serial.printf_P(PSTR("Unhandled websocket event: %d\n"), static_cast<uint8_t>(type));
  440. break;
  441. }
  442. }
  443. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  444. if (numWsClients > 0) {
  445. size_t packetLen = config.packetFormatter->getPacketLength();
  446. char buffer[packetLen*3];
  447. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  448. char formattedPacket[200];
  449. config.packetFormatter->format(packet, formattedPacket);
  450. char responseBuffer[300];
  451. sprintf_P(
  452. responseBuffer,
  453. PSTR("\n%s packet received (%d bytes):\n%s"),
  454. config.name.c_str(),
  455. packetLen,
  456. formattedPacket
  457. );
  458. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  459. }
  460. }
  461. void MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  462. server.sendHeader("Content-Encoding", "gzip");
  463. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  464. server.send(200, "text/html", "");
  465. server.sendContent_P(data, length);
  466. server.sendContent("");
  467. server.client().stop();
  468. }