-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp.c
144 lines (135 loc) · 2.55 KB
/
esp.c
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
#include "esp.h"
#include "str.h"
#include "uart.h"
#include "printf.h"
signed esp_init() {
const char *payload = "AT\r\n";
char buf[4096];
signed try = 0;
while(1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK")) {
break;
}
try++;
}
return try;
}
signed esp_mode(unsigned mode) {
char *payload = "AT+CWMODE=1\r\n";
switch(mode) {
case 0:
payload = "AT+CWMODE=0\r\n";
break;
case 1:
break;
case 2:
payload = "AT+CWMODE=2\r\n";
break;
default:
break;
}
char buf[4096];
unsigned try = 0;
while(1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK") || strstr(buf, "ready")) {
break;
}
try++;
}
return try;
}
signed esp_connect(const char *ssid, const char *pwd) {
char payload[2048];
char buf[4096];
snprintf(payload, sizeof(payload), "AT+CWJAP=\"%s\",\"%s\"\r\n", ssid, pwd);
unsigned try = 0;
while (1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK") || strstr(buf, "WIFI CONNECTED")) break;
try++;
}
return try;
}
signed esp_connection_mode(unsigned mode) {
char *payload = "AT+CIPMUX=1\r\n";
switch(mode) {
case 0:
payload = "AT+CIPMUX=0\r\n";
break;
case 1:
break;
case 2:
payload = "AT+CIPMUX=2\r\n";
break;
default:
break;
}
char buf[4096];
unsigned try = 0;
while(1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK")) {
break;
}
try++;
}
return try;
}
signed esp_checkip() {
const char *payload = "AT+CIFSR\r\n";
char buf[4096];
signed try = 0;
while(1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK") || strstr(buf, "WIFI CONNECTED")) {
break;
}
try++;
}
return try;
}
signed esp_listen(unsigned port) {
char payload[512];
char buf[4096];
snprintf(payload, sizeof(payload), "AT+CIPSERVER=1,%d\r\n", port);
unsigned try = 0;
while (1) {
zero(buf, sizeof(buf));
esp_tx(payload);
esp_rx(buf, sizeof(buf));
if (strstr(buf, "OK")) break;
try++;
}
return try;
}
void esp_tx(const char *payload) {
for (unsigned i = 0; i < strlen(payload); i++) {
uart_putc((unsigned int) payload[i]);
}
uart_flush();
}
unsigned int esp_rx(char buf[], unsigned buflen) {
unsigned bytes;
for (bytes = 0; uart_rx_has_data() && (bytes < buflen); bytes++) {
buf[bytes] = uart_getc();
}
buf[bytes] = '\0';
return bytes;
}
void zero(char buf[], unsigned len) {
for (unsigned i = 0; i < len; i++) {
buf[i] = '\0';
}
}