trying to tweak uart code, for better flashing
[proxmark3-svn] / client / uart.c
CommitLineData
5bcc76c4 1/*
2 * Proxmark3 generic uart / rs232/ serial port library
3 *
4 * Copyright (c) 2012, 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 * Partly based on uart-code written by Teunis van Beelen, available:
33 * http://www.teuniz.net/RS-232/index.html
34 *
35 */
36
37#include "uart.h"
38#include "messages.h"
39
40// Test if we are dealing with unix operating systems
41#ifndef _WIN32
42
43#include <termios.h>
44typedef struct termios term_info;
45typedef struct {
46 int fd; // Serial port file descriptor
47 term_info tiOld; // Terminal info before using the port
48 term_info tiNew; // Terminal info during the transaction
49} serial_port_unix;
50
51// Set time-out on 30 miliseconds
52const struct timeval timeout = {
53 .tv_sec = 0, // 0 second
54 .tv_usec = 30000 // 30000 micro seconds
55};
56
57// Work-around to claim uart interface using the c_iflag (software input processing) from the termios struct
58#define CCLAIMED 0x80000000
59
60serial_port uart_open(const char* pcPortName)
61{
62 serial_port_unix* sp = malloc(sizeof(serial_port_unix));
63
64 if (sp == 0) return INVALID_SERIAL_PORT;
65
66 sp->fd = open(pcPortName, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
67 if(sp->fd == -1)
68 {
69 uart_close(sp);
70 return INVALID_SERIAL_PORT;
71 }
72
73 if(tcgetattr(sp->fd,&sp->tiOld) == -1)
74 {
75 uart_close(sp);
76 return INVALID_SERIAL_PORT;
77 }
78
79 // Make sure the port is not claimed already
80 if (sp->tiOld.c_iflag & CCLAIMED)
81 {
82 uart_close(sp);
83 return CLAIMED_SERIAL_PORT;
84 }
85
86 // Copy the old terminal info struct
87 sp->tiNew = sp->tiOld;
88
89 sp->tiNew.c_cflag = CS8 | CLOCAL | CREAD;
90 sp->tiNew.c_iflag = CCLAIMED | IGNPAR;
91 sp->tiNew.c_oflag = 0;
92 sp->tiNew.c_lflag = 0;
0a24369c 93
94 // Set serial port equivalent to raw mode
95// sp->tiNew.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
96// sp->tiNew.c_oflag &= ~OPOST;
97// sp->tiNew.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
98// sp->tiNew.c_cflag &= ~(CSIZE | PARENB);
99// sp->tiNew.c_iflag |= CCLAIMED | IGNPAR;
100// sp->tiNew.c_cflag |= CS8 | CLOCAL | CREAD;
5bcc76c4 101
102 sp->tiNew.c_cc[VMIN] = 0; // block until n bytes are received
103 sp->tiNew.c_cc[VTIME] = 0; // block until a timer expires (n * 100 mSec.)
104
105 if(tcsetattr(sp->fd,TCSANOW,&sp->tiNew) == -1)
106 {
107 uart_close(sp);
108 return INVALID_SERIAL_PORT;
109 }
110
0a24369c 111 tcflush(sp->fd, TCIOFLUSH);
5bcc76c4 112 return sp;
113}
114
115void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed)
116{
117 DBG("Serial port speed requested to be set to %d bauds.", uiPortSpeed);
118 // Set port speed (Input and Output)
119 speed_t stPortSpeed = B9600;
120 switch(uiPortSpeed) {
121 case 9600: stPortSpeed = B9600;
122 break;
123 case 19200: stPortSpeed = B19200;
124 break;
125 case 38400: stPortSpeed = B38400;
126 break;
127 case 57600: stPortSpeed = B57600;
128 break;
129 case 115200: stPortSpeed = B115200;
130 break;
131 case 230400: stPortSpeed = B230400;
132 break;
133#ifdef B460800
134 case 460800: stPortSpeed = B460800;
135 break;
136#endif
137 default:
138#ifdef B460800
139 ERR("Unable to set serial port speed to %d bauds. Speed value must be one of these constants: 9600 (default), 19200, 38400, 57600, 115200, 230400 or 460800.", uiPortSpeed);
140#else
141 ERR("Unable to set serial port speed to %d bauds. Speed value must be one of these constants: 9600 (default), 19200, 38400, 57600, 115200 or 230400.", uiPortSpeed);
142#endif
143 };
144 const serial_port_unix* spu = (serial_port_unix*)sp;
145 cfsetispeed((struct termios*)&spu->tiNew, stPortSpeed);
146 cfsetospeed((struct termios*)&spu->tiNew, stPortSpeed);
147 if( tcsetattr(spu->fd, TCSADRAIN, &spu->tiNew) == -1)
148 {
149 ERR("Unable to apply new speed settings.");
150 }
151}
152
153uint32_t uart_get_speed(const serial_port sp)
154{
155 uint32_t uiPortSpeed = 0;
156 const serial_port_unix* spu = (serial_port_unix*)sp;
157 switch (cfgetispeed(&spu->tiNew))
158 {
159 case B9600: uiPortSpeed = 9600;
160 break;
161 case B19200: uiPortSpeed = 19200;
162 break;
163 case B38400: uiPortSpeed = 38400;
164 break;
165 case B57600: uiPortSpeed = 57600;
166 break;
167 case B115200: uiPortSpeed = 115200;
168 break;
169 case B230400: uiPortSpeed = 230400;
170 break;
171#ifdef B460800
172 case B460800: uiPortSpeed = 460800;
173 break;
174#endif
175 }
176
177 return uiPortSpeed;
178}
179
180void uart_close(const serial_port sp)
181{
0a24369c 182 tcflush(((serial_port_unix*)sp)->fd,TCIOFLUSH);
5bcc76c4 183 tcsetattr(((serial_port_unix*)sp)->fd,TCSANOW,&((serial_port_unix*)sp)->tiOld);
184 close(((serial_port_unix*)sp)->fd);
185 free(sp);
186}
187
188bool uart_cts(const serial_port sp)
189{
190 char status;
191 if (ioctl(((serial_port_unix*)sp)->fd,TIOCMGET,&status) < 0) return false;
192 return (status & TIOCM_CTS);
193}
194
195bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t* pszRxLen)
196{
197 int res;
198 int byteCount;
199 fd_set rfds;
200 struct timeval tv;
201
202 // Reset the output count
203 *pszRxLen = 0;
204
205 do {
206 // Reset file descriptor
207 FD_ZERO(&rfds);
208 FD_SET(((serial_port_unix*)sp)->fd,&rfds);
209 tv = timeout;
210 res = select(((serial_port_unix*)sp)->fd+1, &rfds, NULL, NULL, &tv);
211
212 // Read error
213 if (res < 0) {
214 DBG("RX error.");
215 return false;
216 }
217
218 // Read time-out
219 if (res == 0) {
220 if (*pszRxLen == 0) {
221 // Error, we received no data
222 DBG("RX time-out, buffer empty.");
223 return false;
224 } else {
225 // We received some data, but nothing more is available
226 return true;
227 }
228 }
229
230 // Retrieve the count of the incoming bytes
231 res = ioctl(((serial_port_unix*)sp)->fd, FIONREAD, &byteCount);
232 if (res < 0) return false;
233
234 // There is something available, read the data
235 res = read(((serial_port_unix*)sp)->fd,pbtRx+(*pszRxLen),byteCount);
236
237 // Stop if the OS has some troubles reading the data
238 if (res <= 0) return false;
239
240 *pszRxLen += res;
241
242 } while (byteCount);
243
244 return true;
245}
246
247bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen)
248{
249 int32_t res;
250 size_t szPos = 0;
251 fd_set rfds;
252 struct timeval tv;
253
254 while (szPos < szTxLen)
255 {
256 // Reset file descriptor
257 FD_ZERO(&rfds);
258 FD_SET(((serial_port_unix*)sp)->fd,&rfds);
259 tv = timeout;
260 res = select(((serial_port_unix*)sp)->fd+1, NULL, &rfds, NULL, &tv);
261
262 // Write error
263 if (res < 0) {
264 DBG("TX error.");
265 return false;
266 }
267
268 // Write time-out
269 if (res == 0) {
270 DBG("TX time-out.");
271 return false;
272 }
273
274 // Send away the bytes
275 res = write(((serial_port_unix*)sp)->fd,pbtTx+szPos,szTxLen-szPos);
276
277 // Stop if the OS has some troubles sending the data
278 if (res <= 0) return false;
279
280 szPos += res;
281 }
282 return true;
283}
284
285#else
286// The windows serial port implementation
287
288typedef struct {
289 HANDLE hPort; // Serial port handle
290 DCB dcb; // Device control settings
291 COMMTIMEOUTS ct; // Serial port time-out configuration
292} serial_port_windows;
293
a0bbdb76 294void upcase(char *p) {
295 while(*p != '\0') {
296 if(*p >= 97 && *p <= 122) {
297 *p -= 32;
298 }
299 ++p;
300 }
301}
302
5bcc76c4 303serial_port uart_open(const char* pcPortName)
304{
305 char acPortName[255];
306 serial_port_windows* sp = malloc(sizeof(serial_port_windows));
307
308 // Copy the input "com?" to "\\.\COM?" format
309 sprintf(acPortName,"\\\\.\\%s",pcPortName);
a0bbdb76 310 upcase(acPortName);
5bcc76c4 311
312 // Try to open the serial port
313 sp->hPort = CreateFileA(acPortName,GENERIC_READ|GENERIC_WRITE,0,NULL,OPEN_EXISTING,0,NULL);
314 if (sp->hPort == INVALID_HANDLE_VALUE)
315 {
316 uart_close(sp);
317 return INVALID_SERIAL_PORT;
318 }
319
320 // Prepare the device control
321 memset(&sp->dcb, 0, sizeof(DCB));
322 sp->dcb.DCBlength = sizeof(DCB);
323 if(!BuildCommDCBA("baud=9600 data=8 parity=N stop=1",&sp->dcb))
324 {
325 uart_close(sp);
326 return INVALID_SERIAL_PORT;
327 }
328
329 // Update the active serial port
330 if(!SetCommState(sp->hPort,&sp->dcb))
331 {
332 uart_close(sp);
333 return INVALID_SERIAL_PORT;
334 }
335
336 sp->ct.ReadIntervalTimeout = 0;
337 sp->ct.ReadTotalTimeoutMultiplier = 0;
338 sp->ct.ReadTotalTimeoutConstant = 30;
339 sp->ct.WriteTotalTimeoutMultiplier = 0;
340 sp->ct.WriteTotalTimeoutConstant = 30;
341
342 if(!SetCommTimeouts(sp->hPort,&sp->ct))
343 {
344 uart_close(sp);
345 return INVALID_SERIAL_PORT;
346 }
347
348 PurgeComm(sp->hPort, PURGE_RXABORT | PURGE_RXCLEAR);
349
350 return sp;
351}
352
353void uart_close(const serial_port sp)
354{
355 CloseHandle(((serial_port_windows*)sp)->hPort);
356 free(sp);
357}
358
359void uart_set_speed(serial_port sp, const uint32_t uiPortSpeed)
360{
361 serial_port_windows* spw;
362
363 DBG("Serial port speed requested to be set to %d bauds.", uiPortSpeed);
364 // Set port speed (Input and Output)
365 switch(uiPortSpeed) {
366 case 9600:
367 case 19200:
368 case 38400:
369 case 57600:
370 case 115200:
371 case 230400:
372 case 460800:
373 break;
374 default:
375 ERR("Unable to set serial port speed to %d bauds. Speed value must be one of these constants: 9600 (default), 19200, 38400, 57600, 115200, 230400 or 460800.", uiPortSpeed);
376 };
377
378 spw = (serial_port_windows*)sp;
379 spw->dcb.BaudRate = uiPortSpeed;
380 if (!SetCommState(spw->hPort, &spw->dcb))
381 {
382 ERR("Unable to apply new speed settings.");
383 }
384}
385
386uint32_t uart_get_speed(const serial_port sp)
387{
388 const serial_port_windows* spw = (serial_port_windows*)sp;
389 if (!GetCommState(spw->hPort, (serial_port)&spw->dcb))
390 return spw->dcb.BaudRate;
391
392 return 0;
393}
394
395bool uart_receive(const serial_port sp, byte_t* pbtRx, size_t* pszRxLen)
396{
397 ReadFile(((serial_port_windows*)sp)->hPort,pbtRx,*pszRxLen,(LPDWORD)pszRxLen,NULL);
398 return (*pszRxLen != 0);
399}
400
401bool uart_send(const serial_port sp, const byte_t* pbtTx, const size_t szTxLen)
402{
403 DWORD dwTxLen = 0;
404 return WriteFile(((serial_port_windows*)sp)->hPort,pbtTx,szTxLen,&dwTxLen,NULL);
405 return (dwTxLen != 0);
406}
407
408#endif
Impressum, Datenschutz