MiLightHttpServer.cpp 10 KB

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