forked from sigrokproject/libserialport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialport.c
2624 lines (2141 loc) · 60.7 KB
/
serialport.c
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This file is part of the libserialport project.
*
* Copyright (C) 2010-2012 Bert Vermeulen <[email protected]>
* Copyright (C) 2010-2015 Uwe Hermann <[email protected]>
* Copyright (C) 2013-2015 Martin Ling <[email protected]>
* Copyright (C) 2013 Matthias Heidbrink <[email protected]>
* Copyright (C) 2014 Aurelien Jacobs <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "libserialport_internal.h"
static const struct std_baudrate std_baudrates[] = {
#ifdef _WIN32
/*
* The baudrates 50/75/134/150/200/1800/230400/460800 do not seem to
* have documented CBR_* macros.
*/
BAUD(110), BAUD(300), BAUD(600), BAUD(1200), BAUD(2400), BAUD(4800),
BAUD(9600), BAUD(14400), BAUD(19200), BAUD(38400), BAUD(57600),
BAUD(115200), BAUD(128000), BAUD(256000),
#else
BAUD(50), BAUD(75), BAUD(110), BAUD(134), BAUD(150), BAUD(200),
BAUD(300), BAUD(600), BAUD(1200), BAUD(1800), BAUD(2400), BAUD(4800),
BAUD(9600), BAUD(19200), BAUD(38400), BAUD(57600), BAUD(115200),
BAUD(230400),
#if !defined(__APPLE__) && !defined(__OpenBSD__)
BAUD(460800),
#endif
#endif
};
#define NUM_STD_BAUDRATES ARRAY_SIZE(std_baudrates)
void (*sp_debug_handler)(const char *format, ...) = sp_default_debug_handler;
static enum sp_return get_config(struct sp_port *port, struct port_data *data,
struct sp_port_config *config);
static enum sp_return set_config(struct sp_port *port, struct port_data *data,
const struct sp_port_config *config);
SP_API enum sp_return sp_get_port_by_name(const char *portname, struct sp_port **port_ptr)
{
struct sp_port *port;
#ifndef NO_PORT_METADATA
enum sp_return ret;
#endif
size_t len;
TRACE("%s, %p", portname, port_ptr);
if (!port_ptr)
RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
*port_ptr = NULL;
if (!portname)
RETURN_ERROR(SP_ERR_ARG, "Null port name");
DEBUG_FMT("Building structure for port %s", portname);
#if !defined(_WIN32) && defined(HAVE_REALPATH)
/*
* get_port_details() below tries to be too smart and figure out
* some transport properties from the port name which breaks with
* symlinks. Therefore we canonicalize the portname first.
*/
char pathbuf[PATH_MAX + 1];
char *res = realpath(portname, pathbuf);
if (!res)
RETURN_ERROR(SP_ERR_ARG, "Could not retrieve realpath behind port name");
portname = pathbuf;
#endif
if (!(port = malloc(sizeof(struct sp_port))))
RETURN_ERROR(SP_ERR_MEM, "Port structure malloc failed");
len = strlen(portname) + 1;
if (!(port->name = malloc(len))) {
free(port);
RETURN_ERROR(SP_ERR_MEM, "Port name malloc failed");
}
memcpy(port->name, portname, len);
#ifdef _WIN32
port->usb_path = NULL;
port->hdl = INVALID_HANDLE_VALUE;
port->write_buf = NULL;
port->write_buf_size = 0;
#else
port->fd = -1;
#endif
port->description = NULL;
port->transport = SP_TRANSPORT_NATIVE;
port->usb_bus = -1;
port->usb_address = -1;
port->usb_vid = -1;
port->usb_pid = -1;
port->usb_manufacturer = NULL;
port->usb_product = NULL;
port->usb_serial = NULL;
port->bluetooth_address = NULL;
#ifndef NO_PORT_METADATA
if ((ret = get_port_details(port)) != SP_OK) {
sp_free_port(port);
return ret;
}
#endif
*port_ptr = port;
RETURN_OK();
}
SP_API char *sp_get_port_name(const struct sp_port *port)
{
TRACE("%p", port);
if (!port)
return NULL;
RETURN_STRING(port->name);
}
SP_API char *sp_get_port_description(const struct sp_port *port)
{
TRACE("%p", port);
if (!port || !port->description)
return NULL;
RETURN_STRING(port->description);
}
SP_API enum sp_transport sp_get_port_transport(const struct sp_port *port)
{
TRACE("%p", port);
RETURN_INT(port ? port->transport : SP_TRANSPORT_NATIVE);
}
SP_API enum sp_return sp_get_port_usb_bus_address(const struct sp_port *port,
int *usb_bus,int *usb_address)
{
TRACE("%p", port);
if (!port)
RETURN_ERROR(SP_ERR_ARG, "Null port");
if (port->transport != SP_TRANSPORT_USB)
RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
if (port->usb_bus < 0 || port->usb_address < 0)
RETURN_ERROR(SP_ERR_SUPP, "Bus and address values are not available");
if (usb_bus)
*usb_bus = port->usb_bus;
if (usb_address)
*usb_address = port->usb_address;
RETURN_OK();
}
SP_API enum sp_return sp_get_port_usb_vid_pid(const struct sp_port *port,
int *usb_vid, int *usb_pid)
{
TRACE("%p", port);
if (!port)
RETURN_ERROR(SP_ERR_ARG, "Null port");
if (port->transport != SP_TRANSPORT_USB)
RETURN_ERROR(SP_ERR_ARG, "Port does not use USB transport");
if (port->usb_vid < 0 || port->usb_pid < 0)
RETURN_ERROR(SP_ERR_SUPP, "VID:PID values are not available");
if (usb_vid)
*usb_vid = port->usb_vid;
if (usb_pid)
*usb_pid = port->usb_pid;
RETURN_OK();
}
SP_API char *sp_get_port_usb_manufacturer(const struct sp_port *port)
{
TRACE("%p", port);
if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_manufacturer)
return NULL;
RETURN_STRING(port->usb_manufacturer);
}
SP_API char *sp_get_port_usb_product(const struct sp_port *port)
{
TRACE("%p", port);
if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_product)
return NULL;
RETURN_STRING(port->usb_product);
}
SP_API char *sp_get_port_usb_serial(const struct sp_port *port)
{
TRACE("%p", port);
if (!port || port->transport != SP_TRANSPORT_USB || !port->usb_serial)
return NULL;
RETURN_STRING(port->usb_serial);
}
SP_API char *sp_get_port_bluetooth_address(const struct sp_port *port)
{
TRACE("%p", port);
if (!port || port->transport != SP_TRANSPORT_BLUETOOTH
|| !port->bluetooth_address)
return NULL;
RETURN_STRING(port->bluetooth_address);
}
SP_API enum sp_return sp_get_port_handle(const struct sp_port *port,
void *result_ptr)
{
TRACE("%p, %p", port, result_ptr);
if (!port)
RETURN_ERROR(SP_ERR_ARG, "Null port");
if (!result_ptr)
RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
#ifdef _WIN32
HANDLE *handle_ptr = result_ptr;
*handle_ptr = port->hdl;
#else
int *fd_ptr = result_ptr;
*fd_ptr = port->fd;
#endif
RETURN_OK();
}
SP_API enum sp_return sp_copy_port(const struct sp_port *port,
struct sp_port **copy_ptr)
{
TRACE("%p, %p", port, copy_ptr);
if (!copy_ptr)
RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
*copy_ptr = NULL;
if (!port)
RETURN_ERROR(SP_ERR_ARG, "Null port");
if (!port->name)
RETURN_ERROR(SP_ERR_ARG, "Null port name");
DEBUG("Copying port structure");
RETURN_INT(sp_get_port_by_name(port->name, copy_ptr));
}
SP_API void sp_free_port(struct sp_port *port)
{
TRACE("%p", port);
if (!port) {
DEBUG("Null port");
RETURN();
}
DEBUG("Freeing port structure");
if (port->name)
free(port->name);
if (port->description)
free(port->description);
if (port->usb_manufacturer)
free(port->usb_manufacturer);
if (port->usb_product)
free(port->usb_product);
if (port->usb_serial)
free(port->usb_serial);
if (port->bluetooth_address)
free(port->bluetooth_address);
#ifdef _WIN32
if (port->usb_path)
free(port->usb_path);
if (port->write_buf)
free(port->write_buf);
#endif
free(port);
RETURN();
}
SP_PRIV struct sp_port **list_append(struct sp_port **list,
const char *portname)
{
void *tmp;
size_t count;
for (count = 0; list[count]; count++)
;
if (!(tmp = realloc(list, sizeof(struct sp_port *) * (count + 2))))
goto fail;
list = tmp;
if (sp_get_port_by_name(portname, &list[count]) != SP_OK)
goto fail;
list[count + 1] = NULL;
return list;
fail:
sp_free_port_list(list);
return NULL;
}
SP_API enum sp_return sp_list_ports(struct sp_port ***list_ptr)
{
#ifndef NO_ENUMERATION
struct sp_port **list;
int ret;
#endif
TRACE("%p", list_ptr);
if (!list_ptr)
RETURN_ERROR(SP_ERR_ARG, "Null result pointer");
*list_ptr = NULL;
#ifdef NO_ENUMERATION
RETURN_ERROR(SP_ERR_SUPP, "Enumeration not supported on this platform");
#else
DEBUG("Enumerating ports");
if (!(list = malloc(sizeof(struct sp_port *))))
RETURN_ERROR(SP_ERR_MEM, "Port list malloc failed");
list[0] = NULL;
ret = list_ports(&list);
if (ret == SP_OK) {
*list_ptr = list;
} else {
sp_free_port_list(list);
*list_ptr = NULL;
}
RETURN_CODEVAL(ret);
#endif
}
SP_API void sp_free_port_list(struct sp_port **list)
{
unsigned int i;
TRACE("%p", list);
if (!list) {
DEBUG("Null list");
RETURN();
}
DEBUG("Freeing port list");
for (i = 0; list[i]; i++)
sp_free_port(list[i]);
free(list);
RETURN();
}
#define CHECK_PORT() do { \
if (!port) \
RETURN_ERROR(SP_ERR_ARG, "Null port"); \
if (!port->name) \
RETURN_ERROR(SP_ERR_ARG, "Null port name"); \
} while (0)
#ifdef _WIN32
#define CHECK_PORT_HANDLE() do { \
if (port->hdl == INVALID_HANDLE_VALUE) \
RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
} while (0)
#else
#define CHECK_PORT_HANDLE() do { \
if (port->fd < 0) \
RETURN_ERROR(SP_ERR_ARG, "Port not open"); \
} while (0)
#endif
#define CHECK_OPEN_PORT() do { \
CHECK_PORT(); \
CHECK_PORT_HANDLE(); \
} while (0)
#ifdef WIN32
/** To be called after port receive buffer is emptied. */
static enum sp_return restart_wait(struct sp_port *port)
{
DWORD wait_result;
if (port->wait_running) {
/* Check status of running wait operation. */
if (GetOverlappedResult(port->hdl, &port->wait_ovl,
&wait_result, FALSE)) {
DEBUG("Previous wait completed");
port->wait_running = FALSE;
} else if (GetLastError() == ERROR_IO_INCOMPLETE) {
DEBUG("Previous wait still running");
RETURN_OK();
} else {
RETURN_FAIL("GetOverlappedResult() failed");
}
}
if (!port->wait_running) {
/* Start new wait operation. */
if (WaitCommEvent(port->hdl, &port->events,
&port->wait_ovl)) {
DEBUG("New wait returned, events already pending");
} else if (GetLastError() == ERROR_IO_PENDING) {
DEBUG("New wait running in background");
port->wait_running = TRUE;
} else {
RETURN_FAIL("WaitCommEvent() failed");
}
}
RETURN_OK();
}
#endif
SP_API enum sp_return sp_open(struct sp_port *port, enum sp_mode flags)
{
struct port_data data;
struct sp_port_config config;
enum sp_return ret;
TRACE("%p, 0x%x", port, flags);
CHECK_PORT();
if (flags > SP_MODE_READ_WRITE)
RETURN_ERROR(SP_ERR_ARG, "Invalid flags");
DEBUG_FMT("Opening port %s", port->name);
#ifdef _WIN32
DWORD desired_access = 0, flags_and_attributes = 0, errors;
char *escaped_port_name;
COMSTAT status;
/* Prefix port name with '\\.\' to work with ports above COM9. */
if (!(escaped_port_name = malloc(strlen(port->name) + 5)))
RETURN_ERROR(SP_ERR_MEM, "Escaped port name malloc failed");
sprintf(escaped_port_name, "\\\\.\\%s", port->name);
/* Map 'flags' to the OS-specific settings. */
flags_and_attributes = FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED;
if (flags & SP_MODE_READ)
desired_access |= GENERIC_READ;
if (flags & SP_MODE_WRITE)
desired_access |= GENERIC_WRITE;
port->hdl = CreateFileA(escaped_port_name, desired_access, 0, 0,
OPEN_EXISTING, flags_and_attributes, 0);
free(escaped_port_name);
if (port->hdl == INVALID_HANDLE_VALUE)
RETURN_FAIL("Port CreateFile() failed");
/* All timeouts initially disabled. */
port->timeouts.ReadIntervalTimeout = 0;
port->timeouts.ReadTotalTimeoutMultiplier = 0;
port->timeouts.ReadTotalTimeoutConstant = 0;
port->timeouts.WriteTotalTimeoutMultiplier = 0;
port->timeouts.WriteTotalTimeoutConstant = 0;
if (SetCommTimeouts(port->hdl, &port->timeouts) == 0) {
sp_close(port);
RETURN_FAIL("SetCommTimeouts() failed");
}
/* Prepare OVERLAPPED structures. */
#define INIT_OVERLAPPED(ovl) do { \
memset(&port->ovl, 0, sizeof(port->ovl)); \
port->ovl.hEvent = INVALID_HANDLE_VALUE; \
if ((port->ovl.hEvent = CreateEvent(NULL, TRUE, TRUE, NULL)) \
== INVALID_HANDLE_VALUE) { \
sp_close(port); \
RETURN_FAIL(#ovl "CreateEvent() failed"); \
} \
} while (0)
INIT_OVERLAPPED(read_ovl);
INIT_OVERLAPPED(write_ovl);
INIT_OVERLAPPED(wait_ovl);
/* Set event mask for RX and error events. */
if (SetCommMask(port->hdl, EV_RXCHAR | EV_ERR) == 0) {
sp_close(port);
RETURN_FAIL("SetCommMask() failed");
}
port->writing = FALSE;
port->wait_running = FALSE;
ret = restart_wait(port);
if (ret < 0) {
sp_close(port);
RETURN_CODEVAL(ret);
}
#else
int flags_local = O_NONBLOCK | O_NOCTTY | O_CLOEXEC;
/* Map 'flags' to the OS-specific settings. */
if ((flags & SP_MODE_READ_WRITE) == SP_MODE_READ_WRITE)
flags_local |= O_RDWR;
else if (flags & SP_MODE_READ)
flags_local |= O_RDONLY;
else if (flags & SP_MODE_WRITE)
flags_local |= O_WRONLY;
if ((port->fd = open(port->name, flags_local)) < 0)
RETURN_FAIL("open() failed");
/*
* On POSIX in the default case the file descriptor of a serial port
* is not opened exclusively. Therefore the settings of a port are
* overwritten if the serial port is opened a second time. Windows
* opens all serial ports exclusively.
* So the idea is to open the serial ports alike in the exclusive mode.
*
* ioctl(*, TIOCEXCL) defines the file descriptor as exclusive. So all
* further open calls on the serial port will fail.
*
* There is a race condition if two processes open the same serial
* port. None of the processes will notice the exclusive ownership of
* the other process because ioctl() doesn't return an error code if
* the file descriptor is already marked as exclusive.
* This can be solved with flock(). It returns an error if the file
* descriptor is already locked by another process.
*/
#ifdef HAVE_FLOCK
if (flock(port->fd, LOCK_EX | LOCK_NB) < 0)
RETURN_FAIL("flock() failed");
#endif
#ifdef TIOCEXCL
/*
* Before Linux 3.8 ioctl(*, TIOCEXCL) was not implemented and could
* lead to EINVAL or ENOTTY.
* These errors aren't fatal and can be ignored.
*/
if (ioctl(port->fd, TIOCEXCL) < 0 && errno != EINVAL && errno != ENOTTY)
RETURN_FAIL("ioctl() failed");
#endif
#endif
ret = get_config(port, &data, &config);
if (ret < 0) {
sp_close(port);
RETURN_CODEVAL(ret);
}
/*
* Assume a default baudrate if the OS does not provide one.
* Cannot assign -1 here since Windows holds the baudrate in
* the DCB and does not configure the rate individually.
*/
if (config.baudrate == 0) {
config.baudrate = 9600;
}
/* Set sane port settings. */
#ifdef _WIN32
data.dcb.fBinary = TRUE;
data.dcb.fDsrSensitivity = FALSE;
data.dcb.fErrorChar = FALSE;
data.dcb.fNull = FALSE;
data.dcb.fAbortOnError = FALSE;
#else
/* Turn off all fancy termios tricks, give us a raw channel. */
data.term.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IMAXBEL);
#ifdef IUCLC
data.term.c_iflag &= ~IUCLC;
#endif
data.term.c_oflag &= ~(OPOST | ONLCR | OCRNL | ONOCR | ONLRET);
#ifdef OLCUC
data.term.c_oflag &= ~OLCUC;
#endif
#ifdef NLDLY
data.term.c_oflag &= ~NLDLY;
#endif
#ifdef CRDLY
data.term.c_oflag &= ~CRDLY;
#endif
#ifdef TABDLY
data.term.c_oflag &= ~TABDLY;
#endif
#ifdef BSDLY
data.term.c_oflag &= ~BSDLY;
#endif
#ifdef VTDLY
data.term.c_oflag &= ~VTDLY;
#endif
#ifdef FFDLY
data.term.c_oflag &= ~FFDLY;
#endif
#ifdef OFILL
data.term.c_oflag &= ~OFILL;
#endif
data.term.c_lflag &= ~(ISIG | ICANON | ECHO | IEXTEN);
data.term.c_cc[VMIN] = 0;
data.term.c_cc[VTIME] = 0;
/* Ignore modem status lines; enable receiver; leave control lines alone on close. */
data.term.c_cflag |= (CLOCAL | CREAD);
data.term.c_cflag &= ~(HUPCL);
#endif
#ifdef _WIN32
if (ClearCommError(port->hdl, &errors, &status) == 0)
RETURN_FAIL("ClearCommError() failed");
#endif
ret = set_config(port, &data, &config);
if (ret < 0) {
sp_close(port);
RETURN_CODEVAL(ret);
}
RETURN_OK();
}
SP_API enum sp_return sp_close(struct sp_port *port)
{
TRACE("%p", port);
CHECK_OPEN_PORT();
DEBUG_FMT("Closing port %s", port->name);
#ifdef _WIN32
/* Returns non-zero upon success, 0 upon failure. */
if (CloseHandle(port->hdl) == 0)
RETURN_FAIL("Port CloseHandle() failed");
port->hdl = INVALID_HANDLE_VALUE;
/* Close event handles for overlapped structures. */
#define CLOSE_OVERLAPPED(ovl) do { \
if (port->ovl.hEvent != INVALID_HANDLE_VALUE && \
CloseHandle(port->ovl.hEvent) == 0) \
RETURN_FAIL(# ovl "event CloseHandle() failed"); \
} while (0)
CLOSE_OVERLAPPED(read_ovl);
CLOSE_OVERLAPPED(write_ovl);
CLOSE_OVERLAPPED(wait_ovl);
if (port->write_buf) {
free(port->write_buf);
port->write_buf = NULL;
}
#else
/* Returns 0 upon success, -1 upon failure. */
if (close(port->fd) == -1)
RETURN_FAIL("close() failed");
port->fd = -1;
#endif
RETURN_OK();
}
SP_API enum sp_return sp_flush(struct sp_port *port, enum sp_buffer buffers)
{
TRACE("%p, 0x%x", port, buffers);
CHECK_OPEN_PORT();
if (buffers > SP_BUF_BOTH)
RETURN_ERROR(SP_ERR_ARG, "Invalid buffer selection");
const char *buffer_names[] = {"no", "input", "output", "both"};
DEBUG_FMT("Flushing %s buffers on port %s",
buffer_names[buffers], port->name);
#ifdef _WIN32
DWORD flags = 0;
if (buffers & SP_BUF_INPUT)
flags |= PURGE_RXCLEAR;
if (buffers & SP_BUF_OUTPUT)
flags |= PURGE_TXCLEAR;
/* Returns non-zero upon success, 0 upon failure. */
if (PurgeComm(port->hdl, flags) == 0)
RETURN_FAIL("PurgeComm() failed");
if (buffers & SP_BUF_INPUT)
TRY(restart_wait(port));
#else
int flags = 0;
if (buffers == SP_BUF_BOTH)
flags = TCIOFLUSH;
else if (buffers == SP_BUF_INPUT)
flags = TCIFLUSH;
else if (buffers == SP_BUF_OUTPUT)
flags = TCOFLUSH;
/* Returns 0 upon success, -1 upon failure. */
if (tcflush(port->fd, flags) < 0)
RETURN_FAIL("tcflush() failed");
#endif
RETURN_OK();
}
SP_API enum sp_return sp_drain(struct sp_port *port)
{
TRACE("%p", port);
CHECK_OPEN_PORT();
DEBUG_FMT("Draining port %s", port->name);
#ifdef _WIN32
/* Returns non-zero upon success, 0 upon failure. */
if (FlushFileBuffers(port->hdl) == 0)
RETURN_FAIL("FlushFileBuffers() failed");
RETURN_OK();
#else
int result;
while (1) {
#if defined(__ANDROID__) && (__ANDROID_API__ < 21)
/* Android only has tcdrain from platform 21 onwards.
* On previous API versions, use the ioctl directly. */
int arg = 1;
result = ioctl(port->fd, TCSBRK, &arg);
#else
result = tcdrain(port->fd);
#endif
if (result < 0) {
if (errno == EINTR) {
DEBUG("tcdrain() was interrupted");
continue;
} else {
RETURN_FAIL("tcdrain() failed");
}
} else {
RETURN_OK();
}
}
#endif
}
#ifdef _WIN32
static enum sp_return await_write_completion(struct sp_port *port)
{
TRACE("%p", port);
DWORD bytes_written;
BOOL result;
/* Wait for previous non-blocking write to complete, if any. */
if (port->writing) {
DEBUG("Waiting for previous write to complete");
result = GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE);
port->writing = 0;
if (!result)
RETURN_FAIL("Previous write failed to complete");
DEBUG("Previous write completed");
}
RETURN_OK();
}
#endif
SP_API enum sp_return sp_blocking_write(struct sp_port *port, const void *buf,
size_t count, unsigned int timeout_ms)
{
TRACE("%p, %p, %d, %d", port, buf, count, timeout_ms);
CHECK_OPEN_PORT();
if (!buf)
RETURN_ERROR(SP_ERR_ARG, "Null buffer");
if (timeout_ms)
DEBUG_FMT("Writing %d bytes to port %s, timeout %d ms",
count, port->name, timeout_ms);
else
DEBUG_FMT("Writing %d bytes to port %s, no timeout",
count, port->name);
if (count == 0)
RETURN_INT(0);
#ifdef _WIN32
DWORD remaining_ms, write_size, bytes_written;
size_t remaining_bytes, total_bytes_written = 0;
const uint8_t *write_ptr = (uint8_t *) buf;
bool result;
struct timeout timeout;
timeout_start(&timeout, timeout_ms);
TRY(await_write_completion(port));
while (total_bytes_written < count) {
if (timeout_check(&timeout))
break;
remaining_ms = timeout_remaining_ms(&timeout);
if (port->timeouts.WriteTotalTimeoutConstant != remaining_ms) {
port->timeouts.WriteTotalTimeoutConstant = remaining_ms;
if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
RETURN_FAIL("SetCommTimeouts() failed");
}
/* Reduce write size if it exceeds the WriteFile limit. */
remaining_bytes = count - total_bytes_written;
if (remaining_bytes > WRITEFILE_MAX_SIZE)
write_size = WRITEFILE_MAX_SIZE;
else
write_size = (DWORD) remaining_bytes;
/* Start write. */
result = WriteFile(port->hdl, write_ptr, write_size, NULL, &port->write_ovl);
timeout_update(&timeout);
if (result) {
DEBUG("Write completed immediately");
bytes_written = write_size;
} else if (GetLastError() == ERROR_IO_PENDING) {
DEBUG("Waiting for write to complete");
if (GetOverlappedResult(port->hdl, &port->write_ovl, &bytes_written, TRUE) == 0) {
if (GetLastError() == ERROR_SEM_TIMEOUT) {
DEBUG("Write timed out");
break;
} else {
RETURN_FAIL("GetOverlappedResult() failed");
}
}
DEBUG_FMT("Write completed, %d/%d bytes written", bytes_written, write_size);
} else {
RETURN_FAIL("WriteFile() failed");
}
write_ptr += bytes_written;
total_bytes_written += bytes_written;
}
RETURN_INT((int) total_bytes_written);
#else
size_t bytes_written = 0;
unsigned char *ptr = (unsigned char *) buf;
struct timeout timeout;
fd_set fds;
ssize_t result;
timeout_start(&timeout, timeout_ms);
FD_ZERO(&fds);
FD_SET(port->fd, &fds);
/* Loop until we have written the requested number of bytes. */
while (bytes_written < count) {
if (timeout_check(&timeout))
break;
result = select(port->fd + 1, NULL, &fds, NULL, timeout_timeval(&timeout));
timeout_update(&timeout);
if (result < 0) {
if (errno == EINTR) {
DEBUG("select() call was interrupted, repeating");
continue;
} else {
RETURN_FAIL("select() failed");
}
} else if (result == 0) {
/* Timeout has expired. */
break;
}
/* Do write. */
result = write(port->fd, ptr, count - bytes_written);
if (result < 0) {
if (errno == EAGAIN)
/* This shouldn't happen because we did a select() first, but handle anyway. */
continue;
else
/* This is an actual failure. */
RETURN_FAIL("write() failed");
}
bytes_written += result;
ptr += result;
}
if (bytes_written < count)
DEBUG("Write timed out");
RETURN_INT(bytes_written);
#endif
}
SP_API enum sp_return sp_nonblocking_write(struct sp_port *port,
const void *buf, size_t count)
{
TRACE("%p, %p, %d", port, buf, count);
CHECK_OPEN_PORT();
if (!buf)
RETURN_ERROR(SP_ERR_ARG, "Null buffer");
DEBUG_FMT("Writing up to %d bytes to port %s", count, port->name);
if (count == 0)
RETURN_INT(0);
#ifdef _WIN32
size_t buf_bytes;
/* Check whether previous write is complete. */
if (port->writing) {
if (HasOverlappedIoCompleted(&port->write_ovl)) {
DEBUG("Previous write completed");
port->writing = 0;
} else {
DEBUG("Previous write not complete");
/* Can't take a new write until the previous one finishes. */
RETURN_INT(0);
}
}
/* Set timeout. */
if (port->timeouts.WriteTotalTimeoutConstant != 0) {
port->timeouts.WriteTotalTimeoutConstant = 0;
if (SetCommTimeouts(port->hdl, &port->timeouts) == 0)
RETURN_FAIL("SetCommTimeouts() failed");
}
/* Reduce count if it exceeds the WriteFile limit. */
if (count > WRITEFILE_MAX_SIZE)
count = WRITEFILE_MAX_SIZE;
/* Copy data to our write buffer. */
buf_bytes = min(port->write_buf_size, count);
memcpy(port->write_buf, buf, buf_bytes);
/* Start asynchronous write. */
if (WriteFile(port->hdl, port->write_buf, (DWORD) buf_bytes, NULL, &port->write_ovl) == 0) {
if (GetLastError() == ERROR_IO_PENDING) {
if ((port->writing = !HasOverlappedIoCompleted(&port->write_ovl)))
DEBUG("Asynchronous write completed immediately");
else
DEBUG("Asynchronous write running");
} else {
/* Actual failure of some kind. */
RETURN_FAIL("WriteFile() failed");
}
}
DEBUG("All bytes written immediately");