MiLightHttpServer.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  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.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(const UrlTokenBindings* bindings) {
  113. bool available = false;
  114. MiLightRadioConfig config = milightClient->getRadioConfig(bindings->get("type"));
  115. while (!available) {
  116. if (!server.clientConnected()) {
  117. return;
  118. }
  119. if (milightClient->available(config.type)) {
  120. available = true;
  121. }
  122. yield();
  123. }
  124. uint8_t packet[config.packetLength];
  125. milightClient->read(static_cast<MiLightRadioType>(config.type), packet);
  126. String response = "Packet received (";
  127. response += String(sizeof(packet)) + " bytes)";
  128. response += ":\n";
  129. char ppBuffer[200];
  130. milightClient->formatPacket(config, packet, ppBuffer);
  131. response += String(ppBuffer);
  132. response += "\n\n";
  133. server.send(200, "text/plain", response);
  134. }
  135. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  136. DynamicJsonBuffer buffer;
  137. JsonObject& request = buffer.parse(server.arg("plain"));
  138. if (!request.success()) {
  139. server.send(400, "text/plain", "Invalid JSON");
  140. return;
  141. }
  142. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  143. const uint8_t groupId = urlBindings->get("group_id").toInt();
  144. const MiLightRadioType type = MiLightClient::getRadioType(urlBindings->get("type"));
  145. if (type == UNKNOWN) {
  146. String body = "Unknown device type: ";
  147. body += urlBindings->get("type");
  148. server.send(400, "text/plain", body);
  149. return;
  150. }
  151. milightClient->setResendCount(
  152. settings.httpRepeatFactor * settings.packetRepeats
  153. );
  154. if (request.containsKey("status")) {
  155. const String& statusStr = request.get<String>("status");
  156. MiLightStatus status = (statusStr == "on" || statusStr == "true") ? ON : OFF;
  157. milightClient->updateStatus(type, deviceId, groupId, status);
  158. }
  159. if (request.containsKey("command")) {
  160. if (request["command"] == "unpair") {
  161. milightClient->unpair(type, deviceId, groupId);
  162. }
  163. if (request["command"] == "pair") {
  164. milightClient->pair(type, deviceId, groupId);
  165. }
  166. }
  167. if (type == RGBW) {
  168. if (request.containsKey("hue")) {
  169. milightClient->updateHue(deviceId, groupId, request["hue"]);
  170. }
  171. if (request.containsKey("level")) {
  172. milightClient->updateBrightness(deviceId, groupId, request["level"]);
  173. }
  174. if (request.containsKey("command")) {
  175. if (request["command"] == "set_white") {
  176. milightClient->updateColorWhite(deviceId, groupId);
  177. }
  178. }
  179. } else if (type == CCT) {
  180. if (request.containsKey("temperature")) {
  181. milightClient->updateTemperature(deviceId, groupId, request["temperature"]);
  182. }
  183. if (request.containsKey("level")) {
  184. milightClient->updateCctBrightness(deviceId, groupId, request["level"]);
  185. }
  186. if (request.containsKey("command")) {
  187. // CCT command work more effectively with a lower number of repeats it seems.
  188. milightClient->setResendCount(MILIGHT_DEFAULT_RESEND_COUNT);
  189. if (request["command"] == "level_up") {
  190. milightClient->increaseCctBrightness(deviceId, groupId);
  191. }
  192. if (request["command"] == "level_down") {
  193. milightClient->decreaseCctBrightness(deviceId, groupId);
  194. }
  195. if (request["command"] == "temperature_up") {
  196. milightClient->increaseTemperature(deviceId, groupId);
  197. }
  198. if (request["command"] == "temperature_down") {
  199. milightClient->decreaseTemperature(deviceId, groupId);
  200. }
  201. milightClient->setResendCount(settings.packetRepeats);
  202. }
  203. }
  204. milightClient->setResendCount(settings.packetRepeats);
  205. server.send(200, "application/json", "true");
  206. }
  207. void MiLightHttpServer::handleUpdateGateway(const UrlTokenBindings* urlBindings) {
  208. DynamicJsonBuffer buffer;
  209. JsonObject& request = buffer.parse(server.arg("plain"));
  210. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  211. const MiLightRadioType type = MiLightClient::getRadioType(urlBindings->get("type"));
  212. if (type == UNKNOWN) {
  213. String body = "Unknown device type: ";
  214. body += urlBindings->get("type");
  215. server.send(400, "text/plain", body);
  216. return;
  217. }
  218. milightClient->setResendCount(MILIGHT_DEFAULT_RESEND_COUNT);
  219. if (request.containsKey("status")) {
  220. if (request["status"] == "on") {
  221. milightClient->allOn(type, deviceId);
  222. } else if (request["status"] == "off") {
  223. milightClient->allOff(type, deviceId);
  224. }
  225. }
  226. server.send(200, "application/json", "true");
  227. }