#include <SD.h>
#include <FS.h>
#include <SPIFFS.h>
#define FORMAT_SPIFFS_IF_FAILED true
#include <sd_defines.h>
#include <sd_diskio.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include "BluetoothSerial.h"
#include "time.h"
#include <sys/time.h>
//#include <TEA5767.h>
//TEA5767 radio = TEA5767();
#include <EEPROM.h>
#include <Adafruit_GFX.h> // Core graphics library
#include <Adafruit_ST7735.h> // Hardware-specific library for ST7735
//#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif
// For the breakout, you can use any 2 or 3 pins
// These pins will also work for the 1.8" TFT shield
#define TFT_CS 26 // DETTO CS ex 15 LCD decine ore
#define TFT1_CS 33 // CS LCD unità ore
#define TFT2_CS 15 // CS LCD decine minuti
#define TFT3_CS 32 // CS LCD unità minuti
#define TFT_RST 2 // pin EN
#define TFT_DC 13 // DETTO RS ex 17
#define TFT_MOSI 14 // DETTO MOSI O SDA
#define TFT_SCLK 27 // DETTO SCL
byte comando = 0;
int minuti=66;
int ore=66;
int font = 0;
float frequenza;
char orario[] = "AAAA";
char ssid[33]="CespyNet";
char password[64]="st3f@ni@02";
const char* ntpServer = "ntp1.inrim.it";
unsigned long previousMillis = 0;
BluetoothSerial SerialBT;
time_t sec;
struct tm timeinfo;
struct Wifi_Struct {
char sid[33];
char pwd[64];
};
Wifi_Struct credenziali;
char direc[11];
char filenam[11];
int x = 0;
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
Adafruit_ST7735 tft1 = Adafruit_ST7735(TFT1_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
Adafruit_ST7735 tft2 = Adafruit_ST7735(TFT2_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
Adafruit_ST7735 tft3 = Adafruit_ST7735(TFT3_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST);
void setup() {
EEPROM.begin(100);
EEPROM.get(2, credenziali);
strcpy(ssid,credenziali.sid);
strcpy(password,credenziali.pwd);
SerialBT.begin("OROLCD"); //Bluetooth device name
Serial.begin(115200);
Serial.print("Initializing SD card...");
if (!SD.begin(5)) {
Serial.print("failed and NOT ");
while(1);
}
Serial.println("OK!");
if(!SPIFFS.begin(FORMAT_SPIFFS_IF_FAILED)){
Serial.println("SPIFFS Mount Failed");
return;
}
Serial.print("Bytes totali: ");
Serial.println(SPIFFS.totalBytes());
File root = SPIFFS.open("/"); //SD.open("/"); // open SD card main root
printDirectory(root, 0); // print all files names and sizes
root.close(); // close the opened root
// Prova();
font = EEPROM.read(0);
CalcolaFont();
tft.initR(INITR_MINI160x80_PLUGIN);
tft.setRotation(0);
tft.fillScreen(ST7735_BLACK);
tft1.initR(INITR_MINI160x80_PLUGIN);
tft1.setRotation(0);
tft1.fillScreen(ST7735_BLACK);
tft2.initR(INITR_MINI160x80_PLUGIN);
tft2.setRotation(0);
tft2.fillScreen(ST7735_BLACK);
tft3.initR(INITR_MINI160x80_PLUGIN);
tft3.setRotation(0);
tft3.fillScreen(ST7735_BLACK);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED) {
if (SerialBT.available()) {
comando= SerialBT.read();
delay(40);
if (comando == 69){ //lettera E (Hex 45)segue un treno di byte per SSID poi un byte=0 come separatore, poi un treno di byte per la password
ScriviWifi();
ESP.restart();
}
}
if (x == 10){
x = 0;
filenam[0] = 47;
filenam[1] = 0;
strcat(filenam,"nowifi.BMP");
bmpDraw(filenam, 0, 0, 0);
delay(1500);
tft.fillScreen(ST7735_BLACK);
}
delay(500);
x +=1;
}
tft.fillScreen(ST7735_BLACK);
WiFiClient client; // or WiFiClientSecure for HTTPS
HTTPClient http;
//http.useHTTP10(true);
http.begin("http://ip.seeip.org");
int response = http.GET();
while(response < 0){
filenam[0] = 47;
filenam[1] = 0;
strcat(filenam,"nointnet.BMP");
bmpDraw(filenam, 0, 0, 0);
delay(1500);
tft.fillScreen(ST7735_BLACK);
delay(10000);
response = http.GET();
//Serial.println(response);
}
configTime(0, 0, ntpServer);
getLocalTime(&timeinfo);
setenv("TZ","CET-1CEST,M3.5.0/2,M10.5.0/3",1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
http.end();
//radio.init(14);
}
void loop() {
if (SerialBT.available()) {
comando= SerialBT.read();
delay(40);
switch (comando) {
case 68: //lettera D (Hex 44): seguono 2 byte con i ritardi da settare
while (SerialBT.available()) {
comando= SerialBT.read();
}
break;
case 66: //lettera B (Hex 42): Test cambio stazione radio (seguono 2 bytes per la frequenza es. 97.4)
frequenza = 0;
comando= SerialBT.read();
frequenza = comando;
comando= SerialBT.read();
frequenza += int(comando)/10;
Serial.print("Frequenza impostata: ");
Serial.println(frequenza);
//radio.setFrequency(frequenza);
while (SerialBT.available()) {
comando= SerialBT.read();
}
break;
case 67: //lettera C (Hex 43): CAMBIO FONT segue 1 byte con il comando da eseguire
comando= SerialBT.read();
EEPROM.write(0, comando);
EEPROM.commit();
font = comando;
CalcolaFont();
minuti=66;
strcpy(orario,"AAAA");
while (SerialBT.available()) {
comando= SerialBT.read();
}
break;
case 69: // (hex 45) Nuove credenziali Wifi - vedi sopra durante la connessione wifi
ScriviWifi();
ESP.restart();
break;
}
}
time_t now;
time(&now);
localtime_r(&now, &timeinfo);
if (timeinfo.tm_min != minuti){
if (timeinfo.tm_wday == 0 && timeinfo.tm_hour == 3 && timeinfo.tm_min == 1 && timeinfo.tm_sec < 2){ //Ogni Domenica alle 3 aggiorna l'orario
AggiornaOrario();
minuti = 66;
strcpy(orario,"AAAA");
}
minuti = timeinfo.tm_min;
ore = timeinfo.tm_hour;
/* Serial.print("decina ore: ");
Serial.println(int(ore/10));
Serial.print("unita ore: ");
Serial.println(ore - (int(ore/10)*10));
Serial.print("decina minuti: ");
Serial.println(int(minuti/10));
Serial.print("unita minuti: ");
Serial.println(minuti - (int(minuti/10)*10)); */
if ( int(ore/10) != orario[0] ){ //Controllo se sono cambiate le decine delle ore
orario[0] = int(ore/10);
filenam[strlen(filenam)-5] = int(ore/10)+48;
bmpDraw(filenam, 0, 0, 0);
}
if ( ore - (int(ore/10)*10) != orario[1] ){ //Controllo se sono cambiate le unità delle ore
orario[1] = ore - (int(ore/10)*10);
filenam[strlen(filenam)-5] = ore - (int(ore/10)*10)+48;
bmpDraw(filenam, 0, 0, 1);
}
if ( int(minuti/10) != orario[2] ){ //Controllo se sono cambiate le decine dei minuti
orario[2] = int(minuti/10);
filenam[strlen(filenam)-5] = int(minuti/10)+48;
bmpDraw(filenam, 0, 0, 2);
}
orario[3] = minuti - (int(minuti/10)*10);
filenam[strlen(filenam)- 5] = minuti - (int(minuti/10)*10)+48;
bmpDraw(filenam, 0, 0, 3);
}
}
void printDirectory(File dir, int numTabs) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
break;
}
for (uint8_t i = 0; i < numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
if (entry.isDirectory()) {
printDirectory(entry, numTabs + 1);
} else {
// files have sizes, directories do not
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
}
entry.close();
filenam[0] = 0;
}
}
#define BUFFPIXEL 85
void bmpDraw(const char *filename, uint8_t x, uint16_t y, int schermo) {
File bmpFile;
int bmpWidth, bmpHeight; // W+H in pixels
uint8_t bmpDepth; // Bit depth (currently must be 24)
uint32_t bmpImageoffset; // Start of image data in file
uint32_t rowSize; // Not always = bmpWidth; may have padding
uint8_t sdbuffer[3*BUFFPIXEL]; // pixel buffer (R+G+B per pixel)
uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer
boolean goodBmp = false; // Set to true on valid header parse
boolean flip = true; // BMP is stored bottom-to-top
int w, h, row, col;
uint8_t r, g, b;
uint32_t pos = 0, startTime = millis();
switch (schermo) {
case 0: // Schermo decine ORE
if((x >= tft.width()) || (y >= tft.height())) return;
break;
case 1: // Schermo unità ORE
if((x >= tft1.width()) || (y >= tft1.height())) return;
break;
case 2: // Schermo decine MINUTI
if((x >= tft2.width()) || (y >= tft2.height())) return;
break;
case 3: // Schermo unità MINUTI
if((x >= tft3.width()) || (y >= tft3.height())) return;
break;
}
Serial.println();
Serial.print(F("Loading image '"));
Serial.print(filename);
Serial.println('\'');
// Open requested file on SD card
if ((bmpFile = SD.open(filename)) == NULL) {
Serial.print(F("File not found"));
return;
}
// Parse BMP header
if(read16(bmpFile) == 0x4D42) { // BMP signature
Serial.print(F("File size: ")); Serial.println(read32(bmpFile));
(void)read32(bmpFile); // Read & ignore creator bytes
bmpImageoffset = read32(bmpFile); // Start of image data
Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC);
// Read DIB header
Serial.print(F("Header size: ")); Serial.println(read32(bmpFile));
bmpWidth = read32(bmpFile);
bmpHeight = read32(bmpFile);
if(read16(bmpFile) == 1) { // # planes -- must be '1'
bmpDepth = read16(bmpFile); // bits per pixel
Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth);
if((bmpDepth == 24) && (read32(bmpFile) == 0)) { // 0 = uncompressed
goodBmp = true; // Supported BMP format -- proceed!
Serial.print(F("Image size: "));
Serial.print(bmpWidth);
Serial.print('x');
Serial.println(bmpHeight);
// BMP rows are padded (if needed) to 4-byte boundary
rowSize = (bmpWidth * 3 + 3) & ~3;
// If bmpHeight is negative, image is in top-down order.
// This is not canon but has been observed in the wild.
if(bmpHeight < 0) {
bmpHeight = -bmpHeight;
flip = false;
}
// Crop area to be loaded
w = bmpWidth;
h = bmpHeight;
switch (schermo) {
case 0: // Schermo decine ORE
if((x+w-1) >= tft.width()) w = tft.width() - x;
if((y+h-1) >= tft.height()) h = tft.height() - y;
// Set TFT address window to clipped image bounds
tft.startWrite();
tft.setAddrWindow(x, y, w, h);
break;
case 1: // Schermo unità ORE
if((x+w-1) >= tft1.width()) w = tft1.width() - x;
if((y+h-1) >= tft1.height()) h = tft1.height() - y;
// Set TFT address window to clipped image bounds
tft1.startWrite();
tft1.setAddrWindow(x, y, w, h);
break;
case 2: // Schermo decine MINUTI
if((x+w-1) >= tft2.width()) w = tft2.width() - x;
if((y+h-1) >= tft2.height()) h = tft2.height() - y;
// Set TFT address window to clipped image bounds
tft2.startWrite();
tft2.setAddrWindow(x, y, w, h);
break;
case 3: // Schermo unità MINUTI
if((x+w-1) >= tft3.width()) w = tft3.width() - x;
if((y+h-1) >= tft3.height()) h = tft3.height() - y;
// Set TFT address window to clipped image bounds
tft3.startWrite();
tft3.setAddrWindow(x, y, w, h);
break;
}
for (row=0; row<h; row++) { // For each scanline...
// Seek to start of scan line. It might seem labor-
// intensive to be doing this on every line, but this
// method covers a lot of gritty details like cropping
// and scanline padding. Also, the seek only takes
// place if the file position actually needs to change
// (avoids a lot of cluster math in SD library).
if(flip) // Bitmap is stored bottom-to-top order (normal BMP)
pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize;
else // Bitmap is stored top-to-bottom
pos = bmpImageoffset + row * rowSize;
if(bmpFile.position() != pos) { // Need seek?
switch (schermo) {
case 0: // Schermo decine ORE
tft.endWrite();
break;
case 1: // Schermo unità ORE
tft1.endWrite();
break;
case 2: // Schermo decine MINUTI
tft2.endWrite();
break;
case 3: // Schermo unità MINUTI
tft3.endWrite();
break;
}
bmpFile.seek(pos);
buffidx = sizeof(sdbuffer); // Force buffer reload
}
for (col=0; col<w; col++) { // For each pixel...
// Time to read more pixel data?
if (buffidx >= sizeof(sdbuffer)) { // Indeed
bmpFile.read(sdbuffer, sizeof(sdbuffer));
buffidx = 0; // Set index to beginning
switch (schermo) {
case 0: // Schermo decine ORE
tft.startWrite();
break;
case 1: // Schermo unità ORE
tft1.startWrite();
break;
case 2: // Schermo decine MINUTI
tft2.startWrite();
break;
case 3: // Schermo unità MINUTI
tft3.startWrite();
break;
}
}
// Convert pixel from BMP to TFT format, push to display
b = sdbuffer[buffidx++];
g = sdbuffer[buffidx++];
r = sdbuffer[buffidx++];
switch (schermo) {
case 0: // Schermo decine ORE
tft.pushColor(tft.color565(r,g,b));
break;
case 1: // Schermo unità ORE
tft1.pushColor(tft.color565(r,g,b));
break;
case 2: // Schermo decine MINUTI
tft2.pushColor(tft.color565(r,g,b));
break;
case 3: // Schermo unità MINUTI
tft3.pushColor(tft.color565(r,g,b));
break;
}
} // end pixel
} // end scanline
switch (schermo) {
case 0: // Schermo decine ORE
tft.endWrite();
break;
case 1: // Schermo unità ORE
tft1.endWrite();
break;
case 2: // Schermo decine MINUTI
tft2.endWrite();
break;
case 3: // Schermo unità MINUTI
tft3.endWrite();
break;
}
Serial.print(F("Loaded in "));
Serial.print(millis() - startTime);
Serial.println(" ms");
} // end goodBmp
}
}
bmpFile.close();
if(!goodBmp) Serial.println(F("BMP format not recognized."));
}
// These read 16- and 32-bit types from the SD card file.
// BMP data is stored little-endian, Arduino is little-endian too.
// May need to reverse subscript order if porting elsewhere.
uint16_t read16(File f) {
uint16_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read(); // MSB
return result;
}
uint32_t read32(File f) {
uint32_t result;
((uint8_t *)&result)[0] = f.read(); // LSB
((uint8_t *)&result)[1] = f.read();
((uint8_t *)&result)[2] = f.read();
((uint8_t *)&result)[3] = f.read(); // MSB
return result;
}
void ScriviWifi(){
strcpy(ssid,"");
strcpy(password,"");
boolean flag= false;
int x = 0;
while (SerialBT.available()) {
comando= SerialBT.read();
if (comando != 0){
if (!flag){
ssid[x]= comando;
}else{
password[x]= comando;
}
x+=1;
}else{
flag= true;
ssid[x]= '\0';
x = 0;
}
}
password[x]= '\0';
strcpy(credenziali.sid,ssid);
strcpy(credenziali.pwd,password);
//Serial.println(credenziali.sid);
//Serial.println(credenziali.pwd);
EEPROM.put(2, credenziali);
EEPROM.commit();
}
void AggiornaOrario(){
unsigned long currentMillis = millis();
while((WiFi.status() != WL_CONNECTED) && (currentMillis - previousMillis >=30000)) {
//Serial.print(millis());
WiFi.disconnect();
WiFi.reconnect();
previousMillis = currentMillis;
}
previousMillis = 0;
if(WiFi.status() == WL_CONNECTED) {
WiFiClient client; // or WiFiClientSecure for HTTPS
HTTPClient http;
//http.useHTTP10(true);
http.begin("http://ip.seeip.org");
int response = http.GET();
if (response > 0){
configTime(0, 0, ntpServer);
getLocalTime(&timeinfo);
setenv("TZ","CET-1CEST,M3.5.0/2,M10.5.0/3",1); // Now adjust the TZ. Clock settings are adjusted to show the new local time
tzset();
}
http.end();
}else{
WiFi.disconnect();
WiFi.reconnect();
}
}
void CalcolaFont(){
strcpy (filenam,"");
filenam[0] = 47;
int posizione = 1;
for (int z=2; z>-1; z--) {
/* Serial.print("font= ");
Serial.println(font);
Serial.print("z= ");
Serial.println(z);
Serial.print("Valore cifra: ");
Serial.println(font/pow(10,z));
Serial.print("Parte intera: ");
Serial.println(int(font/pow(10,z))); */
if (int(font/pow(10,z))!=0 || posizione != 1 || z==0){
filenam[posizione]= int(font/pow(10,z))+48;
/* Serial.print("Char in posizione ");
Serial.print(posizione);
Serial.print(" = ");
Serial.println(filenam[posizione]); */
font = font - int(font/pow(10,z))*pow(10,z);
posizione +=1;
}
}
filenam[posizione] = 47;
filenam[posizione+1] = 0;
strcat(filenam,"x.BMP");
/* Serial.print("risultato: ");
Serial.println(filenam); */
}
void Prova(){
strcpy(filenam,"");
for (int x = 48; x < 58; x++) {
strcat(filenam,"/6/");
filenam[3] = x;
filenam[4] = '\0';
strcat(filenam,".bmp");
Serial.print("File completo : ");
Serial.println(filenam);
File sourceFile = SD.open(filenam);
File destFile = SPIFFS.open(filenam, FILE_WRITE);
static uint8_t buf[512];
while( sourceFile.read( buf, 512) ) {
destFile.write( buf, 512 );
}
destFile.close();
sourceFile.close();
filenam[0] = 0;
}
}