summaryrefslogtreecommitdiff
path: root/mbglib/common/mbgserio.c
blob: d42ea5b35c92ba9a8d3ccb6b80b80dee48b60f0e (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616

/**************************************************************************
 *
 *  $Id: mbgserio.c 1.6.1.32 2017/04/10 13:39:44 martin TEST $
 *
 *  Copyright (c) Meinberg Funkuhren, Bad Pyrmont, Germany
 *
 *  Description:
 *    Meinberg serial I/O functions.
 *
 * -----------------------------------------------------------------------
 *  $Log: mbgserio.c $
 *  Revision 1.6.1.32  2017/04/10 13:39:44  martin
 *  Fixed some compiler warnings.
 *  Revision 1.6.1.31  2016/11/16 13:07:32Z  thomas-b
 *  Fixed several compiler errors under Windows
 *  Revision 1.6.1.30  2016/11/15 15:45:59  martin
 *  Allocate a device control structure when opening a port,
 *  and free the structure when the port is closed.
 *  Cleanup.
 *  Revision 1.6.1.29  2016/11/08 17:22:39  martin
 *  Doxygen fixes.
 *  Revision 1.6.1.28  2016/08/22 13:39:55  gregoire.diehl
 *  Revision 1.6.1.27  2016/02/03 09:48:26Z  martin
 *  Fixed Windows build.
 *  Revision 1.6.1.26  2015/12/10 16:30:17Z  martin
 *  *** empty log message ***
 *  Revision 1.6.1.25  2015/12/10 10:38:39  martin
 *  *** empty log message ***
 *  Revision 1.6.1.24  2015/12/09 17:35:03  martin
 *  *** empty log message ***
 *  Revision 1.6.1.23  2015/11/27 09:57:00  martin
 *  More checking of function return codes.
 *  Revision 1.6.1.22  2015/10/30 16:02:18  martin
 *  Revision 1.6.1.21  2015/10/29 14:01:43Z  martin
 *  *** empty log message ***
 *  Revision 1.6.1.20  2015/10/05 15:07:23  marvin
 *  Unicode support.
 *  Revision 1.6.1.19  2015/09/08 09:48:28Z  martin
 *  Revision 1.6.1.18  2015/08/27 16:20:19Z  martin
 *  Use safe string functions from str_util.c.
 *  Added doxygen comments.
 *  Revision 1.6.1.17  2015/07/22 16:02:52  martin
 *  Cleanup.
 *  Removed trailing whitespace.
 *  Revision 1.6.1.16  2014/05/27 11:26:24  martin
 *  Revision 1.6.1.15  2014/05/09 11:40:41  marvin
 *  Fixed port_str_list if current port already opened.
 *  Revision 1.6.1.14  2014/03/27 11:48:47Z  martin
 *  Revision 1.6.1.13  2014/03/18 10:37:52  martin
 *  Revision 1.6.1.12  2014/03/14 15:41:58Z  martin
 *  Revision 1.6.1.11  2014/03/13 14:31:44Z  martin
 *  Fixed compiler warnings related to select() call.
 *  Revision 1.6.1.10  2014/03/11 14:08:57Z  martin
 *  Revision 1.6.1.9  2014/03/07 13:20:55Z  martin
 *  Tmp. saved changes.
 *  Revision 1.6.1.8  2014/03/06 15:25:19  martin
 *  Revision 1.6.1.7  2014/03/04 12:08:12  martin
 *  Revision 1.6.1.6  2014/03/04 11:56:33Z  martin
 *  Revision 1.6.1.5  2014/01/31 08:49:00Z  marvin
 *  Replaced MBG_ERR_CONNECT_DEF by MBG_ERR_OPEN.
 *  Revision 1.6.1.4  2014/01/08 17:19:41Z  martin
 *  MBG_TGT_POSIX
 *  New libusb
 *  Revision 1.6.1.3  2014/01/07 17:00:18  martin
 *  Use common Meinberg error codes.
 *  Revision 1.6.1.2  2013/12/16 10:11:34  marvin
 *  Changed mbgerror return code.
 *  Revision 1.6.1.1  2013/12/13 13:08:19Z  marvin
 *  Changed error codes. Get error codes from mbgerror.h
 *  Revision 1.6  2013/04/18 13:50:58Z  udo
 *  use O_CLOEXEC on open serial port if defined
 *  Revision 1.5  2013/02/01 16:06:33  martin
 *  Always use mbgserio_read/write rather than the macros.
 *  Got rid of _mbg_open/close/read/write() macros.
 *  Check return code of tcgetattr() when opening port under Linux.
 *  Set up DCB under Windows when opening the port,
 *  not when setting parameters.
 *  Fixed setting up COM port list under Windows.
 *  Flush output on close.
 *  Debug code to test flush under Windows (doesn't seem
 *  to work properly).
 *  New code trying different ways to detect existing ports
 *  reliably under Linux.
 *  Syntax workaround which is required until this module becomes a DLL.
 *  Revision 1.4  2011/07/29 10:12:15  martin
 *  Allow baud rates 115200 and 230400 under Linux, if supported by the OS version.
 *  Revision 1.3  2009/09/01 10:49:30  martin
 *  Cleanup for CVI.
 *  Use new portable timeout functions from mbg_tmo.h.
 *  Timeouts are now specified in milliseconds.
 *  Set DOS/v24tools low level receive timeout to minimum on open.
 *  Let functions return predefined codes.
 *  Revision 1.2  2008/09/04 15:34:18Z  martin
 *  Moved support for different target environments from other files here.
 *  Added mbgserio_set_parms() and don't set parms when opening a port.
 *  Fixed bugs in timeout calculations in mbgserio_read_wait().
 *  Preliminary support for port device lists.
 *  Revision 1.1  2007/11/12 16:48:02  martin
 *  Initial revision.
 *
 **************************************************************************/

#define _MBGSERIO
 #include <mbgserio.h>
#undef _MBGSERIO

#include <mbgerror.h>
#include <str_util.h>

#include <stdio.h>
#include <ctype.h>
#include <time.h>

#if defined( MBG_TGT_POSIX )
  #include <fcntl.h>
  #include <dirent.h>
  #include <errno.h>
#endif



#if defined( MBG_TGT_POSIX )
  static const char dev_dir[] = "/dev";
#endif



#if defined( _USE_V24TOOLS )

/*------------------------------------------------------------------------
 * The definitions in this block and all v24...() functions are part of a
 * third-party library called V.24 Tools Plus by Langner Expertensysteme.
 *
 * This library may no be distributed freely, so the v24..() functions
 * must be replaced by user-written functions or some library available
 * to the user of this demo.
 *-----------------------------------------------------------------------*/

#ifdef __cplusplus
extern "C" {
#endif

int v24open( char *portname, int mode );
/* Open a port with specified name (e.g. "COM1"). The functions return a
 * handle to be used with the other functions. If the handle is < 0, the
 * port could not be opened.
 */

#define O_DIRECT     0x0100  /* open port with direct access to the hardware */
#define O_HIGHPRIO   0x2000  /* open port with high priority (fastopen) */

#define OPEN_MODE    ( O_DIRECT | O_HIGHPRIO )


int v24setparams( int port, long speed, int dbits, int parity, int stopbits );
/* Set the port's transmission speed, number of data bits, parity and
 * number of stop bits. Returns 0 on success.
 */

int v24qempty( int port, int which );
/* Returns 1 if the receive buffer is empty, 0 if it is not, or an other
 * value on error.
 */

int v24getch( int port );
/* Return a character from the receive buffer.
 */

int v24putc( int port, char c );
/* Write a character to the port.
 */

int v24close( int port );
/* Close the port
 */

#ifdef __cplusplus
}
#endif

#endif  // defined( _USE_V24TOOLS )

/*------------------------------------------------------------------------*/



static /*HDR*/
/**
 * @brief Deallocate a serial device control structure
 *
 * Free the memory allocated for the device control structure
 * and set the pointer to NULL.
 *
 * @param[in,out] pp_mdev  Address of a pointer to a device control structure
 *
 * @see ::alloc_mbgserio_dev
 */
void dealloc_mbgserio_dev( MBGSERIO_DEV **pp_mdev )
{
  MBGSERIO_DEV *p_mdev = *pp_mdev;

  if ( p_mdev )
  {
    free( p_mdev );
    *pp_mdev = NULL;
  }

}  // dealloc_mbgserio_dev



static /*HDR*/
/**
 * @brief Allocate a serial device control structure
 *
 * @param[in,out] pp_mdev  Address of a pointer to a device control structure
 *
 * @return ::MBG_SUCCESS or one of the @ref MBG_ERROR_CODES
 *
 * @see ::dealloc_mbgserio_dev
 */
int alloc_mbgserio_dev( MBGSERIO_DEV **pp_mdev )
{
  int rc;
  MBGSERIO_DEV *p_mdev = (MBGSERIO_DEV *) malloc( sizeof( *p_mdev ) );

  if ( p_mdev == NULL )
  {
    rc = mbg_get_last_error( "malloc failed in alloc_mbgserio_dev" );
    goto out;
  }

  memset( p_mdev, 0, sizeof( *p_mdev ) );
  p_mdev->port_handle = MBG_INVALID_PORT_HANDLE;
  rc = MBG_SUCCESS;

out:
  *pp_mdev = p_mdev;
  return rc;

}  // alloc_mbgserio_dev



#if defined( MBG_TGT_WIN32 )

static /*HDR*/
/**
 * @brief Win32-specific function which opens a serial port
 *
 * @param[in]  dev_name  Basic device name, e.g. "COM1"
 * @param[out] ph        Pointer to a HANDLE which is set up on success
 *
 * @return ::MBG_SUCCESS on success, or one of the @ref MBG_ERROR_CODES
 */
int win32_open_serial_port( const char *dev_name, HANDLE *ph )
{
  // A prefix is required for the device name to be able
  // to open ports with large numbers, e.g. COM15.
  static const char prefix[] = "\\\\.\\";

  size_t len = strlen( prefix ) + strlen( dev_name ) + 1;
  char *tmp_name;
  size_t n = 0;
  int rc = MBG_ERR_UNSPEC;

  tmp_name = (char *) malloc( len );

  if ( tmp_name == NULL )  // unable to allocate memory
  {
    rc = MBG_ERR_NO_MEM;
    goto out;
  }

  n = sn_cpy_str_safe( tmp_name, len, prefix );
  n += sn_cpy_str_safe( &tmp_name[n], len - n, dev_name );

  *ph = CreateFileA( tmp_name, GENERIC_READ | GENERIC_WRITE,
        0,
        NULL,
        OPEN_EXISTING,
        FILE_ATTRIBUTE_NORMAL, //##++++++++++++++  | FILE_FLAG_WRITE_THROUGH,
        NULL );

  if ( *ph == INVALID_HANDLE_VALUE )
  {
    rc = mbg_win32_last_err_to_mbg( GetLastError(), "CreateFile failed in win32_open_serial_port" );
    goto out_free;
  }

  rc = MBG_SUCCESS;

out_free:
  free( tmp_name );

out:
  return rc;

}  // win32_open_serial_port

#endif  // defined( MBG_TGT_WIN32 )



/*HDR*/
/**
 * @brief Close a serial port specified by a ::MBGSERIO_DEV structure
 *
 * After the port has been closed the buffer which had been allocated
 * for the ::MBGSERIO_DEV structure is freed, and the pointer to that
 * buffer is set to NULL.
 *
 * @param[in,out]  pp_mdev  Address of a pointer to the control structure including the port handle
 *
 * @return One of the @ref MBG_RETURN_CODES
 */
_NO_MBG_API_ATTR int _MBG_API mbgserio_close( MBGSERIO_DEV **pp_mdev )
{
  if ( *pp_mdev)  // only if a MBGSERIO_DEV structure has been allocated
  {
    MBGSERIO_DEV *p_mdev = *pp_mdev;
    MBG_PORT_HANDLE *p_handle = &p_mdev->port_handle;

    if ( *p_handle != MBG_INVALID_PORT_HANDLE )
    {
      mbgserio_flush_tx( p_mdev );

      #if defined( MBG_TGT_CVI )

        CloseCom( *p_handle );

      #elif defined( MBG_TGT_WIN32 )

        // restore original settings that have been saved

        if ( p_mdev->org_dcb_has_been_read )
          SetCommState( *p_handle, &p_mdev->org_dcb );

        if ( p_mdev->org_commtimeouts_have_been_read )
          SetCommTimeouts( *p_handle, &p_mdev->org_commtimeouts );

        CloseHandle( *p_handle );

      #elif defined( MBG_TGT_POSIX )

        // restore original settings that have been saved

        if ( p_mdev->org_tio_has_been_read )
          tcsetattr( *p_handle, TCSANOW, &p_mdev->org_tio );

        close( *p_handle );

      #elif defined( MBG_TGT_DOS )
        #if defined( _USE_V24TOOLS )

          v24close( *p_handle );

        #else

          #error Target DOS requires v24tools for serial I/O.

        #endif

      #else

        #error This target OS is not supported.

      #endif
    }

    dealloc_mbgserio_dev( pp_mdev );
  }

  return MBG_SUCCESS;

}  // mbgserio_close



/*HDR*/
/**
 * @brief Open a serial port and set up a ::MBGSERIO_DEV structure
 *
 * @param[in,out]  pp_mdev   Address of a pointer to a ::MBGSERIO_DEV device control structure
 *                           allocated and set up by this call. Set to NULL on error.
 * @param[in]      dev_name  Device name of the port to be opened.
 *
 * @return One of the @ref MBG_RETURN_CODES
 */
_NO_MBG_API_ATTR int _MBG_API mbgserio_open( MBGSERIO_DEV **pp_mdev, const char *dev_name )
{
  MBGSERIO_DEV *p_mdev;
  MBG_PORT_HANDLE *p_handle;

  int rc = alloc_mbgserio_dev( pp_mdev );

  if ( mbg_rc_is_error( rc ) )
    return rc;


  p_mdev = *pp_mdev;
  p_handle = &p_mdev->port_handle;

  #if defined( MBG_TGT_CVI )
  {
    int data_bits = 8;  //##+++++++++++++++
    int parity_code = 0;
    int baud_rate = 19200;
    int stop_bits = 1;
    int i;
    int len;
    int rc;

    // Under CVI the port handle passed to OpenComConfig and used furtheron
    // corresponds to the COM port number, e.g. 1 for COM1, so we extract
    // the number from the device name passed as parameter.
    len = strlen( dev_name );

    for ( i = 0; i < len; i++ )
    {
      char c = dev_name[i];

      if ( c >= '0' && c <= '9' )
        break;
    }

    if ( i == len )
    {
      rc = MBG_ERR_INV_PARM;   // no numeric substring found
      goto out;
    }

    *p_handle = atoi( &dev_name[i] );

    rc = OpenComConfig( *p_handle, NULL, baud_rate, parity_code, data_bits, stop_bits, 8192, 1024 );   //##++

    if ( rc < 0 )
    {
      rc = mbg_get_last_error( "OpenComConfig failed in mbgserio_open" );
      *p_handle = MBG_INVALID_PORT_HANDLE;
      goto out;
    }

    rc = SetComTime( *p_handle, 1.0 );   //##+++++++ WTF?

    if ( rc < 0 )
    {
      rc = mbg_get_last_error( "SetComTime failed in mbgserio_open" );
      goto out;
    }

    rc = SetXMode( *p_handle, 0 );

    if ( rc < 0 )
    {
      rc = mbg_get_last_error( "SetXMode failed in mbgserio_open" );
      goto out;
    }
  }
  #elif defined( MBG_TGT_WIN32 )
  {
    COMMTIMEOUTS commtimeouts;
    DCB dcb;

    rc = win32_open_serial_port( dev_name, p_handle );

    // rc is now one of the @ref MBG_RETURN_CODES, and in case of an error
    // the handle has already been set to ::MBG_INVALID_PORT_HANDLE.
    if ( mbg_rc_is_error( rc ) )
      goto out;

    // save settings found at startup
    p_mdev->org_dcb.DCBlength = sizeof( p_mdev->org_dcb );

    if ( !GetCommState( *p_handle, &p_mdev->org_dcb ) )
    {
      rc = mbg_get_last_error( "GetCommState failed in mbgserio_open" );
      goto out;
    }

    p_mdev->org_dcb_has_been_read = 1;

    if ( !GetCommTimeouts( *p_handle, &p_mdev->org_commtimeouts ) )
    {
      rc = mbg_get_last_error( "GetCommTimeouts failed in mbgserio_open" );
      goto out;
    }

    p_mdev->org_commtimeouts_have_been_read = 1;

    if ( !GetCommProperties( *p_handle, &p_mdev->comm_prop ) )
    {
      rc = mbg_get_last_error( "GetCommProperties failed in mbgserio_open" );
      goto out;
    }

    p_mdev->comm_prop_have_been_read = 1;

    #if 0 // fields provided by the Windows DCB structure
      DWORD DCBlength;      /* sizeof(DCB)                     */
      DWORD BaudRate;       /* Baudrate at which running       */
      DWORD fBinary: 1;     /* Binary Mode (skip EOF check)    */
      DWORD fParity: 1;     /* Enable parity checking          */
      DWORD fOutxCtsFlow:1; /* CTS handshaking on output       */
      DWORD fOutxDsrFlow:1; /* DSR handshaking on output       */
      DWORD fDtrControl:2;  /* DTR Flow control                */
      DWORD fDsrSensitivity:1; /* DSR Sensitivity              */
      DWORD fTXContinueOnXoff: 1; /* Continue TX when Xoff sent */
      DWORD fOutX: 1;       /* Enable output X-ON/X-OFF        */
      DWORD fInX: 1;        /* Enable input X-ON/X-OFF         */
      DWORD fErrorChar: 1;  /* Enable Err Replacement          */
      DWORD fNull: 1;       /* Enable Null stripping           */
      DWORD fRtsControl:2;  /* Rts Flow control                */
      DWORD fAbortOnError:1; /* Abort all reads and writes on Error */
      DWORD fDummy2:17;     /* Reserved                        */
      WORD wReserved;       /* Not currently used              */
      WORD XonLim;          /* Transmit X-ON threshold         */
      WORD XoffLim;         /* Transmit X-OFF threshold        */
      BYTE ByteSize;        /* Number of bits/byte, 4-8        */
      BYTE Parity;          /* 0-4=None,Odd,Even,Mark,Space    */
      BYTE StopBits;        /* 0,1,2 = 1, 1.5, 2               */
      char XonChar;         /* Tx and Rx X-ON character        */
      char XoffChar;        /* Tx and Rx X-OFF character       */
      char ErrorChar;       /* Error replacement char          */
      char EofChar;         /* End of Input character          */
      char EvtChar;         /* Received Event character        */
      WORD wReserved1;      /* Fill for now.                   */
    #endif

    // configure our settings
    dcb = p_mdev->org_dcb;         // current settings as default
    dcb.fOutxCtsFlow = FALSE;      // CTS output flow control
    dcb.fOutxDsrFlow = FALSE;      // DSR output flow control
    dcb.fDtrControl = DTR_CONTROL_ENABLE;  // enable DTR
    dcb.fDsrSensitivity = FALSE;   // don't require DSR input active
    //###++ TODO: more missing here
    dcb.fRtsControl = RTS_CONTROL_ENABLE;  // enable RTS for C28COM
    dcb.fOutX = FALSE;

    if ( !SetCommState( *p_handle, &dcb ) )
    {
      rc = mbg_get_last_error( "SetCommState failed in mbgserio_open" );
      goto out;
    }

    memset( &commtimeouts, 0, sizeof( commtimeouts ) );

    if ( !SetCommTimeouts( *p_handle, &commtimeouts ) )
    {
      rc = mbg_get_last_error( "SetCommTimeout failed in mbgserio_open" );
      goto out;
    }

    #if !defined( MBGSERIO_IN_BUFFER_SIZE )
      #define MBGSERIO_IN_BUFFER_SIZE 2048
    #endif

    #if !defined( MBGSERIO_OUT_BUFFER_SIZE )
      #define MBGSERIO_OUT_BUFFER_SIZE 2048
    #endif

    if ( !SetupComm( *p_handle, MBGSERIO_IN_BUFFER_SIZE, MBGSERIO_OUT_BUFFER_SIZE ) )
    {
      rc = mbg_get_last_error( "SetupComm failed in mbgserio_open" );
      goto out;
    }

    PurgeComm( *p_handle, PURGE_TXABORT | PURGE_TXCLEAR );
    PurgeComm( *p_handle, PURGE_RXABORT | PURGE_RXCLEAR );

    //###++ TODO: mbgextio_set_console_control_handler() ?
  }
  #elif defined( MBG_TGT_POSIX )
  {
    // Open as not controlling TTY to prevent from being
    // killed if CTRL-C is received.
    // O_NONBLOCK is the same as O_NDELAY.
    int flags = O_RDWR | O_NOCTTY | O_NONBLOCK;

    #if defined( O_CLOEXEC )
      flags |= O_CLOEXEC;
    #endif

    *p_handle = open( dev_name, flags );   // returns -1 on error

    if ( *p_handle < 0 )
    {
      rc = mbg_get_last_error( "open failed in mbgserio_open" );
      *p_handle = MBG_INVALID_PORT_HANDLE;
      goto out;
    }

    //###++ TODO: Under Unix a serial port can by default be opened
    // by several processes. However, we don't want that, so we
    // should care about this using a lock file for the device
    // and/or setting the TIOCEXCL flag (which unfortunately
    // is not an atomic operation with open()).

    /* save current device settings */
    if ( tcgetattr( *p_handle, &p_mdev->org_tio ) < 0 )
    {
      rc = mbg_get_last_error( "tcgetattr failed in mbgserio_open" );
      goto out;
    }

    p_mdev->org_tio_has_been_read = 1;

    //##++ TODO atexit( port_deinit ); ??
  }
  #elif defined( MBG_TGT_DOS )
    #if defined( _USE_V24TOOLS )
    {
      *p_handle = v24open( (char *) dev_name, OPEN_MODE );

      if ( *p_handle < 0 )
      {
        rc = MBG_ERR_UNSPEC;   //##++ translate rc ?
        *p_handle = MBG_INVALID_PORT_HANDLE;
        goto out;
      }

      v24settimeout( *p_handle, 1 );
    }
    #else

      #error Target DOS requires v24tools for serial I/O.
      rc = MBG_ERR_NOT_SUPP_ON_OS;
      goto out;

    #endif

  #else

    #error This target OS is not supported.
    rc = MBG_ERR_NOT_SUPP_ON_OS;
    goto out;

  #endif

  rc = MBG_SUCCESS;

out:
  if ( mbg_rc_is_error( rc ) )
    mbgserio_close( pp_mdev );

  return rc;

}  // mbgserio_open



#if 0 && defined( MBG_TGT_POSIX )

static /*HDR*/
int scandir_filter_serial_port( const struct dirent *pde )
{
  static const char dev_name_1[] = "ttyS";
  static const char dev_name_2[] = "ttyUSB";
  char tmp_str[100];
  MBGSERIO_DEV *p_mdev;
  int rc;

  int l;

  l = strlen( dev_name_1 );

  if ( strncmp( pde->d_name, dev_name_1, l ) == 0 )
    goto check;


  l = strlen( dev_name_2 );

  if ( strncmp( pde->d_name, dev_name_2, l ) == 0 )
    goto check;

  return 0;

check:
  // if the first character after the search string is not a digit
  // then the search result is not what we want
  if ( pde->d_name[l] < '0' || pde->d_name[l] > '9' )
    return 0;

  snprintf_safe( tmp_str, sizeof( tmp_str ), "%s/%s", dev_dir, pde->d_name );

  rc = mbgserio_open( &p_mdev, tmp_str );

  if ( rc < 0 )
  {
    #if defined( DEBUG )
      fprintf( stderr, "failed to open %s: %i\n", tmp_str, rc );
    #endif

    return 0;
  }

  #if defined( DEBUG )
    fprintf( stderr, "port %s opened successfully\n", tmp_str );
  #endif

  mbgserio_close( &p_mdev );

  return 1;

}  // scandir_filter_serial_port

#endif  // defined( MBG_TGT_POSIX )



/*HDR*/
_NO_MBG_API_ATTR int _MBG_API mbgserio_setup_port_str_list( MBG_STR_LIST **list, int max_devs )
{
  MBG_STR_LIST *list_head;
  int n = 0;
  int i = 0;

  (*list) = (MBG_STR_LIST *) malloc( sizeof( **list ) );
  memset( (*list), 0, sizeof( **list ) );

  list_head = (*list);


#if 0 && defined( MBG_TGT_POSIX )

  struct dirent **namelist;

  n = scandir( dev_dir, &namelist, scandir_filter_serial_port, versionsort );

  if ( n < 0 )
    perror( "scandir" );
  else
  {
    for ( i = 0; i < n; i++ )
    {
      printf( "%s/%s\n", dev_dir, namelist[i]->d_name );
      free( namelist[i] );
    }

    free( namelist );
  }

#elif 0 && defined( MBG_TGT_POSIX )

  DIR *pd = opendir( dev_dir );

  if ( pd )
  {
    struct dirent *pde;

    while ( ( pde = readdir( pd ) ) != NULL )
    {
      if ( strncmp( pde->d_name, "ttyS", 4 ) == 0 )
        goto found;

      if ( strncmp( pde->d_name, "ttyUSB", 6 ) == 0 )
        goto found;

      continue;

found:
      fprintf( stderr, "found /dev/%s\n", pde->d_name );
    }

    closedir( pd );
  }

#else

  for ( i = 0; i < max_devs; i++ )
  {
    char dev_name[100] = { 0 };
    int rc;

    #if defined( MBG_TGT_WIN32 )

      HANDLE h = INVALID_HANDLE_VALUE;

      snprintf_safe( dev_name, sizeof( dev_name ), "COM%i", i + 1 );
      rc = win32_open_serial_port( dev_name, &h );

      // If access is denied then the port exists but is in use
      if ( rc != MBG_SUCCESS && rc != MBG_ERR_ACCESS )
        continue;     // memory allocation error

      if ( h != INVALID_HANDLE_VALUE )
        CloseHandle( h );

    #elif defined( MBG_TGT_LINUX )

      MBGSERIO_DEV *p_mdev;
      snprintf_safe( dev_name, sizeof( dev_name ), "/dev/ttyS%i", i );
      rc = mbgserio_open( &p_mdev, dev_name );

      if ( rc < 0 )
      {
        snprintf_safe( dev_name, sizeof( dev_name ), "/dev/ttyUSB%i", i );

        rc = mbgserio_open( &p_mdev, dev_name );

        if ( rc < 0 )
          continue;
      }

      mbgserio_close( &p_mdev );

    #endif


    // add the device name to the list

    (*list)->s = (char *) malloc( strlen( dev_name ) + 1 );
    strcpy( (*list)->s, dev_name );

    (*list)->next = (MBG_STR_LIST *) malloc( sizeof( **list ) );
    (*list) = (*list)->next;

    memset( (*list), 0, sizeof( **list ) );
    n++;

//    if ( ++i >= N_SUPP_DEV_EXT )
//      break;
  }

  if ( n == 0 )
  {
    free( *list );
    list_head = NULL;
  }
#endif

  *list = list_head;

  return n;

}  // mbgserio_setup_port_str_list



/*HDR*/
_NO_MBG_API_ATTR void _MBG_API mbgserio_free_str_list( MBG_STR_LIST *list )
{
  int i = 0;

  while ( i < 1000 )  //##++
  {
    if ( list )
    {
      if ( list->s )
      {
        free( list->s );
        list->s = NULL;
      }

      if ( list->next )
      {
        MBG_STR_LIST *next = list->next;
        free( list );
        list = next;
      }
      else
      {
        if ( list )
        {
          free( list );
          list = NULL;
        }
        break;
      }
    }
    else
      break;

    i++;
  }

}  // mbgserio_free_str_list



/*HDR*/
/**
 * @brief
 *
 * @return One of the @ref MBG_RETURN_CODES
 */
_NO_MBG_API_ATTR int _MBG_API mbgserio_set_parms( MBGSERIO_DEV *mdev,
                                                  uint32_t baud_rate, const char *framing )
{
  MBG_PORT_HANDLE port_handle = mdev->port_handle;
  const char *cp;
  int rc = MBG_ERR_UNSPEC;

  #if defined( MBG_TGT_CVI )
  {
    int data_bits = 8;
    int parity_code = 0;
    int stop_bits = 1;

    // setup framing.
    for ( cp = framing; *cp; cp++ )
    {
      char c = toupper( *cp );

      switch ( c )
      {
        case '7':
        case '8':
          data_bits = c - '0';
          break;

        case 'N':
          parity_code = 0;
          break;

        case 'E':
          parity_code = 2;
          break;

        case 'O':
          parity_code = 1;
          break;

        case '1':
        case '2':
          stop_bits = c - '0';
          break;

        default:
          return MBG_ERR_INV_PARM;  // invalid framing string
      }
    }

    rc = OpenComConfig( port_handle, NULL, baud_rate, parity_code,
                        data_bits, stop_bits, 8192, 1024 );
    if ( rc < 0 )
      return mbg_cvi_rs232_error_to_mbg( rc, "OpenComConfig failed in mbgserio_set_parms" );

    rc = SetComTime( port_handle, 1.0 );

    if ( rc < 0 )
      return mbg_cvi_rs232_error_to_mbg( rc, "SetComTime failed in mbgserio_set_parms" );

    rc = SetXMode( port_handle, 0 );

    if ( rc < 0 )
      return mbg_cvi_rs232_error_to_mbg( rc, "SetXMode failed in mbgserio_set_parms" );

  }
  #elif defined( MBG_TGT_WIN32 )
  {
    DCB dcb;

    // get current settings
    dcb.DCBlength = sizeof( DCB );

    if ( GetCommState( port_handle, &dcb ) == FALSE )
      return mbg_get_last_error( "GetCommState failed in mbgserio_set_parms" );

    // update changed settings
    dcb.BaudRate = baud_rate;

    // setup framing.
    for ( cp = framing; *cp; cp++ )
    {
      char c = toupper( *cp );

      switch ( c )
      {
        case '7':
        case '8':
          dcb.ByteSize = c - '0';
          break;

        case 'N':
          dcb.Parity = NOPARITY;
          break;

        case 'E':
          dcb.Parity = EVENPARITY;
          break;

        case 'O':
          dcb.Parity = ODDPARITY;
          break;

        case '1':
          dcb.StopBits = ONESTOPBIT;
          break;

        case '2':
          dcb.StopBits = TWOSTOPBITS;
          break;

        default:
          return MBG_ERR_INV_PARM;  // invalid framing string
      }
    }

    if ( SetCommState( port_handle, &dcb ) == FALSE )
      return mbg_get_last_error( "SetCommState failed in mbgserio_set_parms" );
  }
  #elif defined( MBG_TGT_POSIX )
  {
    tcflag_t c_cflag = 0;
    struct termios tio;

    rc = tcgetattr( port_handle, &tio );

    if ( rc < 0 )
      return mbg_get_last_error( "tcgetattr failed in mbgserio_set_parms" );

    // setup transmission speed
    switch ( baud_rate )
    {
      case 300:    c_cflag = B300;    break;
      case 600:    c_cflag = B600;    break;
      case 1200:   c_cflag = B1200;   break;
      case 2400:   c_cflag = B2400;   break;
      case 4800:   c_cflag = B4800;   break;
      case 9600:   c_cflag = B9600;   break;
      case 19200:  c_cflag = B19200;  break;
      case 38400:  c_cflag = B38400;  break;
      case 57600:  c_cflag = B57600;  break;
      #if defined( B115200 )
        case 115200: c_cflag = B115200; break;
      #endif
      #if defined( B230400 )
        case 230400: c_cflag = B230400; break;
      #endif
      #if defined( B460800 )
        case 460800: c_cflag = B460800; break;
      #endif
      #if defined( B500000 )
        case 500000: c_cflag = B500000; break;
      #endif
      #if defined( B576000 )
        case 576000: c_cflag = B576000; break;
      #endif
      #if defined( B921600 )
        case 921600: c_cflag = B921600; break;
      #endif
      #if defined( B1000000 )
        case 1000000: c_cflag = B1000000; break;
      #endif
      #if defined( B1152000 )
        case 1152000: c_cflag = B1152000; break;
      #endif
      #if defined( B1500000 )
        case 1500000: c_cflag = B1500000; break;
      #endif
      #if defined( B2000000 )
        case 2000000: c_cflag = B2000000; break;
      #endif
      #if defined( B2500000 )
        case 2500000: c_cflag = B2500000; break;
      #endif
      #if defined( B3000000 )
        case 3000000: c_cflag = B3000000; break;
      #endif
      #if defined( B3500000 )
        case 3500000: c_cflag = B3500000; break;
      #endif
      #if defined( B4000000 )
        case 4000000: c_cflag = B4000000; break;
      #endif

      default:
        return MBG_ERR_INV_PARM;  // invalid
    }

    #if 0 //###++ This should be used preferably for portability reasons
       int cfsetispeed( struct termios *termios_p, speed_t speed );
       int cfsetospeed( struct termios *termios_p, speed_t speed );
    #endif

    // setup framing.
    for ( cp = framing; *cp; cp++ )
    {
      char c = toupper( *cp );

      switch ( c )
      {
        case '7':  c_cflag |= CS7;             break;
        case '8':  c_cflag |= CS8;             break;

        case 'N':                              break;
        case 'E':  c_cflag |= PARENB;          break;
        case 'O':  c_cflag |= PARENB | PARODD; break;

        case '1':                              break;
        case '2':  c_cflag |= CSTOPB;          break;

        default:
          return MBG_ERR_INV_PARM;  // invalid
      }
    }


    // Setup control flags. The following flags are defined:
    //   CBAUD   (not in POSIX) Baud speed mask (4+1 bits).
    //   CBAUDEX (not in POSIX) Extra baud speed mask (1 bit), included in CBAUD.
    //           (POSIX says that the baud speed is stored in the termios structure
    //           without specifying where precisely, and provides cfgetispeed() and
    //           cfsetispeed() for getting at it. Some systems use bits selected
    //           by CBAUD in c_cflag, other systems use separate fields,
    //           e.g. sg_ispeed and sg_ospeed.)
    //   CSIZE   Character size mask. Values are CS5, CS6, CS7, or CS8.
    //   CSTOPB  Set two stop bits, rather than one.
    //   CREAD   Enable receiver.
    //   PARENB  Enable parity generation on output and parity checking for input.
    //   PARODD  Parity for input and output is odd.
    //   HUPCL   Lower modem control lines after last process closes the device (hang up).
    //   CLOCAL  Ignore modem control lines.
    //   LOBLK   (not in POSIX) Block output from a noncurrent shell layer.
    //           (For use by shl)
    //   CIBAUD  (not in POSIX) Mask for input speeds. The values for the CIBAUD bits are
    //           the same as the values for the CBAUD bits, shifted left IBSHIFT bits.
    //   CRTSCTS (not in POSIX) Enable RTS/CTS (hardware) flow control.

    //   local connection, no modem control (CLOCAL)
    //   no flow control (no CRTSCTS)
    //   enable receiving
    tio.c_cflag = c_cflag | CLOCAL | CREAD;


    // Setup input flags. The following flags are defined:
    //   IGNBRK  Ignore BREAK condition on input
    //   BRKINT  If IGNBRK is set, a BREAK is ignored. If it is not set
    //           but BRKINT is set, then a BREAK causes the input and output
    //           queues to be flushed, and if the terminal is the controlling
    //           terminal of a foreground process group, it will cause a
    //           SIGINT to be sent to this foreground process  group. When
    //           neither IGNBRK nor BRKINT are set, a BREAK reads as a NUL
    //           character, except when PARMRK is set, in which case it reads
    //           as the sequence \377 \0 \0.
    //   IGNPAR  Ignore framing errors and parity errors.
    //   PARMRK  If IGNPAR is not set, prefix a character with a parity error
    //           framing error with \377 \0. If neither IGNPAR nor PARMRK or
    //           is set, read a character with a parity error or framing error as \0.
    //   INPCK   Enable input parity checking.
    //   ISTRIP  Strip off eighth bit.
    //   INLCR   Translate NL to CR on input.
    //   IGNCR   Ignore carriage return on input.
    //   ICRNL   Translate carriage return to newline on input (unless IGNCR is set).
    //   IUCLC   (not in POSIX) Map uppercase characters to lowercase on input.
    //   IXON    Enable XON/XOFF flow control on output.
    //   IXANY   (not in POSIX.1; XSI) Enable any character to restart output.
    //   IXOFF   Enable XON/XOFF flow control on input.
    //   IMAXBEL (not in POSIX) Ring bell when input queue is full. Linux does not
    //           implement this bit, and acts as if it is always set.
    tio.c_iflag = 0;

    #if 0  //###++
    if ( c_cflag & PARENB )
      tio.c_iflag |= IGNPAR;  //##++ this also ignores framing errors
    #endif


    // Setup output flags. The following flags are defined:
    //   OPOST   Enable implementation-defined output processing.
    // The remaining c_oflag flag constants are defined in POSIX 1003.1-2001,
    // unless marked otherwise.
    //   OLCUC   (not in POSIX) Map lowercase characters to uppercase on output.
    //   ONLCR   (XSI) Map NL to CR-NL on output.
    //   OCRNL   Map CR to NL on output.
    //   ONOCR   Don't output CR at column 0.
    //   ONLRET  Don't output CR.
    //   OFILL   Send fill characters for a delay, rather than using a timed delay.
    //   OFDEL   (not in POSIX) Fill character is ASCII DEL (0177). If unset,
    //           fill character is ASCII NUL.
    //   NLDLY   Newline delay mask. Values are NL0 and NL1.
    //   CRDLY   Carriage return delay mask. Values are CR0, CR1, CR2, or CR3.
    //   TABDLY  Horizontal tab delay mask. Values are TAB0, TAB1, TAB2, TAB3
    //           (or XTABS). A value of TAB3, that is, XTABS, expands tabs to
    //           spaces (with tab stops every eight columns).
    //   BSDLY   Backspace delay mask. Values are BS0 or BS1.
    //           (Has never been implemented.)
    //   VTDLY   Vertical tab delay mask. Values are VT0 or VT1.
    //   FFDLY   Form feed delay mask. Values are FF0 or FF1.
    tio.c_oflag = 0;


    // Setup local mode flags. The following flags are defined:
    //   ISIG    When any of the characters INTR, QUIT, SUSP, or DSUSP are
    //           received, generate the corresponding signal.
    //   ICANON  Enable canonical mode. This enables the special characters
    //           EOF, EOL, EOL2, ERASE, KILL, LNEXT, REPRINT, STATUS, and
    //           WERASE, and buffers by lines.
    //   XCASE   (not in POSIX; not supported under Linux) If ICANON is also
    //           set, terminal is uppercase only. Input is converted to
    //           lowercase, except for characters preceded by \. On output,
    //           uppercase characters are preceded by \ and lowercase
    //           characters are converted to uppercase.
    //   ECHO    Echo input characters.
    //   ECHOE   If ICANON is also set, the ERASE character erases the preceding
    //           input character, and WERASE erases the preceding word.
    //   ECHOK   If ICANON is also set, the KILL character erases the current line.
    //   ECHONL  If ICANON is also set, echo the NL character even if ECHO is not set.
    //   ECHOCTL (not  in  POSIX) If ECHO is also set, ASCII control signals
    //           other than TAB, NL, START, and STOP are echoed as ^X, where
    //           X is the character with ASCII code 0x40 greater than the control
    //           signal. For example, character 0x08 (BS) is echoed as ^H.
    //   ECHOPRT (not in POSIX) If ICANON and IECHO are also set, characters are
    //           printed as they are being erased.
    //   ECHOKE  (not in POSIX) If ICANON is also set, KILL is echoed by erasing
    //           each character on the line, as specified by ECHOE and ECHOPRT.
    //   DEFECHO (not in POSIX) Echo only when a process is reading.
    //   FLUSHO  (not in POSIX; not supported under Linux) Output is being flushed.
    //           This flag is toggled by typing the DISCARD character.
    //   NOFLSH  Disable flushing the input and output queues when generating the
    //           SIGINT, SIGQUIT and SIGSUSP signals.
    //   TOSTOP  Send the SIGTTOU signal to the process group of a background
    //           process which tries to write to its controlling terminal.
    //   PENDIN  (not in POSIX; not supported under Linux) All characters in the
    //           input queue are reprinted when the next character is read.
    //           (bash  handles typeahead this way.)
    //   IEXTEN  Enable implementation-defined input processing. This flag, as
    //           well as ICANON must be enabled for the special characters EOL2,
    //           LNEXT, REPRINT, WERASE to be interpreted, and for the IUCLC flag
    //           to be effective.
    tio.c_lflag = 0;


    //   VINTR   (003, ETX, Ctrl-C, or also 0177, DEL, rubout) Interrupt character.
    //           Send a SIGINT signal. Recognized when ISIG is set, and then not
    //           passed as input.
    //   VQUIT   (034, FS, Ctrl-\) Quit character. Send SIGQUIT signal. Recognized
    //           when ISIG is set, and then not passed as input.
    //   VERASE  (0177, DEL, rubout, or 010, BS, Ctrl-H, or also #) Erase character.
    //           This erases the previous not-yet-erased character, but does not erase
    //           past EOF or beginning-of-line. Recognized when ICANON is set,
    //           and then not passed as input.
    //   VKILL   (025, NAK, Ctrl-U, or Ctrl-X, or also @) Kill character. This erases
    //           the input since the last EOF or beginning-of-line. Recognized when
    //           ICANON is set, and then not passed as input.
    //   VEOF    (004, EOT, Ctrl-D) End-of-file character. More precisely: this
    //           character causes the pending tty buffer to be sent to the waiting
    //           user program without waiting for end-of-line. If it is the first
    //           character of the line, the read() in the user program returns 0,
    //           which signifies end-of-file. Recognized when ICANON is set, and
    //           then not passed as input.
    //   VMIN    Minimum number of characters for non-canonical read.
    //   VEOL    (0, NUL) Additional end-of-line character. Recognized when ICANON is set.
    //   VTIME   Timeout in deciseconds for non-canonical read.
    //   VEOL2   (not in POSIX; 0, NUL) Yet another end-of-line character.
    //           Recognized when ICANON is set.
    //   VSWTCH  (not in POSIX; not supported under Linux; 0, NUL) Switch character.
    //           (Used by shl only.)
    //   VSTART  (021, DC1, Ctrl-Q) Start character. Restarts output stopped by the Stop
    //           character. Recognized when IXON is set, and then not passed as input.
    //   VSTOP   (023, DC3, Ctrl-S) Stop character. Stop output until Start character
    //           typed. Recognized when IXON is set, and then not passed as input.
    //   VSUSP   (032, SUB, Ctrl-Z) Suspend character. Send SIGTSTP signal. Recognized
    //           when ISIG is set, and then not passed as input.
    //   VDSUSP  (not in POSIX; not supported under Linux; 031, EM, Ctrl-Y) Delayed
    //           suspend character: send SIGTSTP signal when the character is read by
    //           the user program. Recognized when IEXTEN and ISIG are set, and the
    //           system supports job control, and then not passed as input.
    //   VLNEXT  (not in POSIX; 026, SYN, Ctrl-V) Literal next. Quotes the next input
    //           character, depriving it of a possible special meaning.  Recognized
    //           when IEXTEN is set, and then not passed as input.
    //   VWERASE (not in POSIX; 027, ETB, Ctrl-W) Word erase. Recognized when ICANON
    //           and IEXTEN are set, and then not passed as input.
    //   VREPRINT (not in POSIX; 022, DC2, Ctrl-R) Reprint unread characters. Recognized
    //           when ICANON and IEXTEN are set, and then not passed as input.
    //   VDISCARD (not in POSIX; not supported under Linux; 017, SI, Ctrl-O) Toggle:
    //           start/stop discarding pending output. Recognized when IEXTEN is set,
    //           and then not passed as input.
    //   VSTATUS (not in POSIX; not supported under Linux; status request: 024, DC4, Ctrl-T).


    // Setting up c_cc[VMIN] and c_cc[VTIME]:
    // If MIN > 0 and TIME = 0, MIN sets the number of characters to receive before
    //            the read is satisfied. As TIME is zero, the timer is not used.
    // If MIN = 0 and TIME > 0, TIME serves as a timeout value. The read will be
    //            satisfied if a single character is read, or TIME is exceeded
    //            (t = TIME *0.1 s). If TIME is exceeded, no character will be
    //            returned.
    // If MIN > 0 and TIME > 0, TIME serves as an inter-character timer. The
    //            read will be satisfied if MIN characters are received, or the
    //            time between two characters exceeds TIME. The timer is restarted
    //            every time a character is received and only becomes active after
    //            the first character has been received.
    // If MIN = 0 and TIME = 0, read will be satisfied immediately. The number of
    //            characters currently available, or the number of characters
    //            requested will be returned. You could issue a
    //            fcntl(fd, F_SETFL, FNDELAY); before reading to get the same result.

    // setup control characters for non-blocking read
    tio.c_cc[VMIN] = 0;
    tio.c_cc[VTIME] = 0;

    // now clean the modem line and activate the settings for modem
    if ( tcflush( port_handle, TCIFLUSH ) < 0  )
      return mbg_get_last_error( "tcflush failed in mbgserio_set_parms" );

    if ( tcsetattr( port_handle, TCSANOW, &tio ) < 0 )
      return mbg_get_last_error( "tcsetattr failed in mbgserio_set_parms" );
  }
  #elif defined( MBG_TGT_DOS )
    #if defined( _USE_V24TOOLS )
    {
      int datab = 8;
      char parity = 'N';
      int stopb = 1;

      // setup framing.
      for ( cp = framing; *cp; cp++ )
      {
        char c = toupper( *cp );

        switch ( c )
        {
          case '7':
          case '8':
            datab = c - '0';
            break;

          case 'N':
          case 'E':
          case 'O':
            parity = c;
            break;

          case '1':
          case '2':
            stopb = c - '0';
            break;

          default:
            return MBG_ERR_INV_PARM;  // invalid framing string
        }
      }

      v24setparams( port_handle, baud_rate, datab, parity, stopb );  //### TODO check rc?
    }
    #else

      #error This has to be modified for DOS without v24tools.

    #endif

  #else

    #error This target OS is not supported.

  #endif

  rc = MBG_SUCCESS;

  return rc;

}  // mbgserio_set_parms



/*HDR*/
_NO_MBG_API_ATTR int _MBG_API mbgserio_read( MBGSERIO_DEV *mdev, void *buffer, unsigned int count )
{
  #if defined( MBG_TGT_CVI )

    return ComRd( mdev->port_handle, (char *) buffer, count );  //### TODO check return code

  #elif defined( MBG_TGT_WIN32 )

    BOOL fReadStat;
    COMSTAT ComStat;
    DWORD dwErrorFlags;
    DWORD dwLength;

    ClearCommError( mdev->port_handle, &dwErrorFlags, &ComStat );

    if ( dwErrorFlags )  // transmission error (parity, framing, etc.)
      return MBG_ERR_IO;  //##+++++++++++++++++++++++++


    dwLength = min( (DWORD) count, ComStat.cbInQue );

    if ( dwLength )
    {
      fReadStat = ReadFile( mdev->port_handle, buffer, dwLength, &dwLength, NULL );

      if ( !fReadStat )
        return MBG_ERR_IO;  //### TODO retrieve and return real error code
    }

    return dwLength;

  #elif defined( MBG_TGT_POSIX )

    int rc = read( mdev->port_handle, buffer, count );

    if ( rc < 0 )  // usually -1 in case of error
      rc = mbg_get_last_error( "read failed in mbgserio_read" );

    return rc;

  #elif defined( MBG_TGT_DOS ) && defined( _USE_V24TOOLS )

    int rc = v24read( mdev->port_handle, buffer, count );

    if ( rc < 0 )
      rc = MBG_ERR_UNSPEC;

    return rc;

  #else

    #error mbgserio_read() not implemented for this target

  #endif

} // mbgserio_read


/* //##+++++++++++++++++ need to check all targets
 * @return one of the MBG_ERROR_CODES on error, else number of bytes written
 */
/*HDR*/
_NO_MBG_API_ATTR int _MBG_API mbgserio_write( MBGSERIO_DEV *mdev, const void *buffer, unsigned int count )
{
  #if defined( MBG_TGT_CVI )

    return ComWrt( mdev->port_handle, (char *) buffer, count );  //### TODO check return code

  #elif defined( MBG_TGT_WIN32 )

    BOOL fWriteStat;
    COMSTAT ComStat;
    DWORD dwErrorFlags;
    DWORD dwThisBytesWritten;
    DWORD dwTotalBytesWritten = 0;
    MBG_PORT_HANDLE h = mdev->port_handle;

    while ( dwTotalBytesWritten < (DWORD) count )
    {
      dwThisBytesWritten = 0;

      fWriteStat = WriteFile( h, ( (char *) buffer ) + dwTotalBytesWritten,
                              count - dwTotalBytesWritten,
                              &dwThisBytesWritten, NULL );
      if ( !fWriteStat )
        return mbg_get_last_error( "write failed in mbgserio_write" );

      dwTotalBytesWritten += dwThisBytesWritten;

      ClearCommError( h, &dwErrorFlags, &ComStat );

      if ( dwErrorFlags )
      {
        // Possible errors:
        //
        // CE_RXOVER    0x0001  // Receive Queue overflow
        // CE_OVERRUN   0x0002  // Receive Overrun Error, next character(s) lost
        // CE_RXPARITY  0x0004  // Receive Parity Error
        // CE_FRAME     0x0008  // Receive Framing error
        // CE_BREAK     0x0010  // Break Detected
        // CE_TXFULL    0x0100  // TX Queue is full
        // CE_PTO       0x0200  // LPTx Timeout
        // CE_IOE       0x0400  // LPTx I/O Error
        // CE_DNS       0x0800  // LPTx Device not selected
        // CE_OOP       0x1000  // LPTx Out-Of-Paper
        // CE_MODE      0x8000  // Requested mode unsupported
        //
        // Except CE_TXFULL these are usually RX error flags,
        // so we just ignore them.
      }
    }

    return dwTotalBytesWritten;

  #elif defined( MBG_TGT_POSIX )

    int rc = write( mdev->port_handle, buffer, count );  // returns -1 on error, else number of byte written

    if  ( rc == -1 )
      rc = mbg_get_last_error( "write failed in mbgserio_write" );

    return rc;

  #elif defined( MBG_TGT_DOS ) && defined( _USE_V24TOOLS )

    return v24write( mdev->port_handle, buffer, count );  //### TODO check return code

  #else

    #error mbgserio_write() not implemented for this target

  #endif

}  // mbgserio_write



/*HDR*/
_NO_MBG_API_ATTR void _MBG_API mbgserio_flush_tx( MBGSERIO_DEV *mdev )
{
  #if defined( MBG_TGT_CVI )

    FlushOutQ( mdev->port_handle );

  #elif defined( MBG_TGT_WIN32 )

    #if defined( DEBUG )
      printf( "Flushing TX buffers ...\n" );
    #endif

    FlushFileBuffers( mdev->port_handle );

    #if ( 1 && defined( DEBUG ) ) //##++++++++++++++
    {
      COMSTAT ComStat;
      DWORD dwErrorFlags;

      for (;;)
      {
        ClearCommError( mdev->port_handle, &dwErrorFlags, &ComStat );

        printf( "ErrFlags: %04X, out queue: %u\n", dwErrorFlags, ComStat.cbOutQue );

        if ( ComStat.cbOutQue == 0 )
          break;

        Sleep( 1 );
      }
    }
    #endif

    //##++++ Sleep( 500 );

  #elif defined( MBG_TGT_POSIX )

    tcdrain( mdev->port_handle );

  #elif defined( MBG_TGT_DOS ) && defined( _USE_V24TOOLS )

    v24flush( mdev->port_handle, SND );

  #else

    #error mbgserio_flush_tx() not implemented for this target

  #endif

}  // mbgserio_flush_tx



/*HDR*/
_NO_MBG_API_ATTR int _MBG_API mbgserio_read_wait( MBGSERIO_DEV *mdev, void *buffer,
                                                  uint count )
{
  int rc;

  #if _USE_SELECT_FOR_SERIAL_IO

    struct timeval tv_char_timeout;
    fd_set fds;
    int max_fd;

    mbg_msec_to_timeval( mdev->poll_timeout, &tv_char_timeout );

    FD_ZERO( &fds );
    FD_SET( mdev->port_handle, &fds );

    #if defined( MBG_TGT_WIN32 )
      // Under Windows an fd is a handle which can't simply
      // be converted to an int, but the first argument of
      // select() is ignored under Windows anyway, so we just
      // set max_fd to 0.
      max_fd = 0;
    #else
      max_fd = mdev->port_handle;
    #endif

    rc = select( max_fd + 1, &fds, NULL, NULL, &tv_char_timeout );

    if ( rc < 0 )     // error
      return mbg_get_last_error( "select failed in mbgserio_read_wait" );

    if ( rc == 0 )    // timeout
      return MBG_ERR_TIMEOUT;

    // data is available
    rc = mbgserio_read( mdev, buffer, count );

  #else

    MBG_TMO_TIME tmo;

    mbg_tmo_set_timeout_ms( &tmo, mdev->poll_timeout );

    for (;;)  // wait to read one new char
    {
      rc = mbgserio_read( mdev, buffer, count );

      if ( rc != 0 )     // char(s) received, or error
        break;

      if ( mbg_tmo_curr_time_is_after( &tmo ) )
        return MBG_ERR_TIMEOUT;

      #if defined( MBG_TGT_POSIX )
        usleep( 10 * 1000 );
      #endif
    }
  #endif

  return rc;

}  // mbgserio_read_wait