MiLightHttpServer.cpp 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 = milightClient->getRadioConfig(bindings->get("type"));
  116. while (!available) {
  117. if (!server.clientConnected()) {
  118. return;
  119. }
  120. if (milightClient->available(config.type)) {
  121. available = true;
  122. }
  123. yield();
  124. }
  125. uint8_t packet[config.packetLength];
  126. milightClient->read(static_cast<MiLightRadioType>(config.type), packet);
  127. String response = "Packet received (";
  128. response += String(sizeof(packet)) + " bytes)";
  129. response += ":\n";
  130. char ppBuffer[200];
  131. milightClient->formatPacket(config, packet, ppBuffer);
  132. response += String(ppBuffer);
  133. response += "\n\n";
  134. server.send(200, "text/plain", response);
  135. }
  136. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  137. DynamicJsonBuffer buffer;
  138. JsonObject& request = buffer.parse(server.arg("plain"));
  139. if (!request.success()) {
  140. server.send(400, "text/plain", "Invalid JSON");
  141. return;
  142. }
  143. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  144. const uint8_t groupId = urlBindings->get("group_id").toInt();
  145. const MiLightRadioType type = MiLightClient::getRadioType(urlBindings->get("type"));
  146. if (type == UNKNOWN) {
  147. String body = "Unknown device type: ";
  148. body += urlBindings->get("type");
  149. server.send(400, "text/plain", body);
  150. return;
  151. }
  152. milightClient->setResendCount(
  153. settings.httpRepeatFactor * settings.packetRepeats
  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. // CCT command work more effectively with a lower number of repeats it seems.
  189. milightClient->setResendCount(MILIGHT_DEFAULT_RESEND_COUNT);
  190. if (request["command"] == "level_up") {
  191. milightClient->increaseCctBrightness(deviceId, groupId);
  192. }
  193. if (request["command"] == "level_down") {
  194. milightClient->decreaseCctBrightness(deviceId, groupId);
  195. }
  196. if (request["command"] == "temperature_up") {
  197. milightClient->increaseTemperature(deviceId, groupId);
  198. }
  199. if (request["command"] == "temperature_down") {
  200. milightClient->decreaseTemperature(deviceId, groupId);
  201. }
  202. milightClient->setResendCount(settings.packetRepeats);
  203. }
  204. }
  205. milightClient->setResendCount(settings.packetRepeats);
  206. server.send(200, "application/json", "true");
  207. }
  208. void MiLightHttpServer::handleUpdateGateway(const UrlTokenBindings* urlBindings) {
  209. DynamicJsonBuffer buffer;
  210. JsonObject& request = buffer.parse(server.arg("plain"));
  211. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  212. const MiLightRadioType type = MiLightClient::getRadioType(urlBindings->get("type"));
  213. if (type == UNKNOWN) {
  214. String body = "Unknown device type: ";
  215. body += urlBindings->get("type");
  216. server.send(400, "text/plain", body);
  217. return;
  218. }
  219. milightClient->setResendCount(MILIGHT_DEFAULT_RESEND_COUNT);
  220. if (request.containsKey("status")) {
  221. if (request["status"] == "on") {
  222. milightClient->allOn(type, deviceId);
  223. } else if (request["status"] == "off") {
  224. milightClient->allOff(type, deviceId);
  225. }
  226. }
  227. server.send(200, "application/json", "true");
  228. }
  229. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  230. DynamicJsonBuffer buffer;
  231. JsonObject& request = buffer.parse(server.arg("plain"));
  232. MiLightRadioConfig config = milightClient->getRadioConfig(bindings->get("type"));
  233. uint8_t packet[config.packetLength];
  234. const String& hexPacket = request["packet"];
  235. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config.packetLength);
  236. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  237. if (request.containsKey("num_repeats")) {
  238. numRepeats = request["num_repeats"];
  239. }
  240. for (size_t i = 0; i < numRepeats; i++) {
  241. milightClient->getRadio(config.type)->write(packet, config.packetLength);
  242. }
  243. server.send(200, "text/plain", "true");
  244. }