MiLightHttpServer.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. #include <string.h>
  8. #include <TokenIterator.h>
  9. #include <index.html.gz.h>
  10. void MiLightHttpServer::begin() {
  11. applySettings(settings);
  12. server.on("/", HTTP_GET, handleServe_P(index_html_gz, index_html_gz_len));
  13. server.on("/settings", HTTP_GET, handleServeFile(SETTINGS_FILE, APPLICATION_JSON));
  14. server.on("/settings", HTTP_PUT, [this]() { handleUpdateSettings(); });
  15. server.on("/settings", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success. rebooting")); ESP.restart(); }, handleUpdateFile(SETTINGS_FILE));
  16. server.on("/radio_configs", HTTP_GET, [this]() { handleGetRadioConfigs(); });
  17. server.on("/gateway_traffic", HTTP_GET, [this]() { handleListenGateway(NULL); });
  18. server.onPattern("/gateway_traffic/:type", HTTP_GET, [this](const UrlTokenBindings* b) { handleListenGateway(b); });
  19. server.onPattern("/gateways/:device_id/:type/:group_id", HTTP_ANY, [this](const UrlTokenBindings* b) { handleUpdateGroup(b); });
  20. server.onPattern("/raw_commands/:type", HTTP_ANY, [this](const UrlTokenBindings* b) { handleSendRaw(b); });
  21. server.on("/web", HTTP_POST, [this]() { server.send_P(200, TEXT_PLAIN, PSTR("success")); }, handleUpdateFile(WEB_INDEX_FILENAME));
  22. server.on("/about", HTTP_GET, [this]() { handleAbout(); });
  23. server.on("/system", HTTP_POST, [this]() { handleSystemPost(); });
  24. server.on("/firmware", HTTP_POST,
  25. [this](){
  26. server.sendHeader("Connection", "close");
  27. server.sendHeader("Access-Control-Allow-Origin", "*");
  28. if (Update.hasError()) {
  29. server.send_P(
  30. 500,
  31. TEXT_PLAIN,
  32. PSTR("Failed updating firmware. Check serial logs for more information. You may need to re-flash the device.")
  33. );
  34. } else {
  35. server.send_P(
  36. 200,
  37. TEXT_PLAIN,
  38. PSTR("Success. Device will now reboot.")
  39. );
  40. }
  41. ESP.restart();
  42. },
  43. [this](){
  44. HTTPUpload& upload = server.upload();
  45. if(upload.status == UPLOAD_FILE_START){
  46. WiFiUDP::stopAll();
  47. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  48. if(!Update.begin(maxSketchSpace)){//start with max available size
  49. Update.printError(Serial);
  50. }
  51. } else if(upload.status == UPLOAD_FILE_WRITE){
  52. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  53. Update.printError(Serial);
  54. }
  55. } else if(upload.status == UPLOAD_FILE_END){
  56. if(Update.end(true)){ //true to set the size to the current progress
  57. } else {
  58. Update.printError(Serial);
  59. }
  60. }
  61. yield();
  62. }
  63. );
  64. server.begin();
  65. }
  66. void MiLightHttpServer::handleClient() {
  67. server.handleClient();
  68. }
  69. void MiLightHttpServer::on(const char* path, HTTPMethod method, ESP8266WebServer::THandlerFunction handler) {
  70. server.on(path, method, handler);
  71. }
  72. WiFiClient MiLightHttpServer::client() {
  73. return server.client();
  74. }
  75. void MiLightHttpServer::handleSystemPost() {
  76. DynamicJsonBuffer buffer;
  77. JsonObject& request = buffer.parse(server.arg("plain"));
  78. bool handled = false;
  79. if (request.containsKey("command")) {
  80. if (request["command"] == "restart") {
  81. Serial.println(F("Restarting..."));
  82. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  83. delay(100);
  84. ESP.restart();
  85. handled = true;
  86. } else if (request["command"] == "clear_wifi_config") {
  87. Serial.println(F("Resetting Wifi and then Restarting..."));
  88. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  89. delay(100);
  90. ESP.eraseConfig();
  91. delay(100);
  92. ESP.restart();
  93. handled = true;
  94. }
  95. }
  96. if (handled) {
  97. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  98. } else {
  99. server.send_P(400, TEXT_PLAIN, PSTR("{\"error\":\"Unhandled command\"}"));
  100. }
  101. }
  102. void MiLightHttpServer::applySettings(Settings& settings) {
  103. if (settings.hasAuthSettings()) {
  104. server.requireAuthentication(settings.adminUsername, settings.adminPassword);
  105. } else {
  106. server.disableAuthentication();
  107. }
  108. milightClient->setResendCount(settings.packetRepeats);
  109. }
  110. void MiLightHttpServer::onSettingsSaved(SettingsSavedHandler handler) {
  111. this->settingsSavedHandler = handler;
  112. }
  113. void MiLightHttpServer::handleAbout() {
  114. DynamicJsonBuffer buffer;
  115. JsonObject& response = buffer.createObject();
  116. response["version"] = QUOTE(MILIGHT_HUB_VERSION);
  117. response["variant"] = QUOTE(FIRMWARE_VARIANT);
  118. response["free_heap"] = ESP.getFreeHeap();
  119. response["arduino_version"] = ESP.getCoreVersion();
  120. response["reset_reason"] = ESP.getResetReason();
  121. String body;
  122. response.printTo(body);
  123. server.send(200, APPLICATION_JSON, body);
  124. }
  125. void MiLightHttpServer::handleGetRadioConfigs() {
  126. DynamicJsonBuffer buffer;
  127. JsonArray& arr = buffer.createArray();
  128. for (size_t i = 0; i < MiLightRadioConfig::NUM_CONFIGS; i++) {
  129. const MiLightRadioConfig* config = MiLightRadioConfig::ALL_CONFIGS[i];
  130. arr.add(config->name);
  131. }
  132. String body;
  133. arr.printTo(body);
  134. server.send(200, APPLICATION_JSON, body);
  135. }
  136. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServeFile(
  137. const char* filename,
  138. const char* contentType,
  139. const char* defaultText) {
  140. return [this, filename, contentType, defaultText]() {
  141. if (!serveFile(filename)) {
  142. if (defaultText) {
  143. server.send(200, contentType, defaultText);
  144. } else {
  145. server.send(404);
  146. }
  147. }
  148. };
  149. }
  150. bool MiLightHttpServer::serveFile(const char* file, const char* contentType) {
  151. if (SPIFFS.exists(file)) {
  152. File f = SPIFFS.open(file, "r");
  153. server.streamFile(f, contentType);
  154. f.close();
  155. return true;
  156. }
  157. return false;
  158. }
  159. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleUpdateFile(const char* filename) {
  160. return [this, filename]() {
  161. HTTPUpload& upload = server.upload();
  162. if (upload.status == UPLOAD_FILE_START) {
  163. updateFile = SPIFFS.open(filename, "w");
  164. } else if(upload.status == UPLOAD_FILE_WRITE){
  165. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  166. Serial.println(F("Error updating web file"));
  167. }
  168. } else if (upload.status == UPLOAD_FILE_END) {
  169. updateFile.close();
  170. }
  171. };
  172. }
  173. void MiLightHttpServer::handleUpdateSettings() {
  174. DynamicJsonBuffer buffer;
  175. const String& rawSettings = server.arg("plain");
  176. JsonObject& parsedSettings = buffer.parse(rawSettings);
  177. if (parsedSettings.success()) {
  178. settings.patch(parsedSettings);
  179. settings.save();
  180. this->applySettings(settings);
  181. this->settingsSavedHandler();
  182. server.send(200, APPLICATION_JSON, "true");
  183. } else {
  184. server.send(400, APPLICATION_JSON, "\"Invalid JSON\"");
  185. }
  186. }
  187. void MiLightHttpServer::handleListenGateway(const UrlTokenBindings* bindings) {
  188. bool available = false;
  189. bool listenAll = bindings == NULL;
  190. uint8_t configIx = 0;
  191. MiLightRadioConfig* currentConfig =
  192. listenAll
  193. ? MiLightRadioConfig::ALL_CONFIGS[0]
  194. : MiLightRadioConfig::fromString(bindings->get("type"));
  195. if (currentConfig == NULL && bindings != NULL) {
  196. String body = "Unknown device type: ";
  197. body += bindings->get("type");
  198. server.send(400, "text/plain", body);
  199. return;
  200. }
  201. while (!available) {
  202. if (!server.clientConnected()) {
  203. return;
  204. }
  205. if (listenAll) {
  206. currentConfig = MiLightRadioConfig::ALL_CONFIGS[
  207. configIx++ % MiLightRadioConfig::NUM_CONFIGS
  208. ];
  209. }
  210. milightClient->prepare(*currentConfig, 0, 0);
  211. if (milightClient->available()) {
  212. available = true;
  213. }
  214. yield();
  215. }
  216. uint8_t packet[currentConfig->getPacketLength()];
  217. milightClient->read(packet);
  218. char response[200];
  219. char* responseBuffer = response;
  220. responseBuffer += sprintf_P(
  221. responseBuffer,
  222. PSTR("\n%s packet received (%d bytes):\n"),
  223. currentConfig->name,
  224. sizeof(packet)
  225. );
  226. milightClient->formatPacket(packet, responseBuffer);
  227. server.send(200, "text/plain", response);
  228. }
  229. void MiLightHttpServer::handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  230. DynamicJsonBuffer buffer;
  231. JsonObject& request = buffer.parse(server.arg("plain"));
  232. if (!request.success()) {
  233. server.send_P(400, TEXT_PLAIN, PSTR("Invalid JSON"));
  234. return;
  235. }
  236. milightClient->setResendCount(
  237. settings.httpRepeatFactor * settings.packetRepeats
  238. );
  239. String _deviceIds = urlBindings->get("device_id");
  240. String _groupIds = urlBindings->get("group_id");
  241. String _radioTypes = urlBindings->get("type");
  242. char deviceIds[_deviceIds.length()];
  243. char groupIds[_groupIds.length()];
  244. char radioTypes[_radioTypes.length()];
  245. strcpy(radioTypes, _radioTypes.c_str());
  246. strcpy(groupIds, _groupIds.c_str());
  247. strcpy(deviceIds, _deviceIds.c_str());
  248. TokenIterator deviceIdItr(deviceIds, _deviceIds.length());
  249. TokenIterator groupIdItr(groupIds, _groupIds.length());
  250. TokenIterator radioTypesItr(radioTypes, _radioTypes.length());
  251. while (radioTypesItr.hasNext()) {
  252. const char* _radioType = radioTypesItr.nextToken();
  253. MiLightRadioConfig* config = MiLightRadioConfig::fromString(_radioType);
  254. if (config == NULL) {
  255. char buffer[40];
  256. sprintf_P(buffer, PSTR("Unknown device type: %s"), _radioType);
  257. server.send(400, "text/plain", buffer);
  258. return;
  259. }
  260. deviceIdItr.reset();
  261. while (deviceIdItr.hasNext()) {
  262. const uint16_t deviceId = parseInt<uint16_t>(deviceIdItr.nextToken());
  263. groupIdItr.reset();
  264. while (groupIdItr.hasNext()) {
  265. const uint8_t groupId = atoi(groupIdItr.nextToken());
  266. milightClient->prepare(*config, deviceId, groupId);
  267. handleRequest(request);
  268. }
  269. }
  270. }
  271. server.send(200, APPLICATION_JSON, "true");
  272. }
  273. void MiLightHttpServer::handleRequest(const JsonObject& request) {
  274. milightClient->update(request);
  275. }
  276. void MiLightHttpServer::handleSendRaw(const UrlTokenBindings* bindings) {
  277. DynamicJsonBuffer buffer;
  278. JsonObject& request = buffer.parse(server.arg("plain"));
  279. MiLightRadioConfig* config = MiLightRadioConfig::fromString(bindings->get("type"));
  280. if (config == NULL) {
  281. char buffer[50];
  282. sprintf_P(buffer, PSTR("Unknown device type: %s"), bindings->get("type"));
  283. server.send(400, "text/plain", buffer);
  284. return;
  285. }
  286. uint8_t packet[config->getPacketLength()];
  287. const String& hexPacket = request["packet"];
  288. hexStrToBytes<uint8_t>(hexPacket.c_str(), hexPacket.length(), packet, config->getPacketLength());
  289. size_t numRepeats = MILIGHT_DEFAULT_RESEND_COUNT;
  290. if (request.containsKey("num_repeats")) {
  291. numRepeats = request["num_repeats"];
  292. }
  293. milightClient->prepare(*config, 0, 0);
  294. for (size_t i = 0; i < numRepeats; i++) {
  295. milightClient->write(packet);
  296. }
  297. server.send_P(200, TEXT_PLAIN, PSTR("true"));
  298. }
  299. ESP8266WebServer::THandlerFunction MiLightHttpServer::handleServe_P(const char* data, size_t length) {
  300. return [this, data, length]() {
  301. server.sendHeader("Content-Encoding", "gzip");
  302. server.sendHeader("Content-Length", String(length));
  303. server.setContentLength(CONTENT_LENGTH_UNKNOWN);
  304. server.send(200, "text/html", "");
  305. server.setContentLength(length);
  306. server.sendContent_P(data, length);
  307. server.client().stop();
  308. };
  309. }