main.cpp 9.4 KB

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