MiLightHttpServer.cpp 8.8 KB

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