-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComArduino.c
More file actions
333 lines (310 loc) · 13.3 KB
/
ComArduino.c
File metadata and controls
333 lines (310 loc) · 13.3 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
#include <stdio.h> // standard input / output functions
#include <stdlib.h>
#include <string.h> // string function definitions
#include <unistd.h> // UNIX standard function definitions
#include <fcntl.h> // File control definitions
#include <errno.h> // Error number definitions
#include <termios.h> // POSIX terminal control definitions
#include <sys/ioctl.h>
#include <time.h>
#include <stdbool.h>
#include "ComArduino.h"
#define NANO_PER_SEC 1000000000.0
char comStr[MAX_COM_NAME+1] = "/dev/ttyUSB0";
static int USB;
/*****************************************************************************/
/** Fecha a serial */
/*****************************************************************************/
void fechaSerial(void) {
close(USB);
}
/*****************************************************************************/
/** Configura a serial para trabalhar em modo RAW com o Arduino */
/** Reterna 0 OK */
/** -1 Não conseguiu obter parâmetros da serial */
/** -2 Não conseguiu desabilitar DTR */
/** -3 Não conseguiu hab/desab DTS */
/** -4 Não conseguiu configurar os flags de comunicação */
/*****************************************************************************/
int configuraSerial(void) {
// Obtém a configuração da porta
struct termios tty;
memset (&tty, 0, sizeof tty);
if ( tcgetattr ( USB, &tty ) != 0 ){
printf("Error %d from tcgetattr %s\n", errno,strerror(errno));
return -1;
}
// Desabilita o DTR
int dtr_flag = TIOCM_DTR;
if (ioctl(USB, TIOCMBIC, &dtr_flag) != 0) {
printf("Erro ao desabilitar DTR: %s\n", strerror(errno));
return -2;
}
// Habilita e depois desabilita RTS para resetar o Arduino
int rts_flag = TIOCM_RTS;
ioctl(USB, TIOCMBIS, &dtr_flag); // Ativar DTR
usleep(200000); // Atraso de 200 milissegundos
if (ioctl(USB, TIOCMBIC, &rts_flag) != 0) {
printf("Erro ao desabilitar RTS: %s\n", strerror(errno));
return -3;
}
// Define Baud Rate
cfsetospeed (&tty, B9600);
cfsetispeed (&tty, B9600);
//Define parâmetros de comunicação pela serial
tty.c_cflag &= ~PARENB; // Sem Paridade
tty.c_cflag &= ~CSTOPB; // 1 STOP BIT
tty.c_cflag &= ~CSIZE; // Limpa os bits de tamanho
tty.c_cflag |= CS8; // Define 8 bits por caractere
tty.c_cflag &= ~CRTSCTS; // Desativar controle de fluxo por hardware (RTS/CTS)
tty.c_lflag = 0; // Sem sinais, sem echo, sem processamento canônico
tty.c_oflag = 0; // Sem mapeamento, sem atrasos
tty.c_cc[VMIN] = 0; // Leitura não bloqueia
tty.c_cc[VTIME] = 10; // Timout de 1.0 segundos
//Ativar leitura e ignorar linhas de controle (DTR/DTS)
tty.c_cflag |= CREAD | CLOCAL; // Habilitar leitura, ignorar controle de modem
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // Desativar controle de fluxo por software
tty.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG); // Sem modo canônico, echo ou sinais (raw)
tty.c_oflag &= ~OPOST; // Sem processamento de saída (raw)
// Flush na porta, antes de aplicar os parâmetros
tcflush( USB, TCIFLUSH );
if ( tcsetattr ( USB, TCSANOW, &tty ) != 0) {
printf("Error %d from tcgetattr %s\n", errno,strerror(errno));
return -4;
}
return 0;
}
/*****************************************************************************/
/** */
/** Tenta abrir serial /dev/ttyS0 a /dev/ttyS9 */
/** Aplica configurações que levam o Arduino a resetar. */
/** Se conseguir abrir, realiza o ping para certificar que é o Arduino */
/** Retorna 0, se sucesso */
/** -1, se falha */
/*****************************************************************************/
int probeSerial(void){
int size = strlen(comStr);
int iniciarEm = comStr[size-1] - '0';
int comAtual = iniciarEm;
do {
//Abre a serial
USB = open( comStr, O_RDWR | O_NOCTTY | O_NDELAY);
if ( USB < 0 ) {
printf("Error %d opening %s %s\n", errno, comStr, strerror(errno));
}
else {
printf("Abriu COM %s\n", comStr);
if (configuraSerial() == 0) {
//Tempo para rebootar o Arduino Nano
usleep(2800000);
if (ping() == 0) {
return 0;
}
else
fechaSerial();
}
}
comAtual = (comAtual + 1) % 10;
comStr[size-1] = '0' + comAtual;
} while (comAtual != iniciarEm);
return -1;
}
/*****************************************************************************/
/** A troca de mensagem com o Arduino é sempre iniciada pela TV-Box */
/** O protocolo envolve o reconhecimento do caractere de ínico de mensagem */
/** '<' e do caractere finalizador de mensagem '>'. */
/** O Arduino tem apenas duas mensagens de retorno: */
/** <001,uptime em milissegundos> --> Resposta ao ping */
/** <002,OK> --> Resposta aos demais comandos */
/** */
/** As mensagens de comando são apenas 6: */
/** <100,0,0> --> PING */
/** <200,TEXTO,TIMEOUT> --> TIME (Linha 0, para sala, data e hora) */
/** <300,TEXTO,TIMEOUT> --> LECTURE_NAME (Linha 1, para nome da palestra) */
/** <400,TEXTO,TIMEOUT> --> SPEAKER (Linha 2, para nome do palestrante) */
/** <500,TEXTO,TIEMOUT> --> ATTENDEE (Linha 3, aponta participante registrado*/
/** <600,0,0> --> SUCCESS (Beep de sucesso no registro) */
/** <601,0,0> --> FAIL (Beep de falha no registro) */
/*****************************************************************************/
bool enviaRecebe(char* msg, char* recebido, int sizeRecebido) {
int n_written = write( USB, msg, strlen(msg) );
printf("Enviou %d chars\n", n_written);
int n_read = 0;
char buffer[1];
int posAtual = 0;
bool recvInProgress = false;
double timeOut = 5.0; // Cinco segundos de timeout
struct timespec now;
double espereAte;
double tempoAtual;
clock_gettime(CLOCK_REALTIME, &now);
espereAte = now.tv_sec + now.tv_nsec / NANO_PER_SEC + timeOut;
tempoAtual = now.tv_sec + now.tv_nsec / NANO_PER_SEC;
//Este loop controla o timeout na leitura do retorno
while (tempoAtual < espereAte){
clock_gettime(CLOCK_REALTIME, &now);
tempoAtual = now.tv_sec + now.tv_nsec / NANO_PER_SEC;
n_read = read(USB, buffer, 1);
if (n_read == 1) {
if (recvInProgress == false) {
//Precisa sincronizar com o início da mensagem
if (buffer[0] == '<')
recvInProgress = true;
continue;
}
else { //Recebendo a mensagem
if (buffer[0] != '>' ) {
//Protege contra estouro de buffer
if (posAtual < sizeRecebido-1)
recebido[posAtual++] = buffer[0];
}
else {
recebido[posAtual] = '\0';
return true;
}
}
}
}
recebido[posAtual] = '\0';
return false;
}
/*****************************************************************************/
/** Comando PING */
/*****************************************************************************/
int ping(void) {
printf("Vai enviar dados\n");
char msg[] = "<100,0,0>";
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "001") == 0) {
printf("Arduino encontrado em %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** Comando Time Linha 0 SALA DATA E HORA */
/*****************************************************************************/
int setTime(char* sala, int timeout) {
char msg[100];
time_t t = time(NULL);
struct tm tm = *localtime(&t);
sprintf(msg, "<200,%s %02d/%02d %02d:%02d,%d>",sala, tm.tm_mday, tm.tm_mon + 1, tm.tm_hour, tm.tm_min, timeout);
printf("Vai enviar dados\n");
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
printf("Mensagem Time enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** Comando Lecture Linha 1 NOME DA PALESTRA */
/*****************************************************************************/
int setLecture(char* disciplina, int timeout) {
char msg[100];
sprintf(msg,"<300,%s,%d>",disciplina, timeout);
printf("Vai enviar dados\n");
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido,80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
printf("Mensagem Disciplina enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** Comando Speaker Linha 2 NOME DO PALESTRANTE */
/*****************************************************************************/
int setSpeaker(char* prof, int timeout) {
char msg[100];
sprintf(msg,"<400,%s,%d>",prof, timeout);
printf("Vai enviar dados\n");
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
printf("Mensagem Prof enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** Comando Attendee Linha 3 NOME DE UM PARTICIPANTE QUE REGISTRA PRESENÇA */
/** Também é usado no processo de uso de teclado para exibir user/pass */
/*****************************************************************************/
int setAttendee(char* aluno, int timeout) {
char msg[100];
sprintf(msg,"<500,%s,%d>",aluno,timeout);
//printf("Vai enviar dados\n");
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
//printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
//printf("Mensagem Aluno enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** */
/*****************************************************************************/
int setSuccess(void) {
printf("Vai enviar dados\n");
char msg[100] = "<600,0,0>";
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
printf("Mensagem BUZZER sucesso enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}
/*****************************************************************************/
/** */
/*****************************************************************************/
int setFail(void) {
printf("Vai enviar dados\n");
char msg[100] = "<601,0,0>";
char recebido[80] = "";
bool ret = enviaRecebe(msg, recebido, 80);
printf("Recebeu %s\n", recebido);
if (!ret)
return -2;
char* strtokIndx = strtok(recebido,",");
if (strcmp(strtokIndx, "002") == 0) {
printf("Mensagem BUZZER falha enviada com sucesso %s\n", comStr);
return 0;
}
else
return -1;
}