]> sigrok.org Git - libserialport.git/blob - serialport.c
Initial version. Builds for Linux and Windows.
[libserialport.git] / serialport.c
1 /*
2  * This file is part of the libserialport project.
3  *
4  * Copyright (C) 2010-2012 Bert Vermeulen <bert@biot.com>
5  * Copyright (C) 2010-2012 Uwe Hermann <uwe@hermann-uwe.de>
6  * Copyright (C) 2013 Martin Ling <martin-libserialport@earth.li>
7  *
8  * This program is free software: you can redistribute it and/or modify
9  * it under the terms of the GNU Lesser General Public License as
10  * published by the Free Software Foundation, either version 3 of the
11  * License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
20  */
21
22 #include <string.h>
23 #include <sys/types.h>
24 #include <sys/stat.h>
25 #include <fcntl.h>
26 #include <unistd.h>
27 #ifdef _WIN32
28 #include <windows.h>
29 #else
30 #include <glob.h>
31 #include <termios.h>
32 #include <sys/ioctl.h>
33 #endif
34 #include <stdlib.h>
35 #include <errno.h>
36
37 #include "serialport.h"
38
39 static int sp_validate_port(struct sp_port *port)
40 {
41         if (port == NULL)
42                 return 0;
43 #ifdef _WIN32
44         if (port->hdl == INVALID_HANDLE_VALUE)
45                 return 0;
46 #else
47         if (port->fd < 0)
48                 return 0;
49 #endif
50         return 1;
51 }
52
53 #define CHECK_PORT() do { if (!sp_validate_port(port)) return SP_ERR_ARG; } while (0)
54
55 /**
56  * Open the specified serial port.
57  *
58  * @param port Pointer to empty port structure allocated by caller.
59  * @param portname Name of port to open.
60  * @param flags Flags to use when opening the serial port. Possible flags
61  *              are: SP_MODE_RDWR, SP_MODE_RDONLY, SP_MODE_NONBLOCK.
62  *
63  * @return SP_OK on success, SP_ERR_FAIL on failure,
64  *         or SP_ERR_ARG if an invalid port or name is passed.
65  */
66 int sp_open(struct sp_port *port, char *portname, int flags)
67 {
68         if (!port)
69                 return SP_ERR_ARG;
70
71         if (!portname)
72                 return SP_ERR_ARG;
73
74         port->name = portname;
75
76 #ifdef _WIN32
77         DWORD desired_access = 0, flags_and_attributes = 0;
78         /* Map 'flags' to the OS-specific settings. */
79         desired_access |= GENERIC_READ;
80         flags_and_attributes = FILE_ATTRIBUTE_NORMAL;
81         if (flags & SP_MODE_RDWR)
82                 desired_access |= GENERIC_WRITE;
83         if (flags & SP_MODE_NONBLOCK)
84                 flags_and_attributes |= FILE_FLAG_OVERLAPPED;
85
86         port->hdl = CreateFile(port->name, desired_access, 0, 0,
87                          OPEN_EXISTING, flags_and_attributes, 0);
88         if (port->hdl == INVALID_HANDLE_VALUE)
89                 return SP_ERR_FAIL;
90 #else
91         int flags_local = 0;
92         /* Map 'flags' to the OS-specific settings. */
93         if (flags & SP_MODE_RDWR)
94                 flags_local |= O_RDWR;
95         if (flags & SP_MODE_RDONLY)
96                 flags_local |= O_RDONLY;
97         if (flags & SP_MODE_NONBLOCK)
98                 flags_local |= O_NONBLOCK;
99
100         if ((port->fd = open(port->name, flags_local)) < 0)
101                 return SP_ERR_FAIL;
102 #endif
103
104         return SP_OK;
105 }
106
107 /**
108  * Close the specified serial port.
109  *
110  * @param port Pointer to port structure.
111  *
112  * @return SP_OK on success, SP_ERR_FAIL on failure,
113  *         or SP_ERR_ARG if an invalid port is passed.
114  */
115 int sp_close(struct sp_port *port)
116 {
117         CHECK_PORT();
118
119 #ifdef _WIN32
120         /* Returns non-zero upon success, 0 upon failure. */
121         if (CloseHandle(port->hdl) == 0)
122                 return SP_ERR_FAIL;
123 #else
124         /* Returns 0 upon success, -1 upon failure. */
125         if (close(port->fd) == -1)
126                 return SP_ERR_FAIL;
127 #endif
128
129         return SP_OK;
130 }
131
132 /**
133  * Flush serial port buffers.
134  *
135  * @param port Pointer to port structure.
136  *
137  * @return SP_OK on success, SP_ERR_FAIL on failure,
138  *         or SP_ERR_ARG if an invalid port is passed.
139  */
140 int sp_flush(struct sp_port *port)
141 {
142         CHECK_PORT();
143
144 #ifdef _WIN32
145         /* Returns non-zero upon success, 0 upon failure. */
146         if (PurgeComm(port->hdl, PURGE_RXCLEAR | PURGE_TXCLEAR) == 0)
147                 return SP_ERR_FAIL;
148 #else
149         /* Returns 0 upon success, -1 upon failure. */
150         if (tcflush(port->fd, TCIOFLUSH) < 0)
151                 return SP_ERR_FAIL;
152 #endif
153         return SP_OK;
154 }
155
156 /**
157  * Write a number of bytes to the specified serial port.
158  *
159  * @param port Pointer to port structure.
160  * @param buf Buffer containing the bytes to write.
161  * @param count Number of bytes to write.
162  *
163  * @return The number of bytes written, SP_ERR_FAIL on failure,
164  *         or SP_ERR_ARG if an invalid port is passed.
165  */
166 int sp_write(struct sp_port *port, const void *buf, size_t count)
167 {
168         CHECK_PORT();
169
170         if (!buf)
171                 return SP_ERR_ARG;
172
173 #ifdef _WIN32
174         DWORD written = 0;
175         /* Returns non-zero upon success, 0 upon failure. */
176         if (WriteFile(port->hdl, buf, count, &written, NULL) == 0)
177                 return SP_ERR_FAIL;
178         return written;
179 #else
180         /* Returns the number of bytes written, or -1 upon failure. */
181         ssize_t written = write(port->fd, buf, count);
182         if (written < 0)
183                 return SP_ERR_FAIL;
184         else
185                 return written;;
186 #endif
187 }
188
189 /**
190  * Read a number of bytes from the specified serial port.
191  *
192  * @param port Pointer to port structure.
193  * @param buf Buffer where to store the bytes that are read.
194  * @param count The number of bytes to read.
195  *
196  * @return The number of bytes read, SP_ERR_FAIL on failure,
197  *         or SP_ERR_ARG if an invalid port is passed.
198  */
199 int sp_read(struct sp_port *port, void *buf, size_t count)
200 {
201         CHECK_PORT();
202
203         if (!buf)
204                 return SP_ERR_ARG;
205
206 #ifdef _WIN32
207         DWORD bytes_read = 0;
208         /* Returns non-zero upon success, 0 upon failure. */
209         if (ReadFile(port->hdl, buf, count, &bytes_read, NULL) == 0)
210                 return SP_ERR_FAIL;
211         return bytes_read;
212 #else
213         ssize_t bytes_read;
214         /* Returns the number of bytes read, or -1 upon failure. */
215         if ((bytes_read = read(port->fd, buf, count)) < 0)
216                 return SP_ERR_FAIL;
217         return bytes_read;
218 #endif
219 }
220
221 /**
222  * Set serial parameters for the specified serial port.
223  *
224  * @param port Pointer to port structure.
225  * @param baudrate The baudrate to set.
226  * @param bits The number of data bits to use.
227  * @param parity The parity setting to use (0 = none, 1 = even, 2 = odd).
228  * @param stopbits The number of stop bits to use (1 or 2).
229  * @param flowcontrol The flow control settings to use (0 = none, 1 = RTS/CTS,
230  *                    2 = XON/XOFF).
231  *
232  * @return The number of bytes read, SP_ERR_FAIL on failure,
233  *         or SP_ERR_ARG if an invalid argument is passed.
234  */
235 int sp_set_params(struct sp_port *port, int baudrate,
236                               int bits, int parity, int stopbits,
237                               int flowcontrol, int rts, int dtr)
238 {
239         CHECK_PORT();
240
241 #ifdef _WIN32
242         DCB dcb;
243
244         if (!GetCommState(port->hdl, &dcb))
245                 return SP_ERR_FAIL;
246
247         switch (baudrate) {
248         /*
249          * The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
250          * have documented CBR_* macros.
251          */
252         case 110:
253                 dcb.BaudRate = CBR_110;
254                 break;
255         case 300:
256                 dcb.BaudRate = CBR_300;
257                 break;
258         case 600:
259                 dcb.BaudRate = CBR_600;
260                 break;
261         case 1200:
262                 dcb.BaudRate = CBR_1200;
263                 break;
264         case 2400:
265                 dcb.BaudRate = CBR_2400;
266                 break;
267         case 4800:
268                 dcb.BaudRate = CBR_4800;
269                 break;
270         case 9600:
271                 dcb.BaudRate = CBR_9600;
272                 break;
273         case 14400:
274                 dcb.BaudRate = CBR_14400; /* Not available on Unix? */
275                 break;
276         case 19200:
277                 dcb.BaudRate = CBR_19200;
278                 break;
279         case 38400:
280                 dcb.BaudRate = CBR_38400;
281                 break;
282         case 57600:
283                 dcb.BaudRate = CBR_57600;
284                 break;
285         case 115200:
286                 dcb.BaudRate = CBR_115200;
287                 break;
288         case 128000:
289                 dcb.BaudRate = CBR_128000; /* Not available on Unix? */
290                 break;
291         case 256000:
292                 dcb.BaudRate = CBR_256000; /* Not available on Unix? */
293                 break;
294         default:
295                 return SP_ERR_ARG;
296         }
297
298         switch (stopbits) {
299         /* Note: There's also ONE5STOPBITS == 1.5 (unneeded so far). */
300         case 1:
301                 dcb.StopBits = ONESTOPBIT;
302                 break;
303         case 2:
304                 dcb.StopBits = TWOSTOPBITS;
305                 break;
306         default:
307                 return SP_ERR_ARG;
308         }
309
310         switch (parity) {
311         /* Note: There's also SPACEPARITY, MARKPARITY (unneeded so far). */
312         case SP_PARITY_NONE:
313                 dcb.Parity = NOPARITY;
314                 break;
315         case SP_PARITY_EVEN:
316                 dcb.Parity = EVENPARITY;
317                 break;
318         case SP_PARITY_ODD:
319                 dcb.Parity = ODDPARITY;
320                 break;
321         default:
322                 return SP_ERR_ARG;
323         }
324
325         if (rts != -1) {
326                 if (rts)
327                         dcb.fRtsControl = RTS_CONTROL_ENABLE;
328                 else
329                         dcb.fRtsControl = RTS_CONTROL_DISABLE;
330         }
331
332         if (dtr != -1) {
333                 if (dtr)
334                         dcb.fDtrControl = DTR_CONTROL_ENABLE;
335                 else
336                         dcb.fDtrControl = DTR_CONTROL_DISABLE;
337         }
338
339         if (!SetCommState(port->hdl, &dcb))
340                 return SP_ERR_FAIL;
341 #else
342         struct termios term;
343         speed_t baud;
344         int controlbits;
345
346         if (tcgetattr(port->fd, &term) < 0)
347                 return SP_ERR_FAIL;
348
349         switch (baudrate) {
350         case 50:
351                 baud = B50;
352                 break;
353         case 75:
354                 baud = B75;
355                 break;
356         case 110:
357                 baud = B110;
358                 break;
359         case 134:
360                 baud = B134;
361                 break;
362         case 150:
363                 baud = B150;
364                 break;
365         case 200:
366                 baud = B200;
367                 break;
368         case 300:
369                 baud = B300;
370                 break;
371         case 600:
372                 baud = B600;
373                 break;
374         case 1200:
375                 baud = B1200;
376                 break;
377         case 1800:
378                 baud = B1800;
379                 break;
380         case 2400:
381                 baud = B2400;
382                 break;
383         case 4800:
384                 baud = B4800;
385                 break;
386         case 9600:
387                 baud = B9600;
388                 break;
389         case 19200:
390                 baud = B19200;
391                 break;
392         case 38400:
393                 baud = B38400;
394                 break;
395         case 57600:
396                 baud = B57600;
397                 break;
398         case 115200:
399                 baud = B115200;
400                 break;
401         case 230400:
402                 baud = B230400;
403                 break;
404 #if !defined(__APPLE__) && !defined(__OpenBSD__)
405         case 460800:
406                 baud = B460800;
407                 break;
408 #endif
409         default:
410                 return SP_ERR_ARG;
411         }
412
413         if (cfsetospeed(&term, baud) < 0)
414                 return SP_ERR_FAIL;
415
416         if (cfsetispeed(&term, baud) < 0)
417                 return SP_ERR_FAIL;
418
419         term.c_cflag &= ~CSIZE;
420         switch (bits) {
421         case 8:
422                 term.c_cflag |= CS8;
423                 break;
424         case 7:
425                 term.c_cflag |= CS7;
426                 break;
427         default:
428                 return SP_ERR_ARG;
429         }
430
431         term.c_cflag &= ~CSTOPB;
432         switch (stopbits) {
433         case 1:
434                 term.c_cflag &= ~CSTOPB;
435                 break;
436         case 2:
437                 term.c_cflag |= CSTOPB;
438                 break;
439         default:
440                 return SP_ERR_ARG;
441         }
442
443         term.c_iflag &= ~(IXON | IXOFF);
444         term.c_cflag &= ~CRTSCTS;
445         switch (flowcontrol) {
446         case 0:
447                 /* No flow control. */
448                 break;
449         case 1:
450                 term.c_cflag |= CRTSCTS;
451                 break;
452         case 2:
453                 term.c_iflag |= IXON | IXOFF;
454                 break;
455         default:
456                 return SP_ERR_ARG;
457         }
458
459         term.c_iflag &= ~IGNPAR;
460         term.c_cflag &= ~(PARODD | PARENB);
461         switch (parity) {
462         case SP_PARITY_NONE:
463                 term.c_iflag |= IGNPAR;
464                 break;
465         case SP_PARITY_EVEN:
466                 term.c_cflag |= PARENB;
467                 break;
468         case SP_PARITY_ODD:
469                 term.c_cflag |= PARENB | PARODD;
470                 break;
471         default:
472                 return SP_ERR_ARG;
473         }
474
475         /* Turn off all serial port cooking. */
476         term.c_iflag &= ~(ISTRIP | INLCR | ICRNL);
477         term.c_oflag &= ~(ONLCR | OCRNL | ONOCR);
478 #if !defined(__FreeBSD__) && !defined(__OpenBSD__) && !defined(__NetBSD__)
479         term.c_oflag &= ~OFILL;
480 #endif
481
482         /* Disable canonical mode, and don't echo input characters. */
483         term.c_lflag &= ~(ICANON | ECHO);
484
485         /* Write the configured settings. */
486         if (tcsetattr(port->fd, TCSADRAIN, &term) < 0)
487                 return SP_ERR_FAIL;
488
489         if (rts != -1) {
490                 controlbits = TIOCM_RTS;
491                 if (ioctl(port->fd, rts ? TIOCMBIS : TIOCMBIC,
492                                 &controlbits) < 0)
493                         return SP_ERR_FAIL;
494         }
495
496         if (dtr != -1) {
497                 controlbits = TIOCM_DTR;
498                 if (ioctl(port->fd, dtr ? TIOCMBIS : TIOCMBIC,
499                                 &controlbits) < 0)
500                         return SP_ERR_FAIL;
501         }
502 #endif
503
504         return SP_OK;
505 }
506
507 /**
508  * Get error code for failed operation.
509  *
510  * In order to obtain the correct result, this function should be called
511  * straight after the failure, before executing any other system operations.
512  *
513  * @return The system's numeric code for the error that caused the last
514  *         operation to fail.
515  */
516 int sp_last_error_code(void)
517 {
518 #ifdef _WIN32
519         return GetLastError();
520 #else
521         return errno;
522 #endif
523 }
524
525 /**
526  * Get error message for failed operation.
527  *
528  * In order to obtain the correct result, this function should be called
529  * straight after the failure, before executing other system operations.
530  *
531  * @return The system's message for the error that caused the last
532  *         operation to fail. This string may be allocated by the function,
533  *         and can be freed after use by calling sp_free_error_message.
534  */
535 char *sp_last_error_message(void)
536 {
537 #ifdef _WIN32
538         LPVOID message;
539         DWORD error = GetLastError();
540
541         FormatMessage(
542                 FORMAT_MESSAGE_ALLOCATE_BUFFER |
543                 FORMAT_MESSAGE_FROM_SYSTEM |
544                 FORMAT_MESSAGE_IGNORE_INSERTS,
545                 NULL,
546                 error,
547                 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
548                 (LPTSTR) &message,
549                 0, NULL );
550
551         return message;
552 #else
553         return strerror(errno);
554 #endif
555 }
556
557 /**
558  * Free error message.
559  *
560  * This function can be used to free a string returned by the
561  * sp_last_error_message function.
562  */
563 void sp_free_error_message(char *message)
564 {
565 #ifdef _WIN32
566         LocalFree(message);
567 #endif
568 }