MiLightHttpServer.cpp 15 KB

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