-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathESP8266.ino
More file actions
105 lines (87 loc) · 2.57 KB
/
Copy pathESP8266.ino
File metadata and controls
105 lines (87 loc) · 2.57 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
#include <ESP8266WiFi.h>
//Troque pelos dados da sua rede
const char* ssid = "@allisonverdam";
const char* password = "10203040";
//Timeout da conexão
#define TIMEOUT 1000
#define MAX_BUFFER 300
//Server na porta 80 (padrão http)
WiFiServer server(80);
//Buffer onde serão gravados os bytes da comunicação
uint8_t buffer[MAX_BUFFER];
void setup() {
Serial.begin(115200);
//Envia a informação da rede para conectar
WiFi.disconnect();
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
//Espera a conexão com o access point
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//Inicializa o server
server.begin();
}
void loop() {
//Verifica se alguem se conectou
WiFiClient client = server.available();
if (!client) {
//Se ninguém conectou apenas retorna sem fazer nada
return;
}
//Marca o tempo que o cliente se conectou e a quantidade
//de bytes lidos
uint32_t connectedTime = millis();
int bytesRead = 0;
//Enquanto o cliente estiver conectado
while (client.connected())
{
//Tempo agora
uint32_t now = millis();
//Quanto tempo passou desde a conexão com o cliente
uint32_t ellapsed = now - connectedTime;
//Se o tempo passou do tempo máximo e não leu nenhum byte
if (ellapsed > TIMEOUT && bytesRead == 0)
{
//Fecha a conexão com o cliente
client.stop();
break;
}
int available = client.available();
//Se o cliente possui bytes a serem lidos
if (available)
{
int bufferSize = available < MAX_BUFFER ? available : MAX_BUFFER;
int readCount = client.read(buffer, bufferSize);
//Envia os bytes pela serial e aumenta o contador de bytes lidos
Serial.write(buffer, readCount);
Serial.flush();
bytesRead += readCount;
}
available = Serial.available();
//Se a serial possui bytes a serem lidos
if (available)
{
int bufferSize = available < MAX_BUFFER ? available : MAX_BUFFER;
//Lê os bytes
Serial.readBytes(buffer, bufferSize);
//Se for o byte que define a finalização da conexão
if (buffer[bufferSize - 1] == 127)
{
client.write(buffer, bufferSize - 1);
//Envia o que ainda não tenha sido enviado
client.flush();
//Espera um tempo para o cliente receber
delay(100);
//Fecha a conexão com o cliente e sai do 'while'
client.stop();
break;
}
//Envia os bytes para o cliente
client.write(buffer, bufferSize);
}
}//while(client.connected())
}//loop