MiLightHttpServer.cpp 9.4 KB

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