The esp8266 portion of the project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

920 lines
30 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. #include <ESP8266WiFi.h>
  2. #include <ESP8266WiFiMulti.h>
  3. #include <ArduinoOTA.h>
  4. #include <ESP8266WebServer.h>
  5. #include <ESP8266mDNS.h>
  6. #include <FS.h>
  7. #include <WebSocketsServer.h>
  8. #include <ArduinoJson.h>
  9. #include <SoftwareSerial.h>
  10. #include <Streaming.h>
  11. #include <OneWire.h>
  12. #include <DallasTemperature.h>
  13. #include <GDBStub.h>
  14. #include <ArduinoLog.h>
  15. #define ONE_WIRE_BUS D1
  16. // char wifiMultiSSID[30];
  17. #include <sketch_oct17esp.hpp>
  18. using namespace std;
  19. SoftwareSerial s(D3, D2); //RX.TX
  20. static char temperaturesJson[200];
  21. static char rtcDate[10];
  22. OneWire oneWire(ONE_WIRE_BUS);
  23. DallasTemperature sensors(&oneWire);
  24. const int SENSOR_RESOLUTION = 12;
  25. unsigned long lastTempRequest = 0;
  26. const unsigned int delayInMillisSensors = 750 / (1 << (12 - SENSOR_RESOLUTION));
  27. ESP8266WiFiMulti wifiMulti; // Create an instance of the ESP8266WiFiMulti class, called 'wifiMulti'
  28. ESP8266WebServer server(300); // create a web server on port 80
  29. WebSocketsServer webSocket(301); // create a websocket server on port 81
  30. File fsUploadFile; // a File variable to temporarily store the received file
  31. const char *ssid = "ESP8266 Access Point"; // The name of the Wi-Fi network that will be created
  32. const char *password = "thereisnospoon"; // The password required to connect to it, leave blank for an open network
  33. const char *OTAName = "ESP8266"; // A name and a password for the OTA service
  34. const char *OTAPassword = "esp8266";
  35. const size_t JSON_BUFFER_SIZE = JSON_ARRAY_SIZE(3) + JSON_OBJECT_SIZE(2) + 3 * JSON_OBJECT_SIZE(5) + 180;
  36. // #define LED_RED 15 // specify the pins with an RGB LED connected
  37. // #define LED_GREEN 12
  38. // #define LED_BLUE 13
  39. #define ARDUINO_TO_ESP_PIN D0
  40. // #define ESP_TO_ARDUINO_PIN D2
  41. byte currentArduinoState;
  42. byte previousArduinoState;
  43. const char *mdnsName = "esp8266"; // Domain name for the mDNS responder
  44. /*__________________________________________________________SETUP__________________________________________________________*/
  45. void setup()
  46. {
  47. // pinMode(LED_RED, OUTPUT); // the pins with LEDs connected are outputs
  48. // pinMode(LED_GREEN, OUTPUT);
  49. // pinMode(LED_BLUE, OUTPUT);
  50. Serial.begin(115200);
  51. Log.begin(LOG_LEVEL_VERBOSE, &Serial);
  52. Log.setPrefix(printTimestamp); // Uncomment to get timestamps as prefix
  53. Log.setSuffix(printNewline); // Uncomment to get newline as suffix
  54. // Serial << "Starting up ESP light controller with log level = " << Log.getLevel();
  55. // gdbstub_init();
  56. Serial << "Hello" << endl;
  57. pinMode(ARDUINO_TO_ESP_PIN, INPUT);
  58. // pinMode(ESP_TO_ARDUINO_PIN, OUTPUT);
  59. // digitalWrite(ESP_TO_ARDUINO_PIN, 1);
  60. s.begin(9600); // Start the Serial communication to send messages to the computer
  61. delay(10);
  62. Serial.println("\r\n");
  63. startWiFi(); // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection
  64. startOTA(); // Start the OTA service
  65. startSPIFFS(); // Start the SPIFFS and list all contents
  66. startWebSocket(); // Start a WebSocket server
  67. startMDNS(); // Start the mDNS responder
  68. startServer(); // Start a HTTP server with a file read handler and an upload handler
  69. Serial.println();
  70. sensors.begin();
  71. sensors.setWaitForConversion(false);
  72. sensors.requestTemperatures();
  73. // delayInMillisSensors = 750 / (1 << (12 - SENSOR_RESOLUTION));
  74. // delayInMillisSensors = 1000;
  75. lastTempRequest = millis();
  76. }
  77. /*__________________________________________________________LOOP__________________________________________________________*/
  78. bool rainbow = false; // The rainbow effect is turned off on startup
  79. //bool arduinoON = false;
  80. unsigned long prevMillis = millis();
  81. int hue = 0;
  82. void loop()
  83. {
  84. // // digitalWrite(ESP_TO_ARDUINO_PIN, 0);
  85. // webSocket.loop(); // constantly check for websocket events
  86. server.handleClient(); // run the server
  87. ArduinoOTA.handle(); // listen for OTA events
  88. previousArduinoState = currentArduinoState;
  89. currentArduinoState = digitalRead(ARDUINO_TO_ESP_PIN);
  90. if (previousArduinoState == LOW && currentArduinoState == HIGH)
  91. {
  92. // Serial.println("Arduino turned on");
  93. Log.notice("Arduino turned on");
  94. //arduinoON = true;
  95. //combineSettings();
  96. displayCombinedSettings();
  97. Log.notice("Settings sent to arduino");
  98. }
  99. // if (rainbow)
  100. // { // if the rainbow effect is turned on
  101. // if (millis() > prevMillis + 32)
  102. // {
  103. // if (++hue == 360) // Cycle through the color wheel (increment by one degree every 32 ms)
  104. // hue = 0;
  105. // setHue(hue); // Set the RGB LED to the right color
  106. // prevMillis = millis();
  107. // }
  108. // }
  109. if (s.available() > 0)
  110. {
  111. // Serial << F("Received JSON from arduino") << endl;
  112. // Serial << F("Inside second if ") << endl;
  113. // StaticJsonBuffer<100> jsonBuffer;
  114. // Log.notice(F("Received JSON from arduino"));
  115. DynamicJsonBuffer jsonBuffer(100);
  116. // Serial << "S available = " << s.available();
  117. JsonObject &root = jsonBuffer.parseObject(s);
  118. JsonArray &lcd_data = root["lcdData"];
  119. // lcd_data[0];
  120. // char a[10];
  121. sprintf(rtcDate, lcd_data[1] | "N/A");
  122. // root.printTo(Serial);
  123. // Serial << s.available() << endl;
  124. // s.flush();
  125. // Serial << (char)s.read() << endl;
  126. // sensors.requestTemperatures();
  127. // char str_temp[6];
  128. // dtostrf(sensors.getTempCByIndex(0), 1, 1, str_temp);
  129. // sprintf(a, "%s", str_temp);
  130. // tft.drawString(str_temp, coordinates.x[3], coordinates.y[3], 2);
  131. // Serial.println(sensors.getTempCByIndex(0));
  132. delay(50);
  133. }
  134. // sensors.requestTemperatures();
  135. // Serial.println(sensors.getTempCByIndex(0));
  136. // delay(1000);
  137. // Serial << F("Serial available = ") << s.available() << endl;
  138. // delay(50);
  139. // if (sensors.isConversionAvailable(0))
  140. // {
  141. // // tft.drawString("25.5C", coordinates.x[3], coordinates.y[3], 2);
  142. // Serial << "Reading avaialable" << endl;
  143. // char b[10];
  144. // char str_temp[6];
  145. // dtostrf(sensors.getTempCByIndex(0), 1, 1, str_temp);
  146. // sprintf(b, "%s", str_temp);
  147. // tft.drawString(str_temp, coordinates.x[3], coordinates.y[3], 2);
  148. // Serial.println(sensors.getTempCByIndex(0));
  149. // sensors.requestTemperatures();
  150. // }
  151. if (millis() - lastTempRequest >= delayInMillisSensors)
  152. {
  153. // char b[10];
  154. // char str_temp[6];
  155. // saveTemperatureJson();
  156. // StaticJsonBuffer<200> jsonBuffer;
  157. DynamicJsonBuffer jsonBuffer(100);
  158. JsonObject &root = jsonBuffer.createObject();
  159. if (!root.success())
  160. {
  161. Log.error("Error creating temperature json");
  162. }
  163. JsonArray &temperatures = root.createNestedArray("temperatures");
  164. // temperatures.add(sensors.getTempCByIndex(0));
  165. // Serial << "Sensor" << endl;
  166. float temp1 = sensors.getTempCByIndex(0);
  167. // Serial << "Sensor" << endl;
  168. float temp2 = sensors.getTempCByIndex(1);
  169. temperatures.add(temp1);
  170. temperatures.add(temp2);
  171. // root.prettyPrintTo(Serial);
  172. root.prettyPrintTo(temperaturesJson);
  173. // dtostrf(sensors.getTempCByIndex(0), 1, 1, str_temp);
  174. // sprintf(b, "%s", str_temp);
  175. // tft.drawString(str_temp, coordinates.x[3], coordinates.y[3], 2);
  176. // Serial.println(sensors.getTempCByIndex(0));
  177. // Serial << "Delay: " << delayInMillisSensors << endl;
  178. // Serial << "Requesting temperatures" << endl;
  179. sensors.requestTemperatures();
  180. // delayInMillisSensors = 750 / (1 << (12 - SENSOR_RESOLUTION));
  181. lastTempRequest = millis();
  182. }
  183. }
  184. /*__________________________________________________________SETUP_FUNCTIONS__________________________________________________________*/
  185. void startWiFi()
  186. { // Start a Wi-Fi access point, and try to connect to some given access points. Then wait for either an AP or STA connection
  187. WiFi.softAP(ssid, password); // Start the access point
  188. Serial.print("Access Point \"");
  189. Serial.print(ssid);
  190. Serial.println("\" started\r\n");
  191. // wifiMulti.addAP(wifiMultiSSID, wifiMultiPassword);
  192. // #ifdef WIFI_SSID
  193. // const char *wifiMultiSSID = WIFI_SSID;
  194. // Serial << "Macro " << WIFI_SSID;
  195. // // wifiMulti.addAP(LC_WIFI_SSID, "");
  196. // #else
  197. // const char *wifiMultiSSID = "ssid";
  198. // #endif
  199. // #ifdef WIFI_PASS
  200. // const char *wifiMultiPassword = WIFI_PASS;
  201. // #else
  202. // const char *wifiMultiPassword = "password";
  203. // #endif
  204. // wifiMulti.addAP(wifiMultiSSID, wifiMultiPassword);
  205. Serial.print(F("MAC: "));
  206. Serial.println(WiFi.macAddress());
  207. Serial.println("Connecting");
  208. while (wifiMulti.run() != WL_CONNECTED && WiFi.softAPgetStationNum() < 1)
  209. { // Wait for the Wi-Fi to connect
  210. delay(250);
  211. Serial.print('.');
  212. }
  213. Serial.println("\r\n");
  214. if (WiFi.softAPgetStationNum() == 0)
  215. { // If the ESP is connected to an AP
  216. Serial.print("Connected to ");
  217. Serial.println(WiFi.SSID()); // Tell us what network we're connected to
  218. Serial.print("IP address:\t");
  219. Serial.print(WiFi.localIP()); // Send the IP address of the ESP8266 to the computer
  220. }
  221. else
  222. { // If a station is connected to the ESP SoftAP
  223. Serial.print("Station connected to ESP8266 AP");
  224. }
  225. Serial.println("\r\n");
  226. }
  227. void startOTA()
  228. { // Start the OTA service
  229. ArduinoOTA.setHostname(OTAName);
  230. ArduinoOTA.setPassword(OTAPassword);
  231. ArduinoOTA.onStart([]() {
  232. Serial.println("Start");
  233. // digitalWrite(LED_RED, 0); // turn off the LEDs
  234. // digitalWrite(LED_GREEN, 0);
  235. // digitalWrite(LED_BLUE, 0);
  236. });
  237. ArduinoOTA.onEnd([]() {
  238. Serial.println("\r\nEnd");
  239. });
  240. ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
  241. Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
  242. });
  243. ArduinoOTA.onError([](ota_error_t error) {
  244. Serial.printf("Error[%u]: ", error);
  245. if (error == OTA_AUTH_ERROR)
  246. Serial.println("Auth Failed");
  247. else if (error == OTA_BEGIN_ERROR)
  248. Serial.println("Begin Failed");
  249. else if (error == OTA_CONNECT_ERROR)
  250. Serial.println("Connect Failed");
  251. else if (error == OTA_RECEIVE_ERROR)
  252. Serial.println("Receive Failed");
  253. else if (error == OTA_END_ERROR)
  254. Serial.println("End Failed");
  255. });
  256. ArduinoOTA.begin();
  257. Serial.println("OTA ready\r\n");
  258. }
  259. void startSPIFFS()
  260. { // Start the SPIFFS and list all contents
  261. SPIFFS.begin(); // Start the SPI Flash File System (SPIFFS)
  262. Serial.println("SPIFFS started. Contents:");
  263. {
  264. Dir dir = SPIFFS.openDir("/");
  265. while (dir.next())
  266. { // List the file system contents
  267. String fileName = dir.fileName();
  268. size_t fileSize = dir.fileSize();
  269. Serial.printf("\tFS File: %s, size: %s\r\n", fileName.c_str(), formatBytes(fileSize).c_str());
  270. }
  271. Serial.printf("\n");
  272. }
  273. }
  274. void startWebSocket()
  275. { // Start a WebSocket server
  276. webSocket.begin(); // start the websocket server
  277. webSocket.onEvent(webSocketEvent); // if there's an incomming websocket message, go to function 'webSocketEvent'
  278. Serial.println("WebSocket server started.");
  279. }
  280. void startMDNS()
  281. { // Start the mDNS responder
  282. MDNS.begin(mdnsName); // start the multicast domain name server
  283. Serial.print("mDNS responder started: http://");
  284. Serial.print(mdnsName);
  285. Serial.println(".local");
  286. }
  287. void startServer()
  288. { // Start a HTTP server with a file read handler and an upload handler
  289. server.on(
  290. "/edit.html", HTTP_POST, []() { // If a POST request is sent to the /edit.html address,
  291. // server.send(200, "text/plain", "");
  292. server.send(200);
  293. },
  294. handleFileUpload); // go to 'handleFileUpload'
  295. server.onNotFound(handleNotFound); // if someone requests any other file or page, go to function 'handleNotFound'
  296. // and check if the file exists
  297. server.on("/settings.html", HTTP_POST, handleSettings);
  298. server.on("/manualMode.html", HTTP_POST, handleManual);
  299. server.on("/api/get/temperatures", HTTP_GET, []() {
  300. sendCors();
  301. server.send(200, "application/json", temperaturesJson);
  302. });
  303. server.on("/api/get/date", HTTP_GET, []() {
  304. sendCors();
  305. server.send(200, "text/plain", rtcDate);
  306. });
  307. server.begin(); // start the HTTP server
  308. Serial.println("HTTP server started.");
  309. }
  310. /*__________________________________________________________SERVER_HANDLERS__________________________________________________________*/
  311. void handleNotFound()
  312. { // if the requested file or page doesn't exist, return a 404 not found error
  313. if (!handleFileRead(server.uri()))
  314. { // check if the file exists in the flash memory (SPIFFS), if so, send it
  315. server.send(404, "application/json", "{\"status\":\"failed\",\"message\":\"Resource not found\"}");
  316. }
  317. }
  318. bool handleFileRead(String path)
  319. { // send the right file to the client (if it exists)
  320. Serial.println("handleFileRead: " + path);
  321. if (path.endsWith("/"))
  322. path += "index.html"; // If a folder is requested, send the index file
  323. String contentType = getContentType(path); // Get the MIME type
  324. String pathWithGz = path + ".gz";
  325. if (SPIFFS.exists(pathWithGz) || SPIFFS.exists(path))
  326. { // If the file exists, either as a compressed archive, or normal
  327. if (SPIFFS.exists(pathWithGz)) // If there's a compressed version available
  328. path += ".gz"; // Use the compressed verion
  329. File file = SPIFFS.open(path, "r"); // Open the file
  330. size_t sent = server.streamFile(file, contentType); // Send it to the client
  331. file.close(); // Close the file again
  332. Serial.println(String("\tSent file: ") + path);
  333. return true;
  334. }
  335. Serial.println(String("\tFile Not Found: ") + path); // If the file doesn't exist, return false
  336. return false;
  337. }
  338. void sendCors()
  339. {
  340. server.sendHeader("Access-Control-Allow-Origin", "*");
  341. server.sendHeader("Access-Control-Max-Age", "10000");
  342. server.sendHeader("Access-Control-Allow-Methods", "PUT,POST,GET,OPTIONS");
  343. server.sendHeader("Access-Control-Allow-Headers", "*");
  344. }
  345. void saveTemperatureJson(DallasTemperature &sensors)
  346. {
  347. StaticJsonBuffer<200> jsonBuffer;
  348. JsonObject &root = jsonBuffer.createObject();
  349. if (!root.success())
  350. {
  351. Log.error("Error creating temperature json object");
  352. }
  353. // JsonArray &data = root.createNestedArray("data");
  354. // data.add(48);
  355. // data.add(2);
  356. JsonArray &temperatures = root.createNestedArray("temperatures");
  357. float temp1 = sensors.getTempCByIndex(0);
  358. float temp2 = sensors.getTempCByIndex(1);
  359. temperatures.add(temp1);
  360. temperatures.add(temp2);
  361. temperatures.add(1);
  362. root.prettyPrintTo(Serial);
  363. root.prettyPrintTo(temperaturesJson);
  364. // if (SPIFFS.exists("/temperatures.txt"))
  365. // {
  366. // SPIFFS.remove("/temperatures.txt");
  367. // Serial.println("Old settings file removed");
  368. // }
  369. // File settingsFile = SPIFFS.open("/temperatures.txt", "w");
  370. // if (!settingsFile)
  371. // Log.error("Error wriing json to file");
  372. // root.prettyPrintTo(settingsFile); //Export and save JSON object to SPIFFS area
  373. // Serial.println("Json written to file");
  374. // settingsFile.close();
  375. }
  376. void saveSettings(ESP8266WebServer &server, int num)
  377. {
  378. Log.notice("Ballast num = %d", num);
  379. const int shour = server.arg("shour").toInt();
  380. const int smin = server.arg("smin").toInt();
  381. const int fadePeriod = server.arg("fadePeriod").toInt();
  382. const int ehour = server.arg("ehour").toInt();
  383. const int emin = server.arg("emin").toInt();
  384. StaticJsonBuffer<200> jsonBuffer;
  385. JsonObject &root = jsonBuffer.createObject();
  386. if (!root.success())
  387. {
  388. Log.error("Error creating json");
  389. return;
  390. }
  391. root["shour"] = shour;
  392. root["fadePeriod"] = fadePeriod;
  393. root["smin"] = smin;
  394. root["ehour"] = ehour;
  395. root["emin"] = emin;
  396. root.prettyPrintTo(Serial);
  397. char buf[40] = "";
  398. sprintf(buf, "/settingsFile%d.txt", num);
  399. Log.verbose("Settings file chosen = %s", buf);
  400. if (SPIFFS.exists(buf))
  401. {
  402. SPIFFS.remove(buf);
  403. Log.notice("Old settings file removed");
  404. }
  405. File settingsFile = SPIFFS.open(buf, "w");
  406. if (!settingsFile)
  407. Log.error("Error opening settings file - %d", num);
  408. root.prettyPrintTo(settingsFile); //Export and save JSON object to SPIFFS area
  409. Log.notice("Json written to file");
  410. settingsFile.close();
  411. // delete server;
  412. }
  413. void combineSettings()
  414. {
  415. File file1 = SPIFFS.open("/settingsFile1.txt", "r");
  416. File file2 = SPIFFS.open("/settingsFile2.txt", "r");
  417. File file3 = SPIFFS.open("/settingsFile3.txt", "r");
  418. File file5 = SPIFFS.open("/manualMode.txt", "r");
  419. // Serial.println("2");
  420. if (SPIFFS.exists("/combinedSettingsFile.txt"))
  421. {
  422. SPIFFS.remove("/combinedSettingsFile.txt");
  423. }
  424. File file4 = SPIFFS.open("/combinedSettingsFile.txt", "w");
  425. size_t size1 = file1.size(), size2 = file2.size(), size3 = file3.size(), size5 = file5.size();
  426. ;
  427. std::unique_ptr<char[]> buf1(new char[size1]);
  428. std::unique_ptr<char[]> buf2(new char[size2]);
  429. std::unique_ptr<char[]> buf3(new char[size3]);
  430. std::unique_ptr<char[]> buf5(new char[size5]);
  431. file1.readBytes(buf1.get(), size1);
  432. file2.readBytes(buf2.get(), size2);
  433. file3.readBytes(buf3.get(), size3);
  434. file5.readBytes(buf5.get(), size5);
  435. StaticJsonBuffer<100> jsonBuffer10;
  436. JsonObject &root1 = jsonBuffer10.parseObject(buf1.get());
  437. if (root1 == JsonObject::invalid())
  438. {
  439. Serial.println("Error1");
  440. }
  441. StaticJsonBuffer<100> jsonBuffer11;
  442. JsonObject &root2 = jsonBuffer11.parseObject(buf2.get());
  443. if (root2 == JsonObject::invalid())
  444. {
  445. Serial.println("Error2");
  446. }
  447. StaticJsonBuffer<100> jsonBuffer12;
  448. JsonObject &root3 = jsonBuffer12.parseObject(buf3.get());
  449. if (root3 == JsonObject::invalid())
  450. {
  451. Serial.println("Error3");
  452. }
  453. StaticJsonBuffer<50> jsonBuffer16;
  454. JsonObject &root5 = jsonBuffer16.parseObject(buf5.get());
  455. /*StaticJsonBuffer<300> jsonBuffer13;
  456. JsonObject& root4 = jsonBuffer13.createObject();
  457. JsonObject& ballast1 = root4.createNestedObject();
  458. root4["shour1"]=root1["shour1"];
  459. root4["smin1"]=root1["smin1"];
  460. root4["fadePeriod1"]=root1["fadePeriod1"];
  461. root4["shour2"]=root2["shour2"];
  462. root4["smin2"]=root2["smin2"];
  463. root4["fadePeriod2"]=root2["fadePeriod2"];
  464. root4["shour3"]=root3["shour3"];
  465. root4["smin3"]=root3["smin3"];
  466. root4["fadePeriod3"]=root3["fadePeriod3"];*/
  467. DynamicJsonBuffer jsonBuffer(JSON_BUFFER_SIZE);
  468. JsonObject &root = jsonBuffer.createObject();
  469. JsonArray &settings = root.createNestedArray("settings");
  470. JsonObject &settings_0 = settings.createNestedObject();
  471. settings_0["shour"] = root1["shour"];
  472. settings_0["fadePeriod"] = root1["fadePeriod"];
  473. settings_0["smin"] = root1["smin"];
  474. settings_0["ehour"] = root1["ehour"];
  475. settings_0["emin"] = root1["emin"];
  476. JsonObject &settings_1 = settings.createNestedObject();
  477. settings_1["shour"] = root2["shour"];
  478. settings_1["fadePeriod"] = root2["fadePeriod"];
  479. settings_1["smin"] = root2["smin"];
  480. settings_1["ehour"] = root2["ehour"];
  481. settings_1["emin"] = root2["emin"];
  482. JsonObject &settings_2 = settings.createNestedObject();
  483. settings_2["shour"] = root3["shour"];
  484. settings_2["fadePeriod"] = root3["fadePeriod"];
  485. settings_2["smin"] = root3["smin"];
  486. settings_2["ehour"] = root3["ehour"];
  487. settings_2["emin"] = root3["emin"];
  488. root["manual"] = root5["manual"];
  489. /*root1.printTo(file4);
  490. root1.printTo(Serial);
  491. root2.printTo(file4);
  492. root2.printTo(Serial);
  493. root3.printTo(file4);
  494. root3.printTo(Serial);*/
  495. root.prettyPrintTo(Serial);
  496. root.prettyPrintTo(file4);
  497. // Serial.println("3");
  498. file1.close();
  499. file2.close();
  500. file3.close();
  501. file4.close();
  502. file5.close();
  503. }
  504. void combineSettings_new()
  505. {
  506. const File file1 = SPIFFS.open("/settingsFile1.txt", "r");
  507. const File file2 = SPIFFS.open("/settingsFile2.txt", "r");
  508. const File file3 = SPIFFS.open("/settingsFile3.txt", "r");
  509. File file5 = SPIFFS.open("/manualMode.txt", "r");
  510. if (SPIFFS.exists("/combinedSettingsFile.txt"))
  511. {
  512. SPIFFS.remove("/combinedSettingsFile.txt");
  513. }
  514. File file_arr[] = {file1, file2, file3};
  515. File file4 = SPIFFS.open("/combinedSettingsFile.txt", "w");
  516. StaticJsonBuffer<JSON_BUFFER_SIZE> jsonBuffer;
  517. JsonObject &root = jsonBuffer.createObject();
  518. JsonArray &settings = root.createNestedArray("settings");
  519. StaticJsonBuffer<50> jsonBufferManual;
  520. size_t size_manual = file5.size();
  521. unique_ptr<char[]> buf_manual(new char[size_manual]);
  522. file5.readBytes(buf_manual.get(), size_manual);
  523. JsonObject &root_manual = jsonBufferManual.parseObject(buf_manual.get());
  524. for (int i = 0; i < 3; i++)
  525. {
  526. const size_t file_size = file_arr[i].size();
  527. const unique_ptr<char[]> buf(new char[file_size]);
  528. file_arr[i].readBytes(buf.get(), file_size);
  529. StaticJsonBuffer<(JSON_BUFFER_SIZE / 3) + 50> jsonBuffer;
  530. JsonObject &root_i = jsonBuffer.parseObject(buf.get());
  531. if (!root_i.success())
  532. {
  533. Log.error(F("Error creating json for file %d"), i + 1);
  534. }
  535. else
  536. {
  537. JsonObject &settings_i = settings.createNestedObject();
  538. settings_i["shour"] = root_i["shour"];
  539. settings_i["fadePeriod"] = root_i["fadePeriod"];
  540. settings_i["smin"] = root_i["smin"];
  541. settings_i["ehour"] = root_i["ehour"];
  542. settings_i["emin"] = root_i["emin"];
  543. // Log.notice("inside array temp");
  544. // char buf[JSON_BUFFER_SIZE / 3];
  545. // root_i.prettyPrintTo(buf);
  546. // Log.trace("%s", buf);
  547. Log.trace("Printing settings %d", i + 1);
  548. // settings_i.prettyPrintTo(Serial);
  549. // root.prettyPrintTo(Serial);
  550. // settings.prettyPrintTo(Serial);
  551. file_arr[i].close();
  552. }
  553. }
  554. root["manual"] = root_manual["manual"];
  555. Log.trace("Printing final root");
  556. root.prettyPrintTo(Serial);
  557. root.prettyPrintTo(file4);
  558. file4.close();
  559. file5.close();
  560. }
  561. /*void displaySettings()
  562. {
  563. File file = SPIFFS.open("/settingsFile.txt", "r");
  564. if (!file){
  565. Log.error("Error reading settings file or file does not exist");
  566. } else {
  567. size_t size = file.size();
  568. if ( size == 0 ) {
  569. Serial.println("Settings file is empty");
  570. } else {
  571. std::unique_ptr<char[]> buf (new char[size]);
  572. file.readBytes(buf.get(), size);
  573. StaticJsonBuffer<200> jsonBuffer2;
  574. JsonObject& root = jsonBuffer2.parseObject(buf.get());
  575. if (!root.success()) {
  576. Log.error("Error reading settings file");
  577. } else {
  578. Serial.println("Settings file loaded");
  579. root.prettyPrintTo(Serial);
  580. root.printTo(s);
  581. Serial.println("Settings sent to arduino");
  582. }
  583. }
  584. file.close();
  585. }
  586. }*/
  587. void displayCombinedSettings()
  588. {
  589. File file = SPIFFS.open("/combinedSettingsFile.txt", "r");
  590. if (!file)
  591. {
  592. Log.error("Error reading combined settings file or file does not exist");
  593. }
  594. else
  595. {
  596. Log.notice("Settings file exists");
  597. size_t size = file.size();
  598. if (size == 0)
  599. {
  600. Log.notice("Settings file is empty");
  601. }
  602. else
  603. {
  604. std::unique_ptr<char[]> buf5(new char[size]);
  605. file.readBytes(buf5.get(), size);
  606. // StaticJsonBuffer<300> jsonBuffer;
  607. DynamicJsonBuffer jsonBuffer(JSON_BUFFER_SIZE);
  608. JsonObject &root5 = jsonBuffer.parseObject(buf5.get());
  609. if (!root5.success())
  610. {
  611. Log.error("Error reading combined settings file");
  612. }
  613. else
  614. {
  615. Log.notice("Settings file loaded");
  616. root5.prettyPrintTo(Serial);
  617. // digitalWrite(ESP_TO_ARDUINO_PIN,0);
  618. // analogWrite(ESP_TO_ARDUINO_PIN,255);
  619. root5.printTo(s);
  620. // digitalWrite(ESP_TO_ARDUINO_PIN,1);
  621. }
  622. }
  623. file.close();
  624. }
  625. }
  626. void handleManual()
  627. {
  628. File file = SPIFFS.open("/manualMode.txt", "w");
  629. StaticJsonBuffer<50> jsonBufferManual;
  630. JsonObject &root = jsonBufferManual.createObject();
  631. if (server.arg("manual") == "True")
  632. {
  633. root["manual"] = "True";
  634. }
  635. else
  636. {
  637. root["manual"] = "False";
  638. }
  639. root.prettyPrintTo(file);
  640. file.close();
  641. combineSettings();
  642. // digitalWrite(ESP_TO_ARDUINO_PIN, 1);
  643. displayCombinedSettings();
  644. // digitalWrite(ESP_TO_ARDUINO_PIN,1);
  645. // server.sendHeader("Location", "/manualMode.html"); // Redirect the client to the success page
  646. // server.send(303);
  647. server.send(200);
  648. }
  649. void handleSettings()
  650. {
  651. // if (server.arg("ballast").toInt() == 1)
  652. // handleSettings1();
  653. // else if (server.arg("ballast").toInt() == 2)
  654. // handleSettings2();
  655. // else if (server.arg("ballast").toInt() == 3)
  656. // handleSettings3();
  657. // displayCombinedSettings();
  658. // server.sendHeader("Location", "/settings.html"); // Redirect the client to the success page
  659. const int ballast_num = server.arg("ballast").toInt();
  660. Log.notice("Chosen num = %d", ballast_num);
  661. saveSettings(server, ballast_num);
  662. combineSettings();
  663. displayCombinedSettings();
  664. server.send(200);
  665. }
  666. void handleFileUpload()
  667. { // upload a new file to the SPIFFS
  668. HTTPUpload &upload = server.upload();
  669. String path;
  670. if (upload.status == UPLOAD_FILE_START)
  671. {
  672. path = upload.filename;
  673. if (!path.startsWith("/"))
  674. path = "/" + path;
  675. if (!path.endsWith(".gz"))
  676. { // The file server always prefers a compressed version of a file
  677. String pathWithGz = path + ".gz"; // So if an uploaded file is not compressed, the existing compressed
  678. if (SPIFFS.exists(pathWithGz)) // version of that file must be deleted (if it exists)
  679. SPIFFS.remove(pathWithGz);
  680. }
  681. Serial.print("handleFileUpload Name: ");
  682. Serial.println(path);
  683. fsUploadFile = SPIFFS.open(path, "w"); // Open the file for writing in SPIFFS (create if it doesn't exist)
  684. path = String();
  685. }
  686. else if (upload.status == UPLOAD_FILE_WRITE)
  687. {
  688. if (fsUploadFile)
  689. fsUploadFile.write(upload.buf, upload.currentSize); // Write the received bytes to the file
  690. }
  691. else if (upload.status == UPLOAD_FILE_END)
  692. {
  693. if (fsUploadFile)
  694. { // If the file was successfully created
  695. fsUploadFile.close(); // Close the file again
  696. Serial.print("handleFileUpload Size: ");
  697. Serial.println(upload.totalSize);
  698. // server.sendHeader("Location", "/success.html"); // Redirect the client to the success page
  699. server.send(201, "application/json", "{\"status\":\"success\",\"message\":\"File created successfully\"}");
  700. }
  701. else
  702. {
  703. server.send(500, "application/json", "{\"status\":\"failed\",\"message\":\"Could not create file\"}");
  704. }
  705. }
  706. }
  707. // const char *text = R"(
  708. // { " "
  709. // ;''
  710. // }
  711. // qegqeg
  712. // qegq
  713. // )";
  714. void webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t lenght)
  715. { // When a WebSocket message is received
  716. switch (type)
  717. {
  718. case WStype_DISCONNECTED: // if the websocket is disconnected
  719. Serial.printf("[%u] Disconnected!\n", num);
  720. break;
  721. case WStype_CONNECTED:
  722. { // if a new websocket connection is established
  723. IPAddress ip = webSocket.remoteIP(num);
  724. Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
  725. rainbow = false; // Turn rainbow off when a new connection is established
  726. }
  727. break;
  728. case WStype_TEXT: // if new text data is received
  729. Serial.printf("[%u] get Text: %s\n", num, payload);
  730. if (payload[0] == '#')
  731. { // we get RGB data
  732. uint32_t rgb = (uint32_t)strtol((const char *)&payload[1], NULL, 16); // decode rgb data
  733. int r = ((rgb >> 20) & 0x3FF); // 10 bits per color, so R: bits 20-29
  734. int g = ((rgb >> 10) & 0x3FF); // G: bits 10-19
  735. int b = rgb & 0x3FF; // B: bits 0-9
  736. // analogWrite(LED_RED, r); // write it to the LED output pins
  737. // analogWrite(LED_GREEN, g);
  738. // analogWrite(LED_BLUE, b);
  739. }
  740. else if (payload[0] == 'R')
  741. { // the browser sends an R when the rainbow effect is enabled
  742. rainbow = true;
  743. }
  744. else if (payload[0] == 'N')
  745. { // the browser sends an N when the rainbow effect is disabled
  746. rainbow = false;
  747. }
  748. break;
  749. default:
  750. {
  751. Log.error("Unsupported operation - number %d", type);
  752. }
  753. }
  754. }
  755. /*__________________________________________________________HELPER_FUNCTIONS__________________________________________________________*/
  756. String formatBytes(size_t bytes)
  757. { // convert sizes in bytes to KB and MB
  758. if (bytes < 1024)
  759. {
  760. return String(bytes) + "B";
  761. }
  762. else if (bytes < (1024 * 1024))
  763. {
  764. return String(bytes / 1024.0) + "KB";
  765. }
  766. else if (bytes < (1024 * 1024 * 1024))
  767. {
  768. return String(bytes / 1024.0 / 1024.0) + "MB";
  769. }
  770. else
  771. return "";
  772. }
  773. String getContentType(String filename)
  774. { // determine the filetype of a given filename, based on the extension
  775. if (filename.endsWith(".html"))
  776. return "text/html";
  777. else if (filename.endsWith(".css"))
  778. return "text/css";
  779. else if (filename.endsWith(".js"))
  780. return "application/javascript";
  781. else if (filename.endsWith(".ico"))
  782. return "image/x-icon";
  783. else if (filename.endsWith(".gz"))
  784. return "application/x-gzip";
  785. return "text/plain";
  786. }
  787. void setHue(int hue)
  788. { // Set the RGB LED to a given hue (color) (0° = Red, 120° = Green, 240° = Blue)
  789. hue %= 360; // hue is an angle between 0 and 359°
  790. float radH = hue * 3.142 / 180; // Convert degrees to radians
  791. float rf, gf, bf;
  792. if (hue >= 0 && hue < 120)
  793. { // Convert from HSI color space to RGB
  794. rf = cos(radH * 3 / 4);
  795. gf = sin(radH * 3 / 4);
  796. bf = 0;
  797. }
  798. else if (hue >= 120 && hue < 240)
  799. {
  800. radH -= 2.09439;
  801. gf = cos(radH * 3 / 4);
  802. bf = sin(radH * 3 / 4);
  803. rf = 0;
  804. }
  805. else if (hue >= 240 && hue < 360)
  806. {
  807. radH -= 4.188787;
  808. bf = cos(radH * 3 / 4);
  809. rf = sin(radH * 3 / 4);
  810. gf = 0;
  811. }
  812. int r = rf * rf * 1023;
  813. int g = gf * gf * 1023;
  814. int b = bf * bf * 1023;
  815. // analogWrite(LED_RED, r); // Write the right color to the LED output pins
  816. // analogWrite(LED_GREEN, g);
  817. // analogWrite(LED_BLUE, b);
  818. }
  819. void printTimestamp(Print *_logOutput)
  820. {
  821. char c[12];
  822. int m = sprintf(c, "%10lu ", millis());
  823. _logOutput->print(c);
  824. }
  825. void printNewline(Print *_logOutput)
  826. {
  827. _logOutput->print('\n');
  828. }