MiLightHttpServer.cpp 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. void MiLightHttpServer::begin() {
  8. applySettings(settings);
  9. server.on("/", HTTP_GET, handleServeFile(WEB_INDEX_FILENAME, "text/html"));
  10. server.on("/settings", HTTP_GET, handleServeFile(SETTINGS_FILE, "application/json"));
  11. server.on("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  12. server.on("/settings", HTTP_POST, [this]() { server.send(200, "text/plain", "success"); }, handleUpdateFile(SETTINGS_FILE));
  13. server.on("/radio_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  14. server.onPattern("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  15. server.onPattern("/gateways/:device_id/:type/:group_id", HTTP_PUT, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  16. server.onPattern("/gateways/:device_id/:type", HTTP_PUT, [this](const UrlTokenBindings* b) { handleUpdateGateway(b); });
  17. server.onPattern("/send_raw/:type", HTTP_PUT, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  18. server.on("/web", HTTP_POST, [this]() { server.send(200, "text/plain", "success"); }, handleUpdateFile(WEB_INDEX_FILENAME));
  19. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  20. server.on("/firmware", HTTP_POST,
  21. [this](){
  22. server.sendHeader("Connection", "close");
  23. server.sendHeader("Access-Control-Allow-Origin", "*");
  24. server.send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
  25. ESP.restart();
  26. },
  27. [this](){
  28. HTTPUpload& upload = server.upload();
  29. if(upload.status == UPLOAD_FILE_START){
  30. WiFiUDP::stopAll();
  31. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  32. if(!Update.begin(maxSketchSpace)){//start with max available size
  33. Update.printError(Serial);
  34. }
  35. } else if(upload.status == UPLOAD_FILE_WRITE){
  36. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  37. Update.printError(Serial);
  38. }
  39. } else if(upload.status == UPLOAD_FILE_END){
  40. if(Update.end(true)){ //true to set the size to the current progress
  41. } else {
  42. Update.printError(Serial);
  43. }
  44. }
  45. yield();
  46. }
  47. );
  48. server.begin();
  49. }
  50. void MiLightHttpServer::handleClient() {
  51. server.handleClient();
  52. }
  53. void MiLightHttpServer::applySettings(Settings& settings) {
  54. if (server.authenticationRequired() && !settings.hasAuthSettings()) {
  55. server.disableAuthentication();
  56. } else {
  57. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  58. }
  59. milightClient->setResendCount(settings.packetRepeats);
  60. }
  61. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  62. this->settingsSavedHandler = handler;
  63. }
  64. void MiLightHttpServer::handleAbout() {
  65. DynamicJsonBuffer buffer;
  66. JsonObject& response = buffer.createObject();
  67. response["version"] = MILIGHT_HUB_VERSION;
  68. response["variant"] = FIRMWARE_VARIANT;
  69. String body;
  70. response.printTo(body);
  71. server.send(200, "application", body);
  72. }
  73. void MiLightHttpServer::handleGetRadioConfigs() {
  74. DynamicJsonBuffer buffer;
  75. JsonArray& arr = buffer.createArray();
  76. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  77. const MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[i];
  78. arr.add(config->name);
  79. }
  80. String body;
  81. arr.printTo(body);
  82. server.send(200, "application/json", body);
  83. }
  84. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  85. const char* filename,
  86. const char* contentType,
  87. const char* defaultText) {
  88. return [this, filename, contentType, defaultText]() {
  89. if (!serveFile(filename)) {
  90. if (defaultText) {
  91. server.send(200, contentType, defaultText);
  92. } else {
  93. server.send(404);
  94. }
  95. }
  96. };
  97. }
  98. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  99. if (SPIFFS.exists(file)) {
  100. File f = SPIFFS.open(file, "r");
  101. server.send(200, contentType, f.readString());
  102. f.close();
  103. return true;
  104. }
  105. return false;
  106. }
  107. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  108. return [this, filename]() {
  109. HTTPUpload& upload = server.upload();
  110. if (upload.status == UPLOAD_FILE_START) {
  111. updateFile = SPIFFS.open(filename, "w");
  112. } else if(upload.status == UPLOAD_FILE_WRITE){
  113. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  114. Serial.println("Error updating web file");
  115. }
  116. } else if (upload.status == UPLOAD_FILE_END) {
  117. updateFile.close();
  118. }
  119. };
  120. }
  121. void MiLightHttpServer::handleUpdateSettings() {
  122. DynamicJsonBuffer buffer;
  123. const String& rawSettings = server.arg("plain");
  124. JsonObject& parsedSettings = buffer.parse(rawSettings);
  125. if (parsedSettings.success()) {
  126. settings.patch(parsedSettings);
  127. settings.save();
  128. this->applySettings(settings);
  129. this->settingsSavedHandler();
  130. server.send(200, "application/json", "true");
  131. } else {
  132. server.send(400, "application/json", "\"Invalid JSON\"");
  133. }
  134. }
  135. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  136. bool available = false;
  137. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  138. if (config == NULL) {
  139. String body = "Unknown device type: ";
  140. body += bindings->get("type");
  141. server.send(400, "text/plain", body);
  142. return;
  143. }
  144. milightClient->prepare(*config, 0, 0);
  145. while (!available) {
  146. if (!server.clientConnected()) {
  147. return;
  148. }
  149. if (milightClient->available()) {
  150. available = true;
  151. }
  152. yield();
  153. }
  154. uint8_t packet[config->getPacketLength()];
  155. milightClient->read(packet);
  156. String response = "Packet received (";
  157. response += String(sizeof(packet)) + " bytes)";
  158. response += ":\n";
  159. char ppBuffer[200];
  160. milightClient->formatPacket(packet, ppBuffer);
  161. response += String(ppBuffer);
  162. response += "\n\n";
  163. server.send(200, "text/plain", response);
  164. }
  165. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  166. DynamicJsonBuffer buffer;
  167. JsonObject& request = buffer.parse(server.arg("plain"));
  168. if (!request.success()) {
  169. server.send(400, "text/plain", "Invalid JSON");
  170. return;
  171. }
  172. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  173. const uint8_t groupId = urlBindings->get("group_id").toInt();
  174. MiLightRadioConfig* config = MiLightRadioConfig::fromString(urlBindings->get("type"));
  175. if (config == NULL) {
  176. String body = "Unknown device type: ";
  177. body += urlBindings->get("type");
  178. server.send(400, "text/plain", body);
  179. return;
  180. }
  181. milightClient->setResendCount(
  182. settings.httpRepeatFactor * settings.packetRepeats
  183. );
  184. milightClient->prepare(*config, deviceId, groupId);
  185. if (request.containsKey("status")) {
  186. const String& statusStr = request.get<String>("status");
  187. MiLightStatus status = (statusStr == "on" || statusStr == "true") ? ON : OFF;
  188. milightClient->updateStatus(status);
  189. }
  190. if (request.containsKey("command")) {
  191. if (request["command"] == "unpair") {
  192. milightClient->unpair();
  193. }
  194. if (request["command"] == "pair") {
  195. milightClient->pair();
  196. }
  197. if (request["command"] == "set_white") {
  198. milightClient->updateColorWhite();
  199. }
  200. if (request["command"] == "level_up") {
  201. milightClient->increaseBrightness();
  202. }
  203. if (request["command"] == "level_down") {
  204. milightClient->decreaseBrightness();
  205. }
  206. if (request["command"] == "temperature_up") {
  207. milightClient->increaseTemperature();
  208. }
  209. if (request["command"] == "temperature_down") {
  210. milightClient->decreaseTemperature();
  211. }
  212. if (request["command"] == "next_mode") {
  213. milightClient->nextMode();
  214. }
  215. if (request["command"] == "previous_mode") {
  216. milightClient->previousMode();
  217. }
  218. if (request["command"] == "mode_speed_down") {
  219. milightClient->modeSpeedDown();
  220. }
  221. if (request["command"] == "mode_speed_up") {
  222. milightClient->modeSpeedUp();
  223. }
  224. }
  225. if (request.containsKey("hue")) {
  226. milightClient->updateHue(request["hue"]);
  227. }
  228. if (request.containsKey("level")) {
  229. milightClient->updateBrightness(request["level"]);
  230. }
  231. if (request.containsKey("temperature")) {
  232. milightClient->updateTemperature(request["temperature"]);
  233. }
  234. if (request.containsKey("saturation")) {
  235. milightClient->updateSaturation(request["saturation"]);
  236. }
  237. if (request.containsKey("mode")) {
  238. milightClient->updateMode(request["mode"]);
  239. }
  240. milightClient->setResendCount(settings.packetRepeats);
  241. server.send(200, "application/json", "true");
  242. }
  243. void MiLightHttpServer::handleUpdateGateway(const UrlTokenBindings* urlBindings) {
  244. DynamicJsonBuffer buffer;
  245. JsonObject& request = buffer.parse(server.arg("plain"));
  246. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  247. MiLightRadioConfig* config = MiLightRadioConfig::fromString(urlBindings->get("type"));
  248. if (config == NULL) {
  249. String body = "Unknown device type: ";
  250. body += urlBindings->get("type");
  251. server.send(400, "text/plain", body);
  252. return;
  253. }
  254. milightClient->prepare(*config, deviceId, 0);
  255. if (request.containsKey("status")) {
  256. if (request["status"] == "on") {
  257. milightClient->updateStatus(ON);
  258. } else if (request["status"] == "off") {
  259. milightClient->updateStatus(OFF);
  260. }
  261. }
  262. server.send(200, "application/json", "true");
  263. }
  264. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  265. DynamicJsonBuffer buffer;
  266. JsonObject& request = buffer.parse(server.arg("plain"));
  267. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  268. if (config == NULL) {
  269. String body = "Unknown device type: ";
  270. body += bindings->get("type");
  271. server.send(400, "text/plain", body);
  272. return;
  273. }
  274. uint8_t packet[config->getPacketLength()];
  275. const String& hexPacket = request["packet"];
  276. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  277. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  278. if (request.containsKey("num_repeats")) {
  279. numRepeats = request["num_repeats"];
  280. }
  281. milightClient->prepare(*config, 0, 0);
  282. for (size_t i = 0; i < numRepeats; i++) {
  283. milightClient->write(packet);
  284. }
  285. server.send(200, "text/plain", "true");
  286. }