main.cpp 6.6 KB

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