main.cpp 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. #include <SPI.h>
  2. #include <WiFiManager.h>
  3. #include <ArduinoJson.h>
  4. #include <stdlib.h>
  5. #include <fs.h>
  6. #include <MiLightClient.h>
  7. #include <WebServer.h>
  8. #include <IntParsing.h>
  9. #include <Settings.h>
  10. #include <MiLightUdpServer.h>
  11. MiLightClient* milightClient;
  12. MiLightUdpServer** udpServers;
  13. int numUdpServers = 0;
  14. WiFiManager wifiManager;
  15. WebServer *server = new WebServer(80);
  16. File updateFile;
  17. Settings settings;
  18. void handleUpdateGateway(const UrlTokenBindings* urlBindings) {
  19. DynamicJsonBuffer buffer;
  20. JsonObject& request = buffer.parse(server->arg("plain"));
  21. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  22. if (request.containsKey("status")) {
  23. if (request["status"] == "on") {
  24. milightClient->allOn(deviceId);
  25. } else if (request["status"] == "off") {
  26. milightClient->allOff(deviceId);
  27. }
  28. }
  29. server->send(200, "application/json", "true");
  30. }
  31. void handleUpdateGroup(const UrlTokenBindings* urlBindings) {
  32. DynamicJsonBuffer buffer;
  33. JsonObject& request = buffer.parse(server->arg("plain"));
  34. if (!request.success()) {
  35. server->send(400, "text/plain", "Invalid JSON");
  36. return;
  37. }
  38. const uint16_t deviceId = parseInt<uint16_t>(urlBindings->get("device_id"));
  39. const uint8_t groupId = urlBindings->get("group_id").toInt();
  40. if (request.containsKey("status")) {
  41. const String& statusStr = request.get<String>("status");
  42. MiLightStatus status = (statusStr == "on" || statusStr == "true") ? ON : OFF;
  43. milightClient->updateStatus(deviceId, groupId, status);
  44. }
  45. if (request.containsKey("hue")) {
  46. milightClient->updateHue(deviceId, groupId, request["hue"]);
  47. }
  48. if (request.containsKey("level")) {
  49. milightClient->updateBrightness(deviceId, groupId, request["level"]);
  50. }
  51. if (request.containsKey("command")) {
  52. if (request["command"] == "set_white") {
  53. milightClient->updateColorWhite(deviceId, groupId);
  54. }
  55. if (request["command"] == "all_on") {
  56. milightClient->allOn(deviceId);
  57. }
  58. if (request["command"] == "all_off") {
  59. milightClient->allOff(deviceId);
  60. }
  61. if (request["command"] == "unpair") {
  62. milightClient->unpair(deviceId, groupId);
  63. }
  64. if (request["command"] == "pair") {
  65. milightClient->pair(deviceId, groupId);
  66. }
  67. }
  68. server->send(200, "application/json", "true");
  69. }
  70. void handleListenGateway() {
  71. while (!milightClient->available()) {
  72. if (!server->clientConnected()) {
  73. return;
  74. }
  75. yield();
  76. }
  77. MiLightPacket packet;
  78. milightClient->read(packet);
  79. String response = "Packet received (";
  80. response += String(sizeof(packet)) + " bytes)";
  81. response += ":\n";
  82. response += "Request type : " + String(packet.deviceType, HEX) + "\n";
  83. response += "Device ID : " + String(packet.deviceId, HEX) + "\n";
  84. response += "Color : " + String(packet.color, HEX) + "\n";
  85. response += "Brightness : " + String(packet.brightness, HEX) + "\n";
  86. response += "Group ID : " + String(packet.groupId, HEX) + "\n";
  87. response += "Button : " + String(packet.button, HEX) + "\n";
  88. response += "Sequence Num : " + String(packet.sequenceNum, HEX) + "\n";
  89. response += "\n\n";
  90. server->send(200, "text/plain", response);
  91. }
  92. bool serveFile(const char* file, const char* contentType = "text/html") {
  93. if (SPIFFS.exists(file)) {
  94. File f = SPIFFS.open(file, "r");
  95. server->send(200, contentType, f.readString());
  96. f.close();
  97. return true;
  98. }
  99. return false;
  100. }
  101. ESP8266WebServer::THandlerFunction handleServeFile(const char* filename,
  102. const char* contentType,
  103. const char* defaultText = NULL) {
  104. return [filename, contentType, defaultText]() {
  105. if (!serveFile(filename)) {
  106. if (defaultText) {
  107. server->send(200, contentType, defaultText);
  108. } else {
  109. server->send(404);
  110. }
  111. }
  112. };
  113. }
  114. ESP8266WebServer::THandlerFunction handleUpdateFile(const char* filename) {
  115. return [filename]() {
  116. HTTPUpload& upload = server->upload();
  117. if (upload.status == UPLOAD_FILE_START) {
  118. updateFile = SPIFFS.open(filename, "w");
  119. } else if(upload.status == UPLOAD_FILE_WRITE){
  120. if (updateFile.write(upload.buf, upload.currentSize) != upload.currentSize) {
  121. Serial.println("Error updating web file");
  122. }
  123. } else if (upload.status == UPLOAD_FILE_END) {
  124. updateFile.close();
  125. }
  126. };
  127. yield();
  128. }
  129. void onWebUpdated() {
  130. server->send(200, "text/plain", "success");
  131. }
  132. void initMilightUdpServers() {
  133. if (udpServers) {
  134. for (int i = 0; i < numUdpServers; i++) {
  135. if (udpServers[i]) {
  136. delete udpServers[i];
  137. }
  138. }
  139. delete udpServers;
  140. }
  141. udpServers = new MiLightUdpServer*[settings.numGatewayConfigs];
  142. numUdpServers = settings.numGatewayConfigs;
  143. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  144. GatewayConfig* config = settings.gatewayConfigs[i];
  145. if (config->protocolVersion == 0) {
  146. udpServers[i] = new MiLightUdpServer(milightClient, config->port, config->deviceId);
  147. udpServers[i]->begin();
  148. } else {
  149. Serial.print("Error initializing milight UDP server - Unsupported protocolVersion: ");
  150. Serial.println(config->protocolVersion);
  151. }
  152. }
  153. }
  154. void initMilightClients() {
  155. if (milightClient) {
  156. delete milightClient;
  157. }
  158. milightClient = new MiLightClient(settings.cePin, settings.csnPin);
  159. milightClient->begin();
  160. }
  161. void handleUpdateSettings() {
  162. DynamicJsonBuffer buffer;
  163. const String& rawSettings = server->arg("plain");
  164. JsonObject& parsedSettings = buffer.parse(rawSettings);
  165. if (parsedSettings.success()) {
  166. settings.patch(parsedSettings);
  167. settings.save();
  168. initMilightClients();
  169. initMilightUdpServers();
  170. if (server->authenticationRequired() && !settings.hasAuthSettings()) {
  171. server->disableAuthentication();
  172. } else {
  173. server->requireAuthentication(settings.adminUsername, settings.adminPassword);
  174. }
  175. server->send(200, "application/json", "true");
  176. } else {
  177. server->send(400, "application/json", "\"Invalid JSON\"");
  178. }
  179. }
  180. void setup() {
  181. Serial.begin(9600);
  182. wifiManager.autoConnect();
  183. SPIFFS.begin();
  184. Settings::load(settings);
  185. initMilightClients();
  186. initMilightUdpServers();
  187. server->on("/", HTTP_GET, handleServeFile(WEB_INDEX_FILENAME, "text/html"));
  188. server->on("/settings", HTTP_GET, handleServeFile(SETTINGS_FILE, "application/json"));
  189. server->on("/settings", HTTP_PUT, handleUpdateSettings);
  190. server->on("/gateway_traffic", HTTP_GET, handleListenGateway);
  191. server->onPattern("/gateways/:device_id/:group_id", HTTP_PUT, handleUpdateGroup);
  192. server->onPattern("/gateways/:device_id", HTTP_PUT, handleUpdateGateway);
  193. server->on("/web", HTTP_POST, onWebUpdated, handleUpdateFile(WEB_INDEX_FILENAME));
  194. server->on("/firmware", HTTP_POST,
  195. [](){
  196. server->sendHeader("Connection", "close");
  197. server->sendHeader("Access-Control-Allow-Origin", "*");
  198. server->send(200, "text/plain", (Update.hasError())?"FAIL":"OK");
  199. ESP.restart();
  200. },
  201. [](){
  202. HTTPUpload& upload = server->upload();
  203. if(upload.status == UPLOAD_FILE_START){
  204. WiFiUDP::stopAll();
  205. uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  206. if(!Update.begin(maxSketchSpace)){//start with max available size
  207. Update.printError(Serial);
  208. }
  209. } else if(upload.status == UPLOAD_FILE_WRITE){
  210. if(Update.write(upload.buf, upload.currentSize) != upload.currentSize){
  211. Update.printError(Serial);
  212. }
  213. } else if(upload.status == UPLOAD_FILE_END){
  214. if(Update.end(true)){ //true to set the size to the current progress
  215. } else {
  216. Update.printError(Serial);
  217. }
  218. }
  219. yield();
  220. }
  221. );
  222. if (settings.adminUsername.length() > 0 && settings.adminPassword.length() > 0) {
  223. server->requireAuthentication(settings.adminUsername, settings.adminPassword);
  224. }
  225. server->begin();
  226. }
  227. void loop() {
  228. server->handleClient();
  229. if (udpServers) {
  230. for (size_t i = 0; i < settings.numGatewayConfigs; i++) {
  231. yield();
  232. udpServers[i]->handleClient();
  233. }
  234. }
  235. }