-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwidget-display.cpp
More file actions
477 lines (396 loc) · 12.8 KB
/
widget-display.cpp
File metadata and controls
477 lines (396 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ArduinoJson.h>
#include <Preferences.h>
#include <time.h>
#include <math.h>
// config
#define WIFI_SSID "NOME_REDE" // "Wokwi-GUEST" if using wokwi simulator
#define WIFI_PASS "SENHA_REDE" // "" on wokwi
// weather API
#define OWM_API_KEY "CHAVE_OWM"
#define OWM_CIDADE "Sao Paulo"
#define OWM_PAIS "BR"
// time zone
#define NTP_OFFSET -10800
// buttons
#define BOTAO_PROX 12
#define BOTAO_ANT 14
// hardware
#define LARG_TELA 128
#define ALT_TELA 64
#define OLED_RESET -1
#define OLED_ADDR 0x3C
#define DEBOUNCE_MS 200
Adafruit_SSD1306 display(LARG_TELA, ALT_TELA, &Wire, OLED_RESET);
Preferences prefs;
// modes
enum AppMode {
MODO_RELOGIO = 0,
MODO_CLIMA,
MODO_MUSICA,
MODO_TOTAL
};
AppMode modoAtual = MODO_RELOGIO;
const char* TITULOS_MODOS[MODO_TOTAL] = {
" Relogio",
" Clima",
" Musica"
};
// display region
struct Regiao { int x, y, w, h; };
const Regiao CIMA = {0, 0, 128, 12};
const Regiao CORPO = {0, 13, 128, 43};
const Regiao BAIXO = {0, 57, 128, 7};
void limpaRegiao(Regiao r) {
display.fillRect(r.x, r.y, r.w, r.h, SSD1306_BLACK);
}
// header and base
void renderCabecalho(const char* titulo) {
limpaRegiao(CIMA);
display.drawFastHLine(0, 11, 128, SSD1306_WHITE);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(2, 2);
display.print(titulo);
// mode indicator
for (int i = 0; i < (int)MODO_TOTAL; i++) {
int x = 128 - (MODO_TOTAL - i) * 7;
if (i == (int)modoAtual)
display.fillCircle(x, 5, 2, SSD1306_WHITE);
else
display.drawCircle(x, 5, 2, SSD1306_WHITE);
}
}
// clock mode
struct EstadoRelogio {
bool ntpSincronizado;
int hora, minuto, segundo;
int dia, mes, ano;
char diaSemana[4];
};
EstadoRelogio relogio = {false, 0, 0, 0, 1, 1, 2026, "---"};
const char* DIAS_SEMANA[] = {"Dom","Seg","Ter","Qua","Qui","Sex","Sab"};
void sincronizaNTP() {
if (WiFi.status() != WL_CONNECTED) return;
configTime(NTP_OFFSET, 0, "pool.ntp.org");
}
void atualizaRelogio() {
struct tm timeinfo;
if (getLocalTime(&timeinfo)) {
relogio.hora = timeinfo.tm_hour;
relogio.minuto = timeinfo.tm_min;
relogio.segundo = timeinfo.tm_sec;
relogio.dia = timeinfo.tm_mday;
relogio.mes = timeinfo.tm_mon + 1;
relogio.ano = timeinfo.tm_year + 1900;
strncpy(relogio.diaSemana, DIAS_SEMANA[timeinfo.tm_wday], 4);
relogio.ntpSincronizado = true;
} else {
// fallback
static unsigned long ultimo = 0;
if (millis() - ultimo >= 1000UL) {
ultimo = millis();
if (++relogio.segundo >= 60) { relogio.segundo = 0;
if (++relogio.minuto >= 60) { relogio.minuto = 0;
if (++relogio.hora >= 24) { relogio.hora = 0;
relogio.dia++; }}}
}
}
}
void renderRelogio() {
limpaRegiao(CORPO);
char bufHora[6], bufSeg[3], bufData[18];
sprintf(bufHora, "%02d:%02d", relogio.hora, relogio.minuto);
sprintf(bufSeg, "%02d", relogio.segundo);
sprintf(bufData, "%s %02d/%02d/%04d",
relogio.diaSemana, relogio.dia, relogio.mes, relogio.ano);
// hour
display.setTextSize(3);
int xHora = (LARG_TELA - 6 * 3 * 5) / 2;
display.setCursor(xHora, CORPO.y + 4);
display.print(bufHora);
// sec
display.setTextSize(1);
display.setCursor(110, CORPO.y + 10);
display.print(bufSeg);
// date
int xData = (LARG_TELA - (int)strlen(bufData) * 6) / 2;
display.setCursor(xData, CORPO.y + 32);
display.print(bufData);
// ANTP sinc
if (relogio.ntpSincronizado) {
display.setCursor(120, CORPO.y + 32);
display.print("*");
}
}
// weather mode
struct EstadoClima {
char descricao[24];
int temperatura;
int sensacao;
int humidade;
float vento; // km/h
bool dadosValidos;
unsigned long ultimaBusca;
};
EstadoClima clima = {"---", 0, 0, 0, 0.0f, false, 0};
#define INTERVALO_CLIMA 300000UL
// icons
const uint8_t ICO_SOL[] PROGMEM = {
0b00010000, 0b01010100, 0b00111000, 0b11111110,
0b00111000, 0b01010100, 0b00010000, 0b00000000
};
const uint8_t ICO_NUVEM[] PROGMEM = {
0b00000000, 0b00111000, 0b01111100, 0b11111110,
0b11111110, 0b01111100, 0b00000000, 0b00000000
};
const uint8_t ICO_CHUVA[] PROGMEM = {
0b00111000, 0b01111100, 0b11111110, 0b01111100,
0b00101000, 0b01000100, 0b00101000, 0b01000100
};
const uint8_t ICO_NEVE[] PROGMEM = {
0b00010000, 0b01010100, 0b00111000, 0b11010110,
0b00111000, 0b01010100, 0b00010000, 0b00000000
};
const uint8_t ICO_TEMPESTADE[] PROGMEM = {
0b00111100, 0b01111110, 0b11111110, 0b01111100,
0b00011000, 0b00110000, 0b00011000, 0b00000000
};
void desenhaIconeClima(int x, int y) {
const uint8_t* ico = ICO_NUVEM;
String d = String(clima.descricao);
d.toLowerCase();
if (d.indexOf("sol") >= 0 || d.indexOf("clear") >= 0) ico = ICO_SOL;
else if (d.indexOf("chuva") >= 0 || d.indexOf("rain") >= 0) ico = ICO_CHUVA;
else if (d.indexOf("neve") >= 0 || d.indexOf("snow") >= 0) ico = ICO_NEVE;
else if (d.indexOf("trovoada")>=0 || d.indexOf("thunder")>=0) ico = ICO_TEMPESTADE;
display.drawBitmap(x, y, ico, 8, 8, SSD1306_WHITE);
}
void buscaClima() {
if (WiFi.status() != WL_CONNECTED) return;
if (clima.dadosValidos && millis() - clima.ultimaBusca < INTERVALO_CLIMA) return;
HTTPClient http;
char url[256];
snprintf(url, sizeof(url),
"http://api.openweathermap.org/data/2.5/weather"
"?q=%s,%s&appid=%s&units=metric&lang=pt_br",
OWM_CIDADE, OWM_PAIS, OWM_API_KEY);
http.begin(url);
int code = http.GET();
if (code == 200) {
String payload = http.getString();
StaticJsonDocument<1024> doc;
if (!deserializeJson(doc, payload)) {
clima.temperatura = (int)roundf((float)doc["main"]["temp"]);
clima.sensacao = (int)roundf((float)doc["main"]["feels_like"]);
clima.humidade = doc["main"]["humidity"];
clima.vento = (float)doc["wind"]["speed"] * 3.6f;
const char* d = doc["weather"][0]["description"];
if (d) strncpy(clima.descricao, d, sizeof(clima.descricao) - 1);
clima.dadosValidos = true;
clima.ultimaBusca = millis();
}
}
http.end();
}
void renderClima() {
limpaRegiao(CORPO);
if (!clima.dadosValidos) {
display.setTextSize(1);
display.setCursor(14, CORPO.y + 16);
display.print("Buscando dados...");
return;
}
desenhaIconeClima(2, CORPO.y + 2);
char desc[24];
strncpy(desc, clima.descricao, sizeof(desc) - 1);
desc[0] = toupper(desc[0]);
display.setTextSize(1);
display.setCursor(14, CORPO.y + 2);
display.print(desc);
// temp
display.setTextSize(2);
display.setCursor(2, CORPO.y + 14);
display.print(clima.temperatura);
display.setTextSize(1);
display.print((char)247);
display.print("C");
// sensation, humidity, wind
display.setCursor(60, CORPO.y + 14);
display.print("Sens:"); display.print(clima.sensacao); display.print((char)247);
display.setCursor(60, CORPO.y + 24);
display.print("Hum: "); display.print(clima.humidade); display.print("%");
display.setCursor(60, CORPO.y + 34);
display.print("Vento:"); display.print((int)clima.vento); display.print("km/h");
}
// music mode
#define NUM_BARRAS 16
#define ALTURA_MAX (CORPO.h - 4)
#define INTERVALO_ESPECTRO 80
#define PICO_HOLD_MS 800
#define PICO_QUEDA_MS 50
int espectro[NUM_BARRAS];
int espectroAnt[NUM_BARRAS];
int pico[NUM_BARRAS];
unsigned long tempoPico[NUM_BARRAS];
float envelope[NUM_BARRAS];
unsigned long ultimoEspectro = 0;
// simulated spectrum
void inicializaEspectro() {
for (int i = 0; i < NUM_BARRAS; i++) {
espectro[i] = 0;
espectroAnt[i] = 0;
pico[i] = 0;
tempoPico[i] = 0;
float norm = (float)i / (NUM_BARRAS - 1);
envelope[i] = 0.3f + 0.7f * sinf(norm * 3.14159f);
}
}
void atualizaEspectro() {
if (millis() - ultimoEspectro < (unsigned long)INTERVALO_ESPECTRO) return;
ultimoEspectro = millis();
for (int i = 0; i < NUM_BARRAS; i++) {
espectroAnt[i] = espectro[i];
int alvo = (int)(random(4, ALTURA_MAX) * envelope[i]);
espectro[i] = (espectroAnt[i] * 6 + alvo * 4) / 10;
if (espectro[i] > pico[i]) {
pico[i] = espectro[i];
tempoPico[i] = millis();
} else if (millis() - tempoPico[i] > PICO_HOLD_MS) {
unsigned long tempoApos = millis() - tempoPico[i] - PICO_HOLD_MS;
if (tempoApos > (unsigned long)PICO_QUEDA_MS * (pico[i] - espectro[i])) {
if (pico[i] > 0) pico[i]--;
}
}
}
}
void renderEspectro() {
limpaRegiao(CORPO);
int largBarra = CORPO.w / NUM_BARRAS;
for (int i = 0; i < NUM_BARRAS; i++) {
int h = espectro[i];
int x = CORPO.x + i * largBarra;
int y = CORPO.y + CORPO.h - h;
display.fillRect(x + 1, y, largBarra - 2, h, SSD1306_WHITE);
if (pico[i] > 2) {
int yPico = CORPO.y + CORPO.h - pico[i] - 2;
display.drawFastHLine(x + 1, yPico, largBarra - 2, SSD1306_WHITE);
}
}
}
// config
void salvaConfiguracoes() {
prefs.begin("widget", false);
prefs.putInt("modo", (int)modoAtual);
prefs.end();
}
void carregaConfiguracoes() {
prefs.begin("widget", true);
int m = prefs.getInt("modo", 0);
if (m >= 0 && m < (int)MODO_TOTAL) modoAtual = (AppMode)m;
prefs.end();
}
// buttons
unsigned long ultimoBotao = 0;
bool proximoApertado() { return digitalRead(BOTAO_PROX) == LOW; }
bool anteriorApertado() { return digitalRead(BOTAO_ANT) == LOW; }
void verificaBotoes() {
if (millis() - ultimoBotao < DEBOUNCE_MS) return;
if (proximoApertado()) {
modoAtual = (AppMode)((modoAtual + 1) % MODO_TOTAL);
salvaConfiguracoes();
ultimoBotao = millis();
return;
}
if (anteriorApertado()) {
modoAtual = (AppMode)((modoAtual + MODO_TOTAL - 1) % MODO_TOTAL);
salvaConfiguracoes();
ultimoBotao = millis();
}
}
// render
unsigned long ultimaRenderizacao = 0;
#define INTERVALO_RENDER 100
void renderModoAtual() {
switch (modoAtual) {
case MODO_RELOGIO: renderRelogio(); break;
case MODO_CLIMA: renderClima(); break;
case MODO_MUSICA: renderEspectro(); break;
default: break;
}
}
void renderFrame() {
renderCabecalho(TITULOS_MODOS[modoAtual]);
renderModoAtual();
limpaRegiao(BAIXO);
display.display();
}
// boot screen
void splash() {
display.clearDisplay();
display.drawRect(1, 1, 126, 62, SSD1306_WHITE);
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(20, 10); display.print("WIDGET DISPLAY");
display.setCursor(18, 38); display.print("Inicializando...");
display.display();
delay(1500);
}
void telaConexaoWifi() {
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(SSD1306_WHITE);
display.setCursor(4, 4); display.print("Conectando WiFi:");
display.setCursor(4, 16); display.print(WIFI_SSID);
display.display();
WiFi.begin(WIFI_SSID, WIFI_PASS);
int tentativas = 0;
while (WiFi.status() != WL_CONNECTED && tentativas < 20) {
delay(500);
display.print(".");
display.display();
tentativas++;
}
display.setCursor(4, 34);
if (WiFi.status() == WL_CONNECTED) {
display.print("OK! IP: ");
display.println(WiFi.localIP());
} else {
display.print("offline");
}
display.display();
delay(1200);
}
void setup() {
Serial.begin(115200);
Serial.println("\n=== Widget Display ===");
pinMode(BOTAO_PROX, INPUT_PULLUP);
pinMode(BOTAO_ANT, INPUT_PULLUP);
if (!display.begin(SSD1306_SWITCHCAPVCC, OLED_ADDR)) {
Serial.println("ERRO: SSD1306 nao encontrado. Verifique I2C.");
while (true) delay(1000);
}
display.setTextWrap(false);
display.clearDisplay();
splash();
telaConexaoWifi();
carregaConfiguracoes();
sincronizaNTP();
inicializaEspectro();
buscaClima();
Serial.println("Sistema pronto.");
}
void loop() {
verificaBotoes();
atualizaRelogio();
if (modoAtual == MODO_CLIMA) buscaClima();
if (modoAtual == MODO_MUSICA) atualizaEspectro();
if (millis() - ultimaRenderizacao >= INTERVALO_RENDER) {
ultimaRenderizacao = millis();
renderFrame();
}
}