#include #include #include #include #include #include #include #include #include #include #include #include File myFile; String nssid = "WIFIrouterSSID"; String npwrd = "WIFIpassword"; String uname = "ftpusr"; String pword = "ftppwd"; ESP8266WebServer server(80); FtpServer ftpSrv; //set #define FTP_DEBUG in ESP8266FtpServer.h to see ftp verbose on serial // NTP Servers: IPAddress timeServer(188, 213, 165, 209); // pool.ntp.org // IPAddress timeServer(132, 163, 4, 101); // time-a.timefreq.bldrdoc.gov // IPAddress timeServer(132, 163, 4, 102); // time-b.timefreq.bldrdoc.gov // IPAddress timeServer(132, 163, 4, 103); // time-c.timefreq.bldrdoc.gov const int timeZone = 1; // Central European Time //const int timeZone = -5; // Eastern Standard Time (USA) //const int timeZone = -4; // Eastern Daylight Time (USA) //const int timeZone = -8; // Pacific Standard Time (USA) //const int timeZone = -7; // Pacific Daylight Time (USA) WiFiUDP Udp; unsigned int localPort = 8888; // local port to listen for UDP packets int Bot_mtbs = 15000; //mean time between scan messages long Bot_lasttime; //last time messages' scan has been done bool Start = false; String timestamp = "01/01/1970;12:23:45 "; bool bootstrap = true; bool log_flag = false; // Initialize Telegram BOT #define BOTtoken "123456789:ABCabcdefghijklmnopqrstuvwxyzabcdef" // your Bot Token (Get from Botfather) #define ONE_WIRE_BUS D4 WiFiClientSecure client; UniversalTelegramBot bot(BOTtoken, client); String DS_read = "-12.3"; OneWire oneWire(ONE_WIRE_BUS); DallasTemperature DS18B20(&oneWire); const int chipSelect = 15; unsigned int mtbl = 600; time_t nextLog = 0; void setup() { Serial.begin(115200); // Set WiFi to station mode and disconnect from an AP if it was Previously // connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.print(F("Initializing SD card...")); if (!SD.begin(chipSelect)) { Serial.println(F("SD initialization failed!")); return; } else { Serial.println(F("SD opened!")); read_setup(); // attempt to connect to Wifi network: Serial.print(F("Connecting Wifi: ")); // Serial.println(nssid); WiFi.begin(nssid.c_str(), npwrd.c_str()); while (WiFi.status() != WL_CONNECTED) { Serial.print(F(".")); delay(500); } Serial.print(F("WiFi connected, IP address: ")); Serial.println(WiFi.localIP()); ftpSrv.begin(uname, pword); server.on("/", handleRoot); server.onNotFound(handleNotFound); server.begin(); Udp.begin(localPort); setSyncInterval(86400); //86400=24h } Serial.println(F("initialization done.")); } void loop() { ftpSrv.handleFTP(); //make sure in loop you call handleFTP()!! server.handleClient(); if (millis() > Bot_lasttime + Bot_mtbs) { if (bootstrap || year() == 1970) { //bootstrap one-time routine or no NTP time Serial.println (F("NTP resync...")); setSyncProvider(getNtpTime); nextLog = now() - ((now() % 3600) % mtbl) + mtbl; //align log to minute 00 bootstrap = false; } int numNewMessages = bot.getUpdates(bot.last_message_received + 1); if (now() >= nextLog && log_flag) { //is it time to log ? How about flag? nextLog += mtbl; log_temp(); } create_timestamp(); Serial.print(timestamp); Serial.print(F("free heap ")); Serial.println(ESP.getFreeHeap()); getTemperature(); while (numNewMessages) { handleNewMessages(numNewMessages); numNewMessages = bot.getUpdates(bot.last_message_received + 1); } Bot_lasttime = millis(); } } /*-------- NTP code ----------*/ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets time_t getNtpTime() { while (Udp.parsePacket() > 0) ; // discard any previously received packets Serial.println(F("Transmit NTP Request")); sendNTPpacket(timeServer); uint32_t beginWait = millis(); while (millis() - beginWait < 1500) { int size = Udp.parsePacket(); if (size >= NTP_PACKET_SIZE) { Serial.println(F("Receive NTP Response")); Udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer unsigned long secsSince1900; // convert four bytes starting at location 40 to a long integer secsSince1900 = (unsigned long)packetBuffer[40] << 24; secsSince1900 |= (unsigned long)packetBuffer[41] << 16; secsSince1900 |= (unsigned long)packetBuffer[42] << 8; secsSince1900 |= (unsigned long)packetBuffer[43]; return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR; } } Serial.println(F("No NTP Response :-(")); return 0; // return 0 if unable to get the time } // send an NTP request to the time server at the given address void sendNTPpacket(IPAddress &address) { // set all bytes in the buffer to 0 memset(packetBuffer, 0, NTP_PACKET_SIZE); // Initialize values needed to form NTP request // (see URL above for details on the packets) packetBuffer[0] = 0b11100011; // LI, Version, Mode packetBuffer[1] = 0; // Stratum, or type of clock packetBuffer[2] = 6; // Polling Interval packetBuffer[3] = 0xEC; // Peer Clock Precision // 8 bytes of zero for Root Delay & Root Dispersion packetBuffer[12] = 49; packetBuffer[13] = 0x4E; packetBuffer[14] = 49; packetBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: Udp.beginPacket(address, 123); //NTP requests are to port 123 Udp.write(packetBuffer, NTP_PACKET_SIZE); Udp.endPacket(); } void read_setup() { char c; String temp_string = ""; Serial.print(F("Reading setup... ")); myFile = SD.open("SETUP.TXT"); if (myFile) { while (myFile.read() != '<'); //skip until '<' nssid = ""; do { c = myFile.read(); if (c != '>') nssid += c; } while (c != '>'); //keep until '>' while (myFile.read() != '<'); //skip until '<' npwrd = ""; do { c = myFile.read(); if (c != '>') npwrd += c; } while (c != '>'); //keep until '>' while (myFile.read() != '<'); //skip until '<' uname = ""; do { c = myFile.read(); if (c != '>') uname += c; } while (c != '>'); //keep until '>' while (myFile.read() != '<'); //skip until '<' pword = ""; do { c = myFile.read(); if (c != '>') pword += c; } while (c != '>'); //keep until '>' while (myFile.read() != '<'); //skip until '<' do { c = myFile.read(); if (c == 'Y') log_flag = true; } while (c != '>'); //keep until '>' while (myFile.read() != '<'); //skip until '<' temp_string = ""; do { c = myFile.read(); temp_string += c; } while (c != '>'); //keep until '>' mtbl = temp_string.toInt(); Serial.println(F("Done.")); myFile.close(); } else { // if the file didn't open, print an error: Serial.println(F("error opening setup file")); } } void getTemperature() { float temp; char temperatureString[6]; do { DS18B20.requestTemperatures(); temp = DS18B20.getTempCByIndex(0); delay(100); } while (temp == 85.0 || temp == (-127.0)); dtostrf(temp, 3, 1, temperatureString); for (int i = 0; i < 6; i++) { if ( temperatureString[i] == '.') temperatureString[i] = ',' ; // put a comma instead of dot for a better csv compatibility } DS_read = String(temperatureString); } void handleNewMessages(int numNewMessages) { Serial.print(F("\n New Messages: ")); Serial.println(numNewMessages); for (int i = 0; i < numNewMessages; i++) { String chat_id = String(bot.messages[i].chat_id); String text = bot.messages[i].text; String from_name = bot.messages[i].from_name; if (text == "/command1") { String msgtext = " Temperatura accumulo = " + DS_read + "°C"; bot.sendMessage(chat_id, msgtext, ""); myFile = SD.open("CMD1.TXT", FILE_WRITE); delay(10); if (myFile) { create_timestamp(); //timestamp += msgtext; myFile.print(timestamp); myFile.println(msgtext); myFile.close(); Serial.println(F("\n Bot action logged to CMD1.TXT \n")); } else { // if the file didn't open, print an error: Serial.println(F("error opening file CMD1.TXT")); } } delay(100); } } void create_timestamp() { timestamp = ""; timestamp = inslead0(day()); timestamp += "/"; timestamp += inslead0(month()); timestamp += "/"; timestamp += String(year()); timestamp += ";"; timestamp += inslead0(hour()); timestamp += ":"; timestamp += inslead0(minute()); timestamp += ";"; } void log_temp() { String file_name = monthShortStr(month()) + String(year()) + ".CSV"; myFile = SD.open(file_name, FILE_WRITE); delay(10); if (myFile) { create_timestamp(); myFile.print(timestamp); myFile.println(DS_read); myFile.close(); Serial.println(F("\n Temperature logged to SD \n")); } else { // if the file didn't open, print an error: Serial.print(F("error opening file ")); Serial.println(file_name); } } void handleRoot() { server.send(200, "text/plain", "hello from esp8266!"); } String inslead0(int dgt) { // insert leading zero when dgt < 10 String chunk = ""; if (dgt < 10) chunk += "0"; chunk += String(dgt); return chunk; } void handleNotFound() { String message = "File Not Found\n\n"; /*message += "URI: "; message += server.uri(); message += "\nMethod: "; message += (server.method() == HTTP_GET) ? "GET" : "POST"; message += "\nArguments: "; message += server.args(); message += "\n"; for (uint8_t i = 0; i < server.args(); i++) { message += " " + server.argName(i) + ": " + server.arg(i) + "\n"; }*/ server.send(404, "text/plain", message); }