MiLightHttpServer.cpp 8.6 KB

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