MiLightHttpServer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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. }
  121. void MiLightHttpServer::handleGetRadioConfigs(RequestContext& request) {
  122. JsonArray arr = request.response.json.to<JsonArray>();
  123. for (size_t i = 0; i < MiLightRemoteConfig::NUM_REMOTES; i++) {
  124. const MiLightRemoteConfig* config = MiLightRemoteConfig::ALL_REMOTES[i];
  125. arr.add(config->name);
  126. }
  127. }
  128. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  129. if (SPIFFS.exists(file)) {
  130. File f = SPIFFS.open(file, "r");
  131. server.streamFile(f, contentType);
  132. f.close();
  133. return true;
  134. }
  135. return false;
  136. }
  137. void MiLightHttpServer::handleUpdateFile(const char* filename) {
  138. HTTPUpload& upload = server.upload();
  139. if (upload.status == UPLOAD_FILE_START) {
  140. updateFile = SPIFFS.open(filename, "w");
  141. } else if(upload.status == UPLOAD_FILE_WRITE){
  142. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  143. Serial.println(F("Error updating web file"));
  144. }
  145. } else if (upload.status == UPLOAD_FILE_END) {
  146. updateFile.close();
  147. }
  148. }
  149. void MiLightHttpServer::handleUpdateSettings(RequestContext& request) {
  150. JsonObject parsedSettings = request.getJsonBody().as<JsonObject>();
  151. if (! parsedSettings.isNull()) {
  152. settings.patch(parsedSettings);
  153. settings.save();
  154. if (this->settingsSavedHandler) {
  155. this->settingsSavedHandler();
  156. }
  157. request.response.json["success"] = true;
  158. Serial.println(F("Settings successfully updated"));
  159. }
  160. }
  161. void MiLightHttpServer::handleUpdateSettingsPost(RequestContext& request) {
  162. Settings::load(settings);
  163. if (this->settingsSavedHandler) {
  164. this->settingsSavedHandler();
  165. }
  166. request.response.json["success"] = true;
  167. }
  168. void MiLightHttpServer::handleFirmwarePost() {
  169. server.sendHeader("Connection", "close");
  170. server.sendHeader("Access-Control-Allow-Origin", "*");
  171. if (Update.hasError()) {
  172. server.send_P(
  173. 500,
  174. TEXT_PLAIN,
  175. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  176. );
  177. } else {
  178. server.send_P(
  179. 200,
  180. TEXT_PLAIN,
  181. PSTR("Success. Device will now reboot.")
  182. );
  183. }
  184. delay(1000);
  185. ESP.restart();
  186. }
  187. void MiLightHttpServer::handleFirmwareUpload() {
  188. HTTPUpload& upload = server.upload();
  189. if(upload.status == UPLOAD_FILE_START){
  190. WiFiUDP::stopAll();
  191. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  192. if(!Update.begin(maxSketchSpace)){//start with max available size
  193. Update.printError(Serial);
  194. }
  195. } else if(upload.status == UPLOAD_FILE_WRITE){
  196. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  197. Update.printError(Serial);
  198. }
  199. } else if(upload.status == UPLOAD_FILE_END){
  200. if(Update.end(true)){ //true to set the size to the current progress
  201. } else {
  202. Update.printError(Serial);
  203. }
  204. }
  205. yield();
  206. }
  207. void MiLightHttpServer::handleListenGateway(RequestContext& request) {
  208. bool listenAll = !request.pathVariables.hasBinding("type");
  209. size_t configIx = 0;
  210. std::shared_ptr<MiLightRadio> radio = NULL;
  211. const MiLightRemoteConfig* remoteConfig = NULL;
  212. const MiLightRemoteConfig* tmpRemoteConfig = NULL;
  213. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  214. if (!listenAll) {
  215. String strType(request.pathVariables.get("type"));
  216. tmpRemoteConfig = MiLightRemoteConfig::fromType(strType);
  217. milightClient->prepare(tmpRemoteConfig, 0, 0);
  218. }
  219. if (tmpRemoteConfig == NULL && !listenAll) {
  220. request.response.setCode(400);
  221. request.response.json["error"] = "Unknown device type supplied";
  222. return;
  223. }
  224. if (tmpRemoteConfig != NULL) {
  225. radio = radios->switchRadio(tmpRemoteConfig);
  226. }
  227. while (remoteConfig == NULL) {
  228. if (!server.client().connected()) {
  229. return;
  230. }
  231. if (listenAll) {
  232. radio = radios->switchRadio(configIx++ % radios->getNumRadios());
  233. } else {
  234. radio->configure();
  235. }
  236. if (radios->available()) {
  237. size_t packetLen = radios->read(packet);
  238. remoteConfig = MiLightRemoteConfig::fromReceivedPacket(
  239. radio->config(),
  240. packet,
  241. packetLen
  242. );
  243. }
  244. yield();
  245. }
  246. char responseBody[200];
  247. char* responseBuffer = responseBody;
  248. responseBuffer += sprintf_P(
  249. responseBuffer,
  250. PSTR("\n%s packet received (%d bytes):\n"),
  251. remoteConfig->name.c_str(),
  252. remoteConfig->packetFormatter->getPacketLength()
  253. );
  254. remoteConfig->packetFormatter->format(packet, responseBuffer);
  255. request.response.json["packet_info"] = responseBody;
  256. }
  257. void MiLightHttpServer::sendGroupState(BulbId& bulbId, GroupState* state, RichHttp::Response& response) {
  258. // Wait for packet queue to flush out. State will not have been updated before that.
  259. // Bit hacky to call loop outside of main loop, but should be fine.
  260. while (packetSender->isSending()) {
  261. packetSender->loop();
  262. }
  263. JsonObject obj = response.json.to<JsonObject>();
  264. if (state != NULL) {
  265. state->applyState(obj, bulbId, settings.groupStateFields);
  266. state->debugState("test");
  267. }
  268. }
  269. void MiLightHttpServer::_handleGetGroup(BulbId bulbId, RequestContext& request) {
  270. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  271. }
  272. void MiLightHttpServer::handleGetGroupAlias(RequestContext& request) {
  273. const String alias = request.pathVariables.get("device_alias");
  274. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  275. if (it == settings.groupIdAliases.end()) {
  276. request.response.setCode(404);
  277. request.response.json[F("error")] = F("Device alias not found");
  278. return;
  279. }
  280. _handleGetGroup(it->second, request);
  281. }
  282. void MiLightHttpServer::handleGetGroup(RequestContext& request) {
  283. const String _deviceId = request.pathVariables.get("device_id");
  284. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  285. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  286. if (_remoteType == NULL) {
  287. char buffer[40];
  288. sprintf_P(buffer, PSTR("Unknown device type\n"));
  289. request.response.setCode(400);
  290. request.response.json["error"] = buffer;
  291. return;
  292. }
  293. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  294. _handleGetGroup(bulbId, request);
  295. }
  296. void MiLightHttpServer::handleDeleteGroup(RequestContext& request) {
  297. const String _deviceId = request.pathVariables.get("device_id");
  298. uint8_t _groupId = atoi(request.pathVariables.get("group_id"));
  299. const MiLightRemoteConfig* _remoteType = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  300. if (_remoteType == NULL) {
  301. char buffer[40];
  302. sprintf_P(buffer, PSTR("Unknown device type\n"));
  303. request.response.setCode(400);
  304. request.response.json["error"] = buffer;
  305. return;
  306. }
  307. BulbId bulbId(parseInt<uint16_t>(_deviceId), _groupId, _remoteType->type);
  308. _handleDeleteGroup(bulbId, request);
  309. }
  310. void MiLightHttpServer::handleDeleteGroupAlias(RequestContext& request) {
  311. const String alias = request.pathVariables.get("device_alias");
  312. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  313. if (it == settings.groupIdAliases.end()) {
  314. request.response.setCode(404);
  315. request.response.json[F("error")] = F("Device alias not found");
  316. return;
  317. }
  318. _handleDeleteGroup(it->second, request);
  319. }
  320. void MiLightHttpServer::_handleDeleteGroup(BulbId bulbId, RequestContext& request) {
  321. stateStore->clear(bulbId);
  322. if (groupDeletedHandler != NULL) {
  323. this->groupDeletedHandler(bulbId);
  324. }
  325. request.response.json["success"] = true;
  326. }
  327. void MiLightHttpServer::handleUpdateGroupAlias(RequestContext& request) {
  328. const String alias = request.pathVariables.get("device_alias");
  329. std::map<String, BulbId>::iterator it = settings.groupIdAliases.find(alias);
  330. if (it == settings.groupIdAliases.end()) {
  331. request.response.setCode(404);
  332. request.response.json[F("error")] = F("Device alias not found");
  333. return;
  334. }
  335. BulbId& bulbId = it->second;
  336. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(bulbId.deviceType);
  337. if (config == NULL) {
  338. char buffer[40];
  339. sprintf_P(buffer, PSTR("Unknown device type: %s"), bulbId.deviceType);
  340. request.response.setCode(400);
  341. request.response.json["error"] = buffer;
  342. return;
  343. }
  344. milightClient->prepare(config, bulbId.deviceId, bulbId.groupId);
  345. handleRequest(request.getJsonBody().as<JsonObject>());
  346. sendGroupState(bulbId, stateStore->get(bulbId), request.response);
  347. }
  348. void MiLightHttpServer::handleUpdateGroup(RequestContext& request) {
  349. JsonObject reqObj = request.getJsonBody().as<JsonObject>();
  350. String _deviceIds = request.pathVariables.get("device_id");
  351. String _groupIds = request.pathVariables.get("group_id");
  352. String _remoteTypes = request.pathVariables.get("type");
  353. char deviceIds[_deviceIds.length()];
  354. char groupIds[_groupIds.length()];
  355. char remoteTypes[_remoteTypes.length()];
  356. strcpy(remoteTypes, _remoteTypes.c_str());
  357. strcpy(groupIds, _groupIds.c_str());
  358. strcpy(deviceIds, _deviceIds.c_str());
  359. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  360. TokenIterator groupIdItr(groupIds, _groupIds.length());
  361. TokenIterator remoteTypesItr(remoteTypes, _remoteTypes.length());
  362. BulbId foundBulbId;
  363. size_t groupCount = 0;
  364. while (remoteTypesItr.hasNext()) {
  365. const char* _remoteType = remoteTypesItr.nextToken();
  366. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(_remoteType);
  367. if (config == NULL) {
  368. char buffer[40];
  369. sprintf_P(buffer, PSTR("Unknown device type: %s"), _remoteType);
  370. request.response.setCode(400);
  371. request.response.json["error"] = buffer;
  372. return;
  373. }
  374. deviceIdItr.reset();
  375. while (deviceIdItr.hasNext()) {
  376. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  377. groupIdItr.reset();
  378. while (groupIdItr.hasNext()) {
  379. const uint8_t groupId = atoi(groupIdItr.nextToken());
  380. milightClient->prepare(config, deviceId, groupId);
  381. handleRequest(reqObj);
  382. foundBulbId = BulbId(deviceId, groupId, config->type);
  383. groupCount++;
  384. }
  385. }
  386. }
  387. if (groupCount == 1) {
  388. sendGroupState(foundBulbId, stateStore->get(foundBulbId), request.response);
  389. } else {
  390. request.response.json["success"] = true;
  391. }
  392. }
  393. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  394. milightClient->setRepeatsOverride(
  395. settings.httpRepeatFactor * settings.packetRepeats
  396. );
  397. milightClient->update(request);
  398. milightClient->clearRepeatsOverride();
  399. }
  400. void MiLightHttpServer::handleSendRaw(RequestContext& request) {
  401. JsonObject requestBody = request.getJsonBody().as<JsonObject>();
  402. const MiLightRemoteConfig* config = MiLightRemoteConfig::fromType(request.pathVariables.get("type"));
  403. if (config == NULL) {
  404. char buffer[50];
  405. sprintf_P(buffer, PSTR("Unknown device type: %s"), request.pathVariables.get("type"));
  406. request.response.setCode(400);
  407. request.response.json["error"] = buffer;
  408. return;
  409. }
  410. uint8_t packet[MILIGHT_MAX_PACKET_LENGTH];
  411. const String& hexPacket = requestBody["packet"];
  412. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, MILIGHT_MAX_PACKET_LENGTH);
  413. size_t numRepeats = settings.packetRepeats;
  414. if (requestBody.containsKey("num_repeats")) {
  415. numRepeats = requestBody["num_repeats"];
  416. }
  417. packetSender->enqueue(packet, config, numRepeats);
  418. // To make this response synchronous, wait for packet to be flushed
  419. while (packetSender->isSending()) {
  420. packetSender->loop();
  421. }
  422. request.response.json["success"] = true;
  423. }
  424. void MiLightHttpServer::handleWsEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length) {
  425. switch (type) {
  426. case WStype_DISCONNECTED:
  427. if (numWsClients > 0) {
  428. numWsClients--;
  429. }
  430. break;
  431. case WStype_CONNECTED:
  432. numWsClients++;
  433. break;
  434. default:
  435. Serial.printf_P(PSTR("Unhandled websocket event: %d\n"), static_cast<uint8_t>(type));
  436. break;
  437. }
  438. }
  439. void MiLightHttpServer::handlePacketSent(uint8_t *packet, const MiLightRemoteConfig& config) {
  440. if (numWsClients > 0) {
  441. size_t packetLen = config.packetFormatter->getPacketLength();
  442. char buffer[packetLen*3];
  443. IntParsing::bytesToHexStr(packet, packetLen, buffer, packetLen*3);
  444. char formattedPacket[200];
  445. config.packetFormatter->format(packet, formattedPacket);
  446. char responseBuffer[300];
  447. sprintf_P(
  448. responseBuffer,
  449. PSTR("\n%s packet received (%d bytes):\n%s"),
  450. config.name.c_str(),
  451. packetLen,
  452. formattedPacket
  453. );
  454. wsServer.broadcastTXT(reinterpret_cast<uint8_t*>(responseBuffer));
  455. }
  456. }
  457. void MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  458. server.sendHeader("Content-Encoding", "gzip");
  459. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  460. server.send(200, "text/html", "");
  461. server.sendContent_P(data, length);
  462. server.sendContent("");
  463. server.client().stop();
  464. }