MiLightHttpServer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  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. // Wait for packet queue to flush out. State will not have been updated before that.
  262. // Bit hacky to call loop outside of main loop, but should be fine.
  263. while (packetSender->isSending()) {
  264. packetSender->loop();
  265. }
  266. JsonObject obj = response.json.to<JsonObject>();
  267. if (state != NULL) {
  268. state->applyState(obj, bulbId, settings.groupStateFields);
  269. state->debugState("test");
  270. }
  271. }
  272. void MiLightHttpServer::_handleGetGroup(BulbId bulbId, RequestContext& request) {
  273. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  274. }
  275. void MiLightHttpServer::handleGetGroupAlias(RequestContext& request) {
  276. const String alias = request.pathVariables.get("device_alias");
  277. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  278. if (it == settings.groupIdAliases.end()) {
  279. request.response.setCode(404);
  280. request.response.json[F("error")] = F("Device alias not found");
  281. return;
  282. }
  283. _handleGetGroup(it->second, request);
  284. }
  285. void MiLightHttpServer::handleGetGroup(RequestContext& request) {
  286. const String _deviceId = request.pathVariables.get("device_id");
  287. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  288. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  289. if (_remoteType == NULL) {
  290. char buffer[40];
  291. sprintf_P(buffer, PSTR("Unknown device type\n"));
  292. request.response.setCode(400);
  293. request.response.json["error"] = buffer;
  294. return;
  295. }
  296. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  297. _handleGetGroup(bulbId, request);
  298. }
  299. void MiLightHttpServer::handleDeleteGroup(RequestContext& request) {
  300. const String _deviceId = request.pathVariables.get("device_id");
  301. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  302. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  303. if (_remoteType == NULL) {
  304. char buffer[40];
  305. sprintf_P(buffer, PSTR("Unknown device type\n"));
  306. request.response.setCode(400);
  307. request.response.json["error"] = buffer;
  308. return;
  309. }
  310. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  311. _handleDeleteGroup(bulbId, request);
  312. }
  313. void MiLightHttpServer::handleDeleteGroupAlias(RequestContext& request) {
  314. const String alias = request.pathVariables.get("device_alias");
  315. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  316. if (it == settings.groupIdAliases.end()) {
  317. request.response.setCode(404);
  318. request.response.json[F("error")] = F("Device alias not found");
  319. return;
  320. }
  321. _handleDeleteGroup(it->second, request);
  322. }
  323. void MiLightHttpServer::_handleDeleteGroup(BulbId bulbId, RequestContext& request) {
  324. stateStore->clear(bulbId);
  325. if (groupDeletedHandler != NULL) {
  326. this->groupDeletedHandler(bulbId);
  327. }
  328. request.response.json["success"] = true;
  329. }
  330. void MiLightHttpServer::handleUpdateGroupAlias(RequestContext& request) {
  331. const String alias = request.pathVariables.get("device_alias");
  332. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  333. if (it == settings.groupIdAliases.end()) {
  334. request.response.setCode(404);
  335. request.response.json[F("error")] = F("Device alias not found");
  336. return;
  337. }
  338. BulbId& bulbId = it->second;
  339. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bulbId.deviceType);
  340. if (config == NULL) {
  341. char buffer[40];
  342. sprintf_P(buffer, PSTR("Unknown device type: %s"), bulbId.deviceType);
  343. request.response.setCode(400);
  344. request.response.json["error"] = buffer;
  345. return;
  346. }
  347. milightClient->prepare(config, bulbId.deviceId, bulbId.groupId);
  348. handleRequest(request.getJsonBody().as<JsonObject>());
  349. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  350. }
  351. void MiLightHttpServer::handleUpdateGroup(RequestContext& request) {
  352. JsonObject reqObj = request.getJsonBody().as<JsonObject>();
  353. String _deviceIds = request.pathVariables.get("device_id");
  354. String _groupIds = request.pathVariables.get("group_id");
  355. String _remoteTypes = request.pathVariables.get("type");
  356. char deviceIds[_deviceIds.length()];
  357. char groupIds[_groupIds.length()];
  358. char remoteTypes[_remoteTypes.length()];
  359. strcpy(remoteTypes, _remoteTypes.c_str());
  360. strcpy(groupIds, _groupIds.c_str());
  361. strcpy(deviceIds, _deviceIds.c_str());
  362. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  363. TokenIterator groupIdItr(groupIds, _groupIds.length());
  364. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  365. BulbId foundBulbId;
  366. size_t groupCount = 0;
  367. while (remoteTypesItr.hasNext()) {
  368. const char* _remoteType = remoteTypesItr.nextToken();
  369. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  370. if (config == NULL) {
  371. char buffer[40];
  372. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  373. request.response.setCode(400);
  374. request.response.json["error"] = buffer;
  375. return;
  376. }
  377. deviceIdItr.reset();
  378. while (deviceIdItr.hasNext()) {
  379. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  380. groupIdItr.reset();
  381. while (groupIdItr.hasNext()) {
  382. const uint8_t groupId = atoi(groupIdItr.nextToken());
  383. milightClient->prepare(config, deviceId, groupId);
  384. handleRequest(reqObj);
  385. foundBulbId = BulbId(deviceId, groupId, config->type);
  386. groupCount++;
  387. }
  388. }
  389. }
  390. if (groupCount == 1) {
  391. sendGroupState(foundBulbId, stateStore->get(foundBulbId), request.response);
  392. } else {
  393. request.response.json["success"] = true;
  394. }
  395. }
  396. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  397. milightClient->setRepeatsOverride(
  398. settings.httpRepeatFactor * settings.packetRepeats
  399. );
  400. milightClient->update(request);
  401. milightClient->clearRepeatsOverride();
  402. }
  403. void MiLightHttpServer::handleSendRaw(RequestContext& request) {
  404. JsonObject requestBody = request.getJsonBody().as<JsonObject>();
  405. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  406. if (config == NULL) {
  407. char buffer[50];
  408. sprintf_P(buffer, PSTR("Unknown device type: %s"), request.pathVariables.get("type"));
  409. request.response.setCode(400);
  410. request.response.json["error"] = buffer;
  411. return;
  412. }
  413. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  414. const String& hexPacket = requestBody["packet"];
  415. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  416. size_t numRepeats = settings.packetRepeats;
  417. if (requestBody.containsKey("num_repeats")) {
  418. numRepeats = requestBody["num_repeats"];
  419. }
  420. packetSender->enqueue(packet, config, numRepeats);
  421. // To make this response synchronous, wait for packet to be flushed
  422. while (packetSender->isSending()) {
  423. packetSender->loop();
  424. }
  425. request.response.json["success"] = true;
  426. }
  427. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  428. switch (type) {
  429. case WStype_DISCONNECTED:
  430. if (numWsClients > 0) {
  431. numWsClients--;
  432. }
  433. break;
  434. case WStype_CONNECTED:
  435. numWsClients++;
  436. break;
  437. default:
  438. Serial.printf_P(PSTR("Unhandled websocket event: %d\n"), static_cast<uint8_t>(type));
  439. break;
  440. }
  441. }
  442. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  443. if (numWsClients > 0) {
  444. size_t packetLen = config.packetFormatter->getPacketLength();
  445. char buffer[packetLen*3];
  446. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  447. char formattedPacket[200];
  448. config.packetFormatter->format(packet, formattedPacket);
  449. char responseBuffer[300];
  450. sprintf_P(
  451. responseBuffer,
  452. PSTR("\n%s packet received (%d bytes):\n%s"),
  453. config.name.c_str(),
  454. packetLen,
  455. formattedPacket
  456. );
  457. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  458. }
  459. }
  460. void MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  461. server.sendHeader("Content-Encoding", "gzip");
  462. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  463. server.send(200, "text/html", "");
  464. server.sendContent_P(data, length);
  465. server.sendContent("");
  466. server.client().stop();
  467. }