MiLightHttpServer.cpp 8.1 KB

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