]> git.zerfleddert.de Git - proxmark3-svn/blob - client/uart.c
FIX: the changes to uart.c timings seems to have fixed my problem with the pm3...
[proxmark3-svn] / client / uart.c
1 /*
2 * Generic uart / rs232/ serial port library
3 *
4 * Copyright (c) 2013, Roel Verdult
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions are met:
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
14 * 3. Neither the name of the copyright holders nor the
15 * names of its contributors may be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY
19 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY
22 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 *
29 * @file uart.c
30 * @brief
31 *
32 */
33
34 #include "uart.h"
35
36 // Test if we are dealing with unix operating systems
37 #ifndef _WIN32
38
39 #include <termios.h>
40 typedef struct termios term_info;
41 typedef struct {
42 int fd; // Serial port file descriptor
43 term_info tiOld; // Terminal info before using the port
44 term_info tiNew; // Terminal info during the transaction
45 } serial_port_unix;
46
47 // Set time-out on 30 miliseconds
48 const struct timeval timeout = {
49 .tv_sec = 0, // 0 second
50 .tv_usec = 30000 // 30000 micro seconds
51 };
52
53 serial_port uart_open(const char* pcPortName)
54 {
55 serial_port_unix* sp = malloc(sizeof(serial_port_unix));
56 if (sp == 0) return INVALID_SERIAL_PORT;
57
58 sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
59 if(sp->fd == -1) {
60 uart_close(sp);
61 return INVALID_SERIAL_PORT;
62 }
63
64 // Finally figured out a way to claim a serial port interface under unix
65 // We just try to set a (advisory) lock on the file descriptor
66 struct flock fl;
67 fl.l_type = F_WRLCK;
68 fl.l_whence = SEEK_SET;
69 fl.l_start = 0;
70 fl.l_len = 0;
71 fl.l_pid = getpid();
72
73 // Does the system allows us to place a lock on this file descriptor
74 if (fcntl(sp->fd, F_SETLK, &fl) == -1) {
75 // A conflicting lock is held by another process
76 free(sp);
77 return CLAIMED_SERIAL_PORT;
78 }
79
80 // Try to retrieve the old (current) terminal info struct
81 if(tcgetattr(sp->fd,&sp->tiOld) == -1) {
82 uart_close(sp);
83 return INVALID_SERIAL_PORT;
84 }
85
86 // Duplicate the (old) terminal info struct
87 sp->tiNew = sp->tiOld;
88
89 // Configure the serial port
90 sp->tiNew.c_cflag = CS8 | CLOCAL | CREAD;
91 sp->tiNew.c_iflag = IGNPAR;
92 sp->tiNew.c_oflag = 0;
93 sp->tiNew.c_lflag = 0;
94
95 // Block until n bytes are received
96 sp->tiNew.c_cc[VMIN] = 0;
97 // Block until a timer expires (n * 100 mSec.)
98 sp->tiNew.c_cc[VTIME] = 0;
99
100 // Try to set the new terminal info struct
101 if(tcsetattr(sp->fd,TCSANOW,&sp->tiNew) == -1) {
102 uart_close(sp);
103 return INVALID_SERIAL_PORT;
104 }
105
106 // Flush all lingering data that may exist
107 tcflush(sp->fd, TCIOFLUSH);
108
109 return sp;
110 }
111
112 void uart_close(const serial_port sp) {
113 serial_port_unix* spu = (serial_port_unix*)sp;
114 tcflush(spu->fd,TCIOFLUSH);
115 tcsetattr(spu->fd,TCSANOW,&(spu->tiOld));
116 struct flock fl;
117 fl.l_type = F_UNLCK;
118 fl.l_whence = SEEK_SET;
119 fl.l_start = 0;
120 fl.l_len = 0;
121 fl.l_pid = getpid();
122
123 // Does the system allows us to place a lock on this file descriptor
124 int err = fcntl(spu->fd, F_SETLK, &fl);
125 if ( err == -1) {
126 //perror("fcntl");
127 }
128 close(spu->fd);
129 free(sp);
130 }
131
132 bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) {
133 const serial_port_unix* spu = (serial_port_unix*)sp;
134 speed_t stPortSpeed;
135 switch (uiPortSpeed) {
136 case 0: stPortSpeed = B0; break;
137 case 50: stPortSpeed = B50; break;
138 case 75: stPortSpeed = B75; break;
139 case 110: stPortSpeed = B110; break;
140 case 134: stPortSpeed = B134; break;
141 case 150: stPortSpeed = B150; break;
142 case 300: stPortSpeed = B300; break;
143 case 600: stPortSpeed = B600; break;
144 case 1200: stPortSpeed = B1200; break;
145 case 1800: stPortSpeed = B1800; break;
146 case 2400: stPortSpeed = B2400; break;
147 case 4800: stPortSpeed = B4800; break;
148 case 9600: stPortSpeed = B9600; break;
149 case 19200: stPortSpeed = B19200; break;
150 case 38400: stPortSpeed = B38400; break;
151 # ifdef B57600
152 case 57600: stPortSpeed = B57600; break;
153 # endif
154 # ifdef B115200
155 case 115200: stPortSpeed = B115200; break;
156 # endif
157 # ifdef B230400
158 case 230400: stPortSpeed = B230400; break;
159 # endif
160 # ifdef B460800
161 case 460800: stPortSpeed = B460800; break;
162 # endif
163 # ifdef B921600
164 case 921600: stPortSpeed = B921600; break;
165 # endif
166 default: return false;
167 };
168 struct termios ti;
169 if (tcgetattr(spu->fd,&ti) == -1) return false;
170 // Set port speed (Input and Output)
171 cfsetispeed(&ti,stPortSpeed);
172 cfsetospeed(&ti,stPortSpeed);
173 return (tcsetattr(spu->fd,TCSANOW,&ti) != -1);
174 }
175
176 uint32_t uart_get_speed(const serial_port sp) {
177 struct termios ti;
178 uint32_t uiPortSpeed;
179 const serial_port_unix* spu = (serial_port_unix*)sp;
180 if (tcgetattr(spu->fd,&ti) == -1) return 0;
181 // Set port speed (Input)
182 speed_t stPortSpeed = cfgetispeed(&ti);
183 switch (stPortSpeed) {
184 case B0: uiPortSpeed = 0; break;
185 case B50: uiPortSpeed = 50; break;
186 case B75: uiPortSpeed = 75; break;
187 case B110: uiPortSpeed = 110; break;
188 case B134: uiPortSpeed = 134; break;
189 case B150: uiPortSpeed = 150; break;
190 case B300: uiPortSpeed = 300; break;
191 case B600: uiPortSpeed = 600; break;
192 case B1200: uiPortSpeed = 1200; break;
193 case B1800: uiPortSpeed = 1800; break;
194 case B2400: uiPortSpeed = 2400; break;
195 case B4800: uiPortSpeed = 4800; break;
196 case B9600: uiPortSpeed = 9600; break;
197 case B19200: uiPortSpeed = 19200; break;
198 case B38400: uiPortSpeed = 38400; break;
199 # ifdef B57600
200 case B57600: uiPortSpeed = 57600; break;
201 # endif
202 # ifdef B115200
203 case B115200: uiPortSpeed = 115200; break;
204 # endif
205 # ifdef B230400
206 case B230400: uiPortSpeed = 230400; break;
207 # endif
208 # ifdef B460800
209 case B460800: uiPortSpeed = 460800; break;
210 # endif
211 # ifdef B921600
212 case B921600: uiPortSpeed = 921600; break;
213 # endif
214 default: return 0;
215 };
216 return uiPortSpeed;
217 }
218
219 bool uart_set_parity(serial_port sp, serial_port_parity spp) {
220 struct termios ti;
221 const serial_port_unix* spu = (serial_port_unix*)sp;
222 if (tcgetattr(spu->fd,&ti) == -1) return false;
223 switch(spp) {
224 case SP_INVALID: return false;
225 case SP_NONE: ti.c_cflag &= ~(PARENB | PARODD); break;
226 case SP_EVEN: ti.c_cflag |= PARENB; ti.c_cflag &= ~(PARODD); break;
227 case SP_ODD: ti.c_cflag |= PARENB | PARODD; break;
228 }
229 return (tcsetattr(spu->fd,TCSANOW,&ti) != -1);
230 }
231
232 serial_port_parity uart_get_parity(const serial_port sp) {
233 struct termios ti;
234 const serial_port_unix* spu = (serial_port_unix*)sp;
235 if (tcgetattr(spu->fd,&ti) == -1) return SP_INVALID;
236
237 if (ti.c_cflag & PARENB) {
238 if (ti.c_cflag & PARODD) {
239 return SP_ODD;
240 } else {
241 return SP_EVEN;
242 }
243 } else {
244 return SP_NONE;
245 }
246 }
247
248 bool uart_cts(const serial_port sp) {
249 char status;
250 if (ioctl(((serial_port_unix*)sp)->fd,TIOCMGET,&status) < 0) return false;
251 return (status & TIOCM_CTS);
252 }
253
254 bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t* pszRxLen) {
255
256 int res;
257 int byteCount;
258 fd_set rfds;
259 struct timeval tv;
260
261 // Reset the output count
262 *pszRxLen = 0;
263
264 do {
265 // Reset file descriptor
266 FD_ZERO(&rfds);
267 FD_SET(((serial_port_unix*)sp)->fd,&rfds);
268 tv = timeout;
269 res = select(((serial_port_unix*)sp)->fd+1, &rfds, NULL, NULL, &tv);
270
271 // Read error
272 if (res < 0) {
273 return false;
274 }
275
276 // Read time-out
277 if (res == 0) {
278 if (*pszRxLen == 0) {
279 // Error, we received no data
280 return false;
281 } else {
282 // We received some data, but nothing more is available
283 return true;
284 }
285 }
286
287 // Retrieve the count of the incoming bytes
288 res = ioctl(((serial_port_unix*)sp)->fd, FIONREAD, &byteCount);
289 if (res < 0) return false;
290
291 // There is something available, read the data
292 res = read(((serial_port_unix*)sp)->fd,pbtRx+(*pszRxLen),byteCount);
293
294 // Stop if the OS has some troubles reading the data
295 if (res <= 0) return false;
296
297 *pszRxLen += res;
298
299 if(res==byteCount)
300 return true;
301
302 } while (byteCount);
303
304 return true;
305 }
306
307 bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen) {
308 int32_t res;
309 size_t szPos = 0;
310 fd_set rfds;
311 struct timeval tv;
312
313 while (szPos < szTxLen) {
314 // Reset file descriptor
315 FD_ZERO(&rfds);
316 FD_SET(((serial_port_unix*)sp)->fd,&rfds);
317 tv = timeout;
318 res = select(((serial_port_unix*)sp)->fd+1, NULL, &rfds, NULL, &tv);
319
320 // Write error
321 if (res < 0) {
322 return false;
323 }
324
325 // Write time-out
326 if (res == 0) {
327 return false;
328 }
329
330 // Send away the bytes
331 res = write(((serial_port_unix*)sp)->fd,pbtTx+szPos,szTxLen-szPos);
332
333 // Stop if the OS has some troubles sending the data
334 if (res <= 0) return false;
335
336 szPos += res;
337 }
338 return true;
339 }
340
341 #else
342 // The windows serial port implementation
343
344 typedef struct {
345 HANDLE hPort; // Serial port handle
346 DCB dcb; // Device control settings
347 COMMTIMEOUTS ct; // Serial port time-out configuration
348 } serial_port_windows;
349
350 void upcase(char *p) {
351 while(*p != '\0') {
352 if(*p >= 97 && *p <= 122) {
353 *p -= 32;
354 }
355 ++p;
356 }
357 }
358
359 serial_port uart_open(const char* pcPortName) {
360 char acPortName[255];
361 serial_port_windows* sp = malloc(sizeof(serial_port_windows));
362
363 // Copy the input "com?" to "\\.\COM?" format
364 sprintf(acPortName,"\\\\.\\%s",pcPortName);
365 upcase(acPortName);
366
367 // Try to open the serial port
368 sp->hPort = CreateFileA(acPortName,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
369 if (sp->hPort == INVALID_HANDLE_VALUE) {
370 uart_close(sp);
371 return INVALID_SERIAL_PORT;
372 }
373
374 // Prepare the device control
375 memset(&sp->dcb, 0, sizeof(DCB));
376 sp->dcb.DCBlength = sizeof(DCB);
377 if(!BuildCommDCBA("baud=115200 parity=N data=8 stop=1",&sp->dcb)) {
378 uart_close(sp);
379 return INVALID_SERIAL_PORT;
380 }
381
382 // Update the active serial port
383 if(!SetCommState(sp->hPort,&sp->dcb)) {
384 uart_close(sp);
385 return INVALID_SERIAL_PORT;
386 }
387
388 sp->ct.ReadIntervalTimeout = 1;
389 sp->ct.ReadTotalTimeoutMultiplier = 1;
390 sp->ct.ReadTotalTimeoutConstant = 30;
391 sp->ct.WriteTotalTimeoutMultiplier = 1;
392 sp->ct.WriteTotalTimeoutConstant = 30;
393
394 if(!SetCommTimeouts(sp->hPort,&sp->ct)) {
395 uart_close(sp);
396 return INVALID_SERIAL_PORT;
397 }
398
399 PurgeComm(sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR);
400
401 return sp;
402 }
403
404 void uart_close(const serial_port sp) {
405 CloseHandle(((serial_port_windows*)sp)->hPort);
406 free(sp);
407 }
408
409 bool uart_set_speed(serial_port sp, const uint32_t uiPortSpeed) {
410 serial_port_windows* spw;
411 spw = (serial_port_windows*)sp;
412 spw->dcb.BaudRate = uiPortSpeed;
413 return SetCommState(spw->hPort, &spw->dcb);
414 }
415
416 uint32_t uart_get_speed(const serial_port sp) {
417 const serial_port_windows* spw = (serial_port_windows*)sp;
418 if (!GetCommState(spw->hPort, (serial_port)&spw->dcb)) {
419 return spw->dcb.BaudRate;
420 }
421 return 0;
422 }
423
424 bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t* pszRxLen) {
425 ReadFile(((serial_port_windows*)sp)->hPort,pbtRx,*pszRxLen,(LPDWORD)pszRxLen,NULL);
426 return (*pszRxLen != 0);
427 }
428
429 bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen) {
430 DWORD dwTxLen = 0;
431 return WriteFile(((serial_port_windows*)sp)->hPort,pbtTx,szTxLen,&dwTxLen,NULL);
432 return (dwTxLen != 0);
433 }
434
435 #endif
Impressum, Datenschutz