-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserial.c
More file actions
214 lines (180 loc) · 5.22 KB
/
serial.c
File metadata and controls
214 lines (180 loc) · 5.22 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
#include "serial.h"
#include "crc16.h"
#include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#include <errno.h>
#define PORTA_COM "/dev/ttyUSB0" // TODO: deixar variavel configurada
#define BAUDRATE 9600
unsigned long millis_now() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000UL) + (tv.tv_usec / 1000UL);
}
SerialPort portaSerial; // variável global
int serialOpen(const char *portname, int baudrate, int databits, int parity, int stopbits)
{
portaSerial.fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
if (portaSerial.fd < 0)
{
perror("Erro ao abrir porta serial");
return 0;
}
memset(&portaSerial.tty, 0, sizeof(portaSerial.tty));
if (tcgetattr(portaSerial.fd, &portaSerial.tty) != 0)
{
perror("Erro em tcgetattr");
close(portaSerial.fd);
return 0;
}
speed_t speed;
switch (baudrate)
{
case 9600:
speed = B9600;
break;
case 19200:
speed = B19200;
break;
case 38400:
speed = B38400;
break;
case 57600:
speed = B57600;
break;
case 115200:
speed = B115200;
break;
default:
fprintf(stderr, "Baudrate inválido. Usando 9600.\n");
speed = B9600;
}
cfsetospeed(&portaSerial.tty, speed);
cfsetispeed(&portaSerial.tty, speed);
portaSerial.tty.c_cflag &= ~CSIZE;
portaSerial.tty.c_cflag |= (databits == 7) ? CS7 : CS8;
switch (parity)
{
case PARITY_EVEN:
portaSerial.tty.c_cflag |= PARENB;
portaSerial.tty.c_cflag &= ~PARODD;
break;
case PARITY_ODD:
portaSerial.tty.c_cflag |= PARENB;
portaSerial.tty.c_cflag |= PARODD;
break;
default:
portaSerial.tty.c_cflag &= ~PARENB;
break;
}
if (stopbits == TWOSTOPBITS)
portaSerial.tty.c_cflag |= CSTOPB;
else
portaSerial.tty.c_cflag &= ~CSTOPB;
portaSerial.tty.c_cflag |= CREAD | CLOCAL;
portaSerial.tty.c_lflag = 0;
portaSerial.tty.c_iflag = 0;
portaSerial.tty.c_oflag = 0;
portaSerial.tty.c_cc[VMIN] = 0;
portaSerial.tty.c_cc[VTIME] = 1; //VTIME = 1 → read() espera até 100 ms por um byte.
if (tcsetattr(portaSerial.fd, TCSANOW, &portaSerial.tty) != 0)
{
perror("Erro em tcsetattr");
close(portaSerial.fd);
return 0;
}
return 1;
}
int serialWrite(const char *data, int length)
{
return write(portaSerial.fd, data, length);
}
int serialClose(void)
{
return close(portaSerial.fd) == 0;
}
void exibeDados(const char *buffer, int length)
{
for (int i = 0; i < length; i++)
{
printf("%02X ", (unsigned char)buffer[i]);
}
printf("\n");
}
char *lerResposta(void)
{
static char buffer[256];
memset(buffer, 0, sizeof(buffer));
int bytesRecebidos = 0;
unsigned long inicio = millis_now();
unsigned long ultimoByte = inicio;
printf("🔍 Aguardando frame até %lu ms...\n", inicio + TIMEOUT_TOTAL_MS);
while (1)
{
int n = read(portaSerial.fd, buffer + bytesRecebidos, 1);
unsigned long agora = millis_now();
if (n > 0)
{
ultimoByte = agora;
bytesRecebidos += n;
}
else
{
if ((agora - ultimoByte) >= TIMEOUT_INTERBYTE_MS && bytesRecebidos > 0)
break;
if ((agora - inicio) >= TIMEOUT_TOTAL_MS)
{
printf("⏱️ Timeout global de %lu ms atingido.\n", agora - inicio);
return NULL;
}
usleep(100); // evita CPU 100%
}
}
if (bytesRecebidos < 5)
{
printf("⚠️ Resposta muito curta (%d bytes).\n", bytesRecebidos);
return NULL;
}
unsigned short crc_resp = (unsigned char)buffer[bytesRecebidos - 2] |
((unsigned char)buffer[bytesRecebidos - 1] << 8);
unsigned short crc_calc = CRC16(buffer, bytesRecebidos - 2);
if (crc_resp != crc_calc)
{
printf("❌ CRC inválido");
return NULL;
}
if (buffer[1] & 0x80)
{
printf("❗ Exceção Modbus recebida: Código 0x%02X\n", buffer[2]);
return NULL;
}
printf("📥 Resposta recebida (%d bytes): ", bytesRecebidos);
exibeDados(buffer, bytesRecebidos);
return buffer;
}
int modbusWrite(const char *req, int total) {
if (!serialOpen(PORTA_COM, BAUDRATE, 8, NOPARITY, TWOSTOPBITS)) {
fprintf(stderr, "❌ Erro ao abrir porta serial.\n");
return 0;
}
printf("📤 Enviando: ");
exibeDados(req, total);
if (serialWrite(req, total) != total) {
fprintf(stderr, "❌ Falha ao enviar dados.\n");
serialClose();
return 0;
}
char *resposta = lerResposta();
if (resposta) {
printf("✅ Resposta válida recebida.\n");
} else {
printf("❌ Nenhuma resposta válida.\n");
}
serialClose();
return 1;
}