-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy paththingspeak.ino
More file actions
100 lines (79 loc) · 2.41 KB
/
thingspeak.ino
File metadata and controls
100 lines (79 loc) · 2.41 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
void enviaDados()
{
char Fields[100];
//verifica se está conectado no WiFi e se é o momento de enviar dados ao ThingSpeak
if (!client.connected() && (millis() - ultimaConexao > INTERVALO_ENVIO_THINGSPEAK))
{
sprintf(
Fields,
"field1=%d&field2=%d&field3=%d&field4=%d&field5=%d&field6=%d",
UmidadeInternaTruncada,
TemperaturaInternaTruncada,
UmidadeExternaTruncada,
TemperaturaExternaTruncada,
(int)luzAcesa,
(int)ventilacaoLigada
);
Serial.print("- Enviando dados: ");
Serial.println(Fields);
post(Fields);
}
}
void recebeDados()
{
//verifica se está conectado no WiFi e se é o momento de recuperar os dados do ThingSpeak
if (!client.connected() && (millis() - ultimaConexaoLeitura > INTERVALO_LEITURA_THINGSPEAK))
{
String comando = get();
Serial.println(comando);
}
}
void post(String StringDados)
{
if (client.connect(EnderecoAPIThingSpeak, 80))
{
//faz a requisição HTTP ao ThingSpeak
client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: " + ChaveEscritaThingSpeak + "\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(StringDados.length());
client.print("\n\n");
client.print(StringDados);
ultimaConexao = millis();
Serial.println("- Informações enviadas ao ThingSpeak!");
}
client.stop();
}
String get()
{
String talkBackCommand;
if (client.connect(EnderecoAPIThingSpeak, 80))
{
//faz a requisição HTTP ao ThingSpeak
client.print("GET /talkbacks/" + talkBackID + "/commands/execute?api_key=" + talkBackAPIKey + " HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("\n");
delay(1000);
while (client.available()) {
String line = client.readStringUntil('\n');
//actual content starts after empty line (that has length 1)
if (line.length() == 1) {
talkBackCommand = client.readStringUntil('\n');
break;
}
}
ultimaConexaoLeitura = millis();
if (talkBackCommand.length() > 1) {
Serial.print("- Comando: ");
Serial.println(talkBackCommand);
}
client.stop();
} else {
Serial.println("- Connection failed");
}
return talkBackCommand;
}