MiLightHttpServer.cpp 20 KB

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