-
Notifications
You must be signed in to change notification settings - Fork 93
/
sim_serial.c
1878 lines (1514 loc) · 72.5 KB
/
sim_serial.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
/* sim_serial.c: OS-dependent serial port routines
Copyright (c) 2008, J. David Bryan, Mark Pizzolato
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the author shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the author.
The author gratefully acknowledges the assistance of Holger Veit with the
UNIX-specific code and testing.
07-Oct-08 JDB [serial] Created file
22-Apr-12 MP Adapted from code originally written by J. David Bryan
This module provides OS-dependent routines to access serial ports on the host
machine. The terminal multiplexer library uses these routines to provide
serial connections to simulated terminal interfaces.
Currently, the module supports Windows and UNIX. Use on other systems
returns error codes indicating that the functions failed, inhibiting serial
port support in SIMH.
The following routines are provided:
sim_open_serial open a serial port
sim_config_serial change baud rate and character framing configuration
sim_control_serial manipulate and/or return the modem bits on a serial port
sim_read_serial read from a serial port
sim_write_serial write to a serial port
sim_close_serial close a serial port
sim_show_serial shows the available host serial ports
The calling sequences are as follows:
SERHANDLE sim_open_serial (char *name)
--------------------------------------
The serial port referenced by the OS-dependent "name" is opened. If the open
is successful, and "name" refers to a serial port on the host system, then a
handle to the port is returned. If not, then the value INVALID_HANDLE is
returned.
t_stat sim_config_serial (SERHANDLE port, const char *config)
-------------------------------------------------------------
The baud rate and framing parameters (character size, parity, and number of
stop bits) of the serial port associated with "port" are set. If any
"config" field value is unsupported by the host system, or if the combination
of values (e.g., baud rate and number of stop bits) is unsupported, SCPE_ARG
is returned. If the configuration is successful, SCPE_OK is returned.
sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits)
-------------------------------------------------------------------------------------------------
The DTR and RTS line of the serial port is set or cleared as indicated in
the respective bits_to_set or bits_to_clear parameters. If the
incoming_bits parameter is not NULL, then the modem status bits DCD, RNG,
DSR and CTS are returned.
If unreasonable or nonsense bits_to_set or bits_to_clear bits are
specified, then the return status is SCPE_ARG;
If an error occurs, SCPE_IOERR is returned.
int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
----------------------------------------------------------------------------
A non-blocking read is issued for the serial port indicated by "port" to get
at most "count" bytes into the string "buffer". If a serial line break was
detected during the read, the variable pointed to by "brk" is set to 1. If
the read is successful, the actual number of characters read is returned. If
no characters were available, then the value 0 is returned. If an error
occurs, then the value -1 is returned.
int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
------------------------------------------------------------------
A write is issued to the serial port indicated by "port" to put "count"
characters from "buffer". If the write is successful, the actual number of
characters written is returned. If an error occurs, then the value -1 is
returned.
void sim_close_serial (SERHANDLE port)
--------------------------------------
The serial port indicated by "port" is closed.
int sim_serial_devices (int max, SERIAL_LIST* list)
---------------------------------------------------
enumerates the available host serial ports
t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, const void* desc)
---------------------------------
displays the available host serial ports
*/
#include "sim_defs.h"
#include "sim_serial.h"
#include "sim_tmxr.h"
#include <ctype.h>
#define SER_DEV_NAME_MAX 256 /* maximum device name size */
#define SER_DEV_DESC_MAX 256 /* maximum device description size */
#define SER_DEV_CONFIG_MAX 64 /* maximum device config size */
#define SER_MAX_DEVICE 64 /* maximum serial devices */
typedef struct serial_list {
char name[SER_DEV_NAME_MAX];
char desc[SER_DEV_DESC_MAX];
} SERIAL_LIST;
typedef struct serial_config { /* serial port configuration */
uint32 baudrate; /* baud rate */
uint32 charsize; /* character size in bits */
char parity; /* parity (N/O/E/M/S) */
uint32 stopbits; /* 0/1/2 stop bits (0 implies 1.5) */
} SERCONFIG;
static int sim_serial_os_devices (int max, SERIAL_LIST* list);
static SERHANDLE sim_open_os_serial (char *name);
static void sim_close_os_serial (SERHANDLE port);
static t_stat sim_config_os_serial (SERHANDLE port, SERCONFIG config);
static struct open_serial_device {
SERHANDLE port;
TMLN *line;
char name[SER_DEV_NAME_MAX];
char config[SER_DEV_CONFIG_MAX];
} *serial_open_devices = NULL;
static int serial_open_device_count = 0;
static struct open_serial_device *_get_open_device (SERHANDLE port)
{
int i;
for (i=0; i<serial_open_device_count; ++i)
if (serial_open_devices[i].port == port)
return &serial_open_devices[i];
return NULL;
}
static struct open_serial_device *_get_open_device_byname (const char *name)
{
int i;
for (i=0; i<serial_open_device_count; ++i)
if (0 == strcmp(name, serial_open_devices[i].name))
return &serial_open_devices[i];
return NULL;
}
static struct open_serial_device *_serial_add_to_open_list (SERHANDLE port, TMLN *line, const char *name, const char *config)
{
serial_open_devices = (struct open_serial_device *)realloc(serial_open_devices, (++serial_open_device_count)*sizeof(*serial_open_devices));
memset(&serial_open_devices[serial_open_device_count-1], 0, sizeof(serial_open_devices[serial_open_device_count-1]));
serial_open_devices[serial_open_device_count-1].port = port;
serial_open_devices[serial_open_device_count-1].line = line;
strlcpy(serial_open_devices[serial_open_device_count-1].name, name, sizeof(serial_open_devices[serial_open_device_count-1].name));
if (config)
strlcpy(serial_open_devices[serial_open_device_count-1].config, config, sizeof(serial_open_devices[serial_open_device_count-1].config));
return &serial_open_devices[serial_open_device_count-1];
}
static void _serial_remove_from_open_list (SERHANDLE port)
{
int i, j;
for (i=0; i<serial_open_device_count; ++i)
if (serial_open_devices[i].port == port) {
for (j=i+1; j<serial_open_device_count; ++j)
serial_open_devices[j-1] = serial_open_devices[j];
--serial_open_device_count;
break;
}
}
/* Generic error message handler.
This routine should be called for unexpected errors. Some error returns may
be expected, e.g., a "file not found" error from an "open" routine. These
should return appropriate status codes to the caller, allowing SCP to print
an error message if desired, rather than printing this generic error message.
*/
static void sim_error_serial (const char *routine, int error)
{
sim_printf ("Serial: %s fails with error %d\n", routine, error);
return;
}
/* Used when sorting a list of serial port names */
static int _serial_name_compare (const void *pa, const void *pb)
{
const SERIAL_LIST *a = (const SERIAL_LIST *)pa;
const SERIAL_LIST *b = (const SERIAL_LIST *)pb;
return strcmp(a->name, b->name);
}
static int sim_serial_devices (int max, SERIAL_LIST *list)
{
int i, j, ports = sim_serial_os_devices(max, list);
/* Open ports may not show up in the list returned by sim_serial_os_devices
so we add the open ports to the list removing duplicates before sorting
the resulting list */
for (i=0; i<serial_open_device_count; ++i) {
for (j=0; j<ports; ++j)
if (0 == strcmp(serial_open_devices[i].name, list[j].name))
break;
if (j<ports)
continue;
if (ports >= max)
break;
strcpy(list[ports].name, serial_open_devices[i].name);
strcpy(list[ports].desc, serial_open_devices[i].config);
++ports;
}
if (ports) /* Order the list returned alphabetically by the port name */
qsort (list, ports, sizeof(list[0]), _serial_name_compare);
return ports;
}
static char* sim_serial_getname (int number, char* name)
{
SERIAL_LIST list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
if (count <= number)
return NULL;
strcpy(name, list[number].name);
return name;
}
static char* sim_serial_getname_bydesc (char* desc, char* name)
{
SERIAL_LIST list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
int i;
size_t j=strlen(desc);
for (i=0; i<count; i++) {
int found = 1;
size_t k = strlen(list[i].desc);
if (j != k)
continue;
for (k=0; k<j; k++)
if (tolower(list[i].desc[k]) != tolower(desc[k]))
found = 0;
if (found == 0)
continue;
/* found a case-insensitive description match */
strcpy(name, list[i].name);
return name;
}
/* not found */
return NULL;
}
static char* sim_serial_getname_byname (char* name, char* temp)
{
SERIAL_LIST list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;
found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
if ((n == strlen(list[i].name)) &&
(strncasecmp(name, list[i].name, n) == 0)) {
found = 1;
strcpy(temp, list[i].name); /* only case might be different */
}
}
return (found ? temp : NULL);
}
char* sim_serial_getdesc_byname (char* name, char* temp)
{
SERIAL_LIST list[SER_MAX_DEVICE];
int count = sim_serial_devices(SER_MAX_DEVICE, list);
size_t n;
int i, found;
found = 0;
n = strlen(name);
for (i=0; i<count && !found; i++) {
if ((n == strlen(list[i].name)) &&
(strncasecmp(name, list[i].name, n) == 0)) {
found = 1;
strcpy(temp, list[i].desc);
}
}
return (found ? temp : NULL);
}
t_stat sim_show_serial (FILE* st, DEVICE *dptr, UNIT* uptr, int32 val, CONST char* desc)
{
SERIAL_LIST list[SER_MAX_DEVICE];
int number = sim_serial_devices(SER_MAX_DEVICE, list);
fprintf(st, "Serial devices:\n");
if (number == -1)
fprintf(st, " serial support not available in simulator\n");
else {
if (number == 0) {
fprintf(st, " no serial devices are available.\n");
fprintf(st, "You may need to run with privilege or set device permissions\n");
fprintf(st, "to access local serial ports\n");
}
else {
size_t min, len;
int i;
for (i=0, min=0; i<number; i++)
if ((len = strlen(list[i].name)) > min)
min = len;
for (i=0; i<number; i++)
fprintf(st," ser%d\t%-*s%s%s%s\n", i, (int)min, list[i].name, list[i].desc[0] ? " (" : "", list[i].desc, list[i].desc[0] ? ")" : "");
}
}
if (serial_open_device_count) {
int i;
char desc[SER_DEV_DESC_MAX], *d;
fprintf(st,"Open Serial Devices:\n");
for (i=0; i<serial_open_device_count; i++) {
d = sim_serial_getdesc_byname(serial_open_devices[i].name, desc);
fprintf(st, " %s\tLn%02d %s%s%s%s\tConfig: %s\n", serial_open_devices[i].line->mp->dptr->name, (int)(serial_open_devices[i].line->mp->ldsc-serial_open_devices[i].line),
serial_open_devices[i].line->destination, ((d != NULL) && (*d != '\0')) ? " (" : "", ((d != NULL) && (*d != '\0')) ? d : "", ((d != NULL) && (*d != '\0')) ? ")" : "", serial_open_devices[i].line->serconfig);
}
}
return SCPE_OK;
}
SERHANDLE sim_open_serial (char *name, TMLN *lp, t_stat *stat)
{
char temp1[1024], devname [1024];
char *savname = name;
SERHANDLE port = INVALID_HANDLE;
CONST char *config;
t_stat status;
config = get_glyph_nc (name, devname, ';'); /* separate port name from optional config params */
if ((config == NULL) || (*config == '\0'))
config = "9600-8N1";
if (stat)
*stat = SCPE_OK;
/* translate name of type "serX" to real device name */
if ((strlen(devname) <= 5)
&& (tolower(devname[0]) == 's')
&& (tolower(devname[1]) == 'e')
&& (tolower(devname[2]) == 'r')
&& (isdigit(devname[3]))
&& (isdigit(devname[4]) || (devname[4] == '\0'))
) {
int num = atoi(&devname[3]);
savname = sim_serial_getname(num, temp1);
if (savname == NULL) { /* didn't translate */
if (stat)
*stat = SCPE_OPENERR;
return INVALID_HANDLE;
}
}
else {
/* are they trying to use device description? */
savname = sim_serial_getname_bydesc(devname, temp1);
if (savname == NULL) { /* didn't translate */
/* probably is not serX and has no description */
savname = sim_serial_getname_byname(devname, temp1);
if (savname == NULL) /* didn't translate */
savname = devname;
}
}
if (_get_open_device_byname (savname)) {
if (stat)
*stat = SCPE_OPENERR;
return INVALID_HANDLE;
}
port = sim_open_os_serial (savname);
if (port == INVALID_HANDLE) {
if (stat)
*stat = SCPE_OPENERR;
return port;
}
status = sim_config_serial (port, config); /* set serial configuration */
if ((lp) && (status == SCPE_OK)) /* line specified? */
status = tmxr_set_config_line (lp, config); /* set line speed parameters */
if (status != SCPE_OK) { /* port configuration error? */
sim_close_serial (port); /* close the port */
if (stat)
*stat = status;
port = INVALID_HANDLE; /* report error */
}
if ((port != INVALID_HANDLE) && (*config) && (lp)) {
lp->serconfig = (char *)realloc (lp->serconfig, 1 + strlen (config));
strcpy (lp->serconfig, config);
}
if (port != INVALID_HANDLE)
_serial_add_to_open_list (port, lp, savname, config);
return port;
}
void sim_close_serial (SERHANDLE port)
{
_serial_remove_from_open_list (port);
sim_close_os_serial (port);
}
t_stat sim_config_serial (SERHANDLE port, CONST char *sconfig)
{
CONST char *pptr;
CONST char *sptr, *tptr;
SERCONFIG config = { 0 };
t_bool arg_error = FALSE;
t_stat r;
struct open_serial_device *dev;
if ((sconfig == NULL) || (*sconfig == '\0'))
sconfig = "9600-8N1"; /* default settings */
pptr = sconfig;
config.baudrate = (uint32)strtotv (pptr, &sptr, 10); /* parse baud rate */
arg_error = (pptr == sptr); /* check for bad argument */
if (*sptr) /* separator present? */
sptr++; /* skip it */
config.charsize = (uint32)strtotv (sptr, &tptr, 10); /* parse character size */
arg_error = arg_error || (sptr == tptr); /* check for bad argument */
if (*tptr) /* parity character present? */
config.parity = (char)toupper (*tptr++); /* save parity character */
config.stopbits = (uint32)strtotv (tptr, &sptr, 10); /* parse number of stop bits */
arg_error = arg_error || (tptr == sptr); /* check for bad argument */
if (arg_error) /* bad conversions? */
return SCPE_ARG; /* report argument error */
if (strcmp (sptr, ".5") == 0) /* 1.5 stop bits requested? */
config.stopbits = 0; /* code request */
r = sim_config_os_serial (port, config);
dev = _get_open_device (port);
if (dev) {
dev->line->serconfig = (char *)realloc (dev->line->serconfig, 1 + strlen (sconfig));
strcpy (dev->line->serconfig, sconfig);
}
return r;
}
#if defined (_WIN32)
/* Windows serial implementation */
/* Enumerate the available serial ports.
The serial port names are extracted from the appropriate place in the
windows registry (HKLM\HARDWARE\DEVICEMAP\SERIALCOMM\). The resulting
list is sorted alphabetically by device name (COMn). The device description
is set to the OS internal name for the COM device.
*/
struct SERPORT {
HANDLE hPort;
DWORD dwEvtMask;
OVERLAPPED oReadSync;
OVERLAPPED oWriteReady;
OVERLAPPED oWriteSync;
};
static int sim_serial_os_devices (int max, SERIAL_LIST* list)
{
int ports = 0;
HKEY hSERIALCOMM;
memset(list, 0, max*sizeof(*list));
if (RegOpenKeyExA(HKEY_LOCAL_MACHINE, "HARDWARE\\DEVICEMAP\\SERIALCOMM", 0, KEY_QUERY_VALUE, &hSERIALCOMM) == ERROR_SUCCESS) {
DWORD dwIndex = 0;
DWORD dwType;
DWORD dwValueNameSize = sizeof(list[ports].desc);
DWORD dwDataSize = sizeof(list[ports].name);
/* Enumerate all the values underneath HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALCOMM */
while (RegEnumValueA(hSERIALCOMM, dwIndex, list[ports].desc, &dwValueNameSize, NULL, &dwType, (BYTE *)list[ports].name, &dwDataSize) == ERROR_SUCCESS) {
/* String values with non-zero size are the interesting ones */
if ((dwType == REG_SZ) && (dwDataSize > 0)) {
if (ports < max)
++ports;
else
break;
}
/* Be sure to clear the working entry before trying again */
memset(list[ports].name, 0, sizeof(list[ports].name));
memset(list[ports].desc, 0, sizeof(list[ports].desc));
dwValueNameSize = sizeof(list[ports].desc);
dwDataSize = sizeof(list[ports].name);
++dwIndex;
}
RegCloseKey(hSERIALCOMM);
}
return ports;
}
/* Open a serial port.
The serial port designated by "name" is opened, and the handle to the port is
returned. If an error occurs, INVALID_HANDLE is returned instead. After
opening, the port is configured with the default communication parameters
established by the system, and the timeouts are set for immediate return on a
read request to enable polling.
Implementation notes:
1. We call "GetDefaultCommConfig" to obtain the default communication
parameters for the specified port. If the name does not refer to a
communications port (serial or parallel), the function fails.
2. There is no way to limit "CreateFile" just to serial ports, so we must
check after the port is opened. The "GetCommState" routine will return
an error if the handle does not refer to a serial port.
3. Calling "GetDefaultCommConfig" for a serial port returns a structure
containing a DCB. This contains the default parameters. However, some
of the DCB fields are not set correctly, so we cannot use this directly
in a call to "SetCommState". Instead, we must copy the fields of
interest to a DCB retrieved from a call to "GetCommState".
*/
static SERHANDLE sim_open_os_serial (char *name)
{
HANDLE hPort;
SERHANDLE port;
DCB dcb;
COMMCONFIG commdefault;
DWORD error;
DWORD commsize = sizeof (commdefault);
COMMTIMEOUTS cto;
char win32name[1028];
if (!GetDefaultCommConfig (name, &commdefault, &commsize)) { /* get default comm parameters */
error = GetLastError (); /* function failed; get error */
if (error != ERROR_INVALID_PARAMETER) /* not a communications port name? */
sim_error_serial ("GetDefaultCommConfig", (int) error); /* no, so report unexpected error */
return INVALID_HANDLE; /* indicate bad port name */
}
snprintf (win32name, sizeof (win32name), "\\\\.\\%s", name);
hPort = CreateFile (win32name, GENERIC_READ | GENERIC_WRITE, /* open the port */
0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
if (hPort == INVALID_HANDLE_VALUE) { /* open failed? */
error = GetLastError (); /* get error code */
if ((error != ERROR_FILE_NOT_FOUND) && /* bad filename? */
(error != ERROR_ACCESS_DENIED)) /* already open? */
sim_error_serial ("CreateFile", (int) error); /* no, so report unexpected error */
return INVALID_HANDLE; /* indicate bad port name */
}
port = (SERHANDLE)calloc (1, sizeof(*port)); /* instantiate the SERHANDLE */
port->hPort = hPort;
if (!GetCommState (port->hPort, &dcb)) { /* get the current comm parameters */
error = GetLastError (); /* function failed; get error */
if (error != ERROR_INVALID_PARAMETER) /* not a serial port name? */
sim_error_serial ("GetCommState", (int) error); /* no, so report unexpected error */
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate bad port name */
}
dcb.BaudRate = commdefault.dcb.BaudRate; /* copy default parameters of interest */
dcb.Parity = commdefault.dcb.Parity;
dcb.ByteSize = commdefault.dcb.ByteSize;
dcb.StopBits = commdefault.dcb.StopBits;
dcb.fOutX = commdefault.dcb.fOutX;
dcb.fInX = commdefault.dcb.fInX;
dcb.fDtrControl = DTR_CONTROL_DISABLE; /* disable DTR initially until poll connects */
if (!SetCommState (port->hPort, &dcb)) { /* configure the port with default parameters */
sim_error_serial ("SetCommState", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
cto.ReadIntervalTimeout = MAXDWORD; /* set port to return immediately on read */
cto.ReadTotalTimeoutMultiplier = 0; /* i.e., to enable polling */
cto.ReadTotalTimeoutConstant = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant = 0;
if (!SetCommTimeouts (port->hPort, &cto)) { /* configure port timeouts */
sim_error_serial ("SetCommTimeouts", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
/* Create an event object for use by WaitCommEvent. */
port->oWriteReady.hEvent = CreateEvent(NULL, /* default security attributes */
TRUE, /* manual-reset event */
TRUE, /* signaled */
NULL); /* no name */
if (port->oWriteReady.hEvent == NULL) {
sim_error_serial ("CreateEvent", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
port->oReadSync.hEvent = CreateEvent(NULL, /* default security attributes */
TRUE, /* manual-reset event */
FALSE, /* not signaled */
NULL); /* no name */
if (port->oReadSync.hEvent == NULL) {
sim_error_serial ("CreateEvent", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
port->oWriteSync.hEvent = CreateEvent(NULL, /* default security attributes */
TRUE, /* manual-reset event */
FALSE, /* not signaled */
NULL); /* no name */
if (port->oWriteSync.hEvent == NULL) {
sim_error_serial ("CreateEvent", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
if (!SetCommMask (port->hPort, EV_TXEMPTY)) {
sim_error_serial ("SetCommMask", /* function failed; report unexpected error */
(int) GetLastError ());
sim_close_os_serial (port); /* close port */
return INVALID_HANDLE; /* and indicate failure to caller */
}
return port; /* return port handle on success */
}
/* Configure a serial port.
Port parameters are configured as specified in the "config" structure. If
"config" contains an invalid configuration value, or if the host system
rejects the configuration (e.g., by requesting an unsupported combination of
character size and stop bits), SCPE_ARG is returned to the caller. If an
unexpected error occurs, SCPE_IOERR is returned. If the configuration
succeeds, SCPE_OK is returned.
Implementation notes:
1. We do not enable input parity checking, as the multiplexer library has no
way of communicating parity errors back to the target simulator.
2. A zero value for the "stopbits" field of the "config" structure implies
1.5 stop bits.
*/
static t_stat sim_config_os_serial (SERHANDLE port, SERCONFIG config)
{
static const struct {
char parity;
BYTE parity_code;
} parity_map [] =
{ { 'E', EVENPARITY }, { 'M', MARKPARITY }, { 'N', NOPARITY },
{ 'O', ODDPARITY }, { 'S', SPACEPARITY } };
static const int32 parity_count = sizeof (parity_map) / sizeof (parity_map [0]);
DCB dcb;
DWORD error;
int32 i;
if (!GetCommState (port->hPort, &dcb)) { /* get the current comm parameters */
sim_error_serial ("GetCommState", /* function failed; report unexpected error */
(int) GetLastError ());
return SCPE_IOERR; /* return failure status */
}
dcb.BaudRate = config.baudrate; /* assign baud rate */
if (config.charsize >= 5 && config.charsize <= 8) /* character size OK? */
dcb.ByteSize = (BYTE)config.charsize; /* assign character size */
else
return SCPE_ARG; /* not a valid size */
for (i = 0; i < parity_count; i++) /* assign parity */
if (config.parity == parity_map [i].parity) { /* match mapping value? */
dcb.Parity = parity_map [i].parity_code; /* assign corresponding code */
break;
}
if (i == parity_count) /* parity assigned? */
return SCPE_ARG; /* not a valid parity specifier */
if (config.stopbits == 1) /* assign stop bits */
dcb.StopBits = ONESTOPBIT;
else if (config.stopbits == 2)
dcb.StopBits = TWOSTOPBITS;
else if (config.stopbits == 0) /* 0 implies 1.5 stop bits */
dcb.StopBits = ONE5STOPBITS;
else
return SCPE_ARG; /* not a valid number of stop bits */
if (!SetCommState (port->hPort, &dcb)) { /* set the configuration */
error = GetLastError (); /* check for error */
if (error == ERROR_INVALID_PARAMETER) /* invalid configuration? */
return SCPE_ARG; /* report as argument error */
sim_error_serial ("SetCommState", (int) error); /* function failed; report unexpected error */
return SCPE_IOERR; /* return failure status */
}
return SCPE_OK; /* return success status */
}
/* Control a serial port.
The DTR and RTS line of the serial port is set or cleared as indicated in
the respective bits_to_set or bits_to_clear parameters. If the
incoming_bits parameter is not NULL, then the modem status bits DCD, RNG,
DSR and CTS are returned.
If unreasonable or nonsense bits_to_set or bits_to_clear bits are
specified, then the return status is SCPE_ARG;
If an error occurs, SCPE_IOERR is returned.
*/
t_stat sim_control_serial (SERHANDLE port, int32 bits_to_set, int32 bits_to_clear, int32 *incoming_bits)
{
if ((bits_to_set & ~(TMXR_MDM_OUTGOING)) || /* Assure only settable bits */
(bits_to_clear & ~(TMXR_MDM_OUTGOING)) ||
(bits_to_set & bits_to_clear)) /* and can't set and clear the same bits */
return SCPE_ARG;
if (bits_to_set&TMXR_MDM_DTR)
if (!EscapeCommFunction (port->hPort, SETDTR)) {
sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
return SCPE_IOERR;
}
if (bits_to_clear&TMXR_MDM_DTR)
if (!EscapeCommFunction (port->hPort, CLRDTR)) {
sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
return SCPE_IOERR;
}
if (bits_to_set&TMXR_MDM_RTS)
if (!EscapeCommFunction (port->hPort, SETRTS)) {
sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
return SCPE_IOERR;
}
if (bits_to_clear&TMXR_MDM_RTS)
if (!EscapeCommFunction (port->hPort, CLRRTS)) {
sim_error_serial ("EscapeCommFunction", (int) GetLastError ());
return SCPE_IOERR;
}
if (incoming_bits) {
DWORD ModemStat;
if (!GetCommModemStatus (port->hPort, &ModemStat)) {
sim_error_serial ("GetCommModemStatus", (int) GetLastError ());
return SCPE_IOERR;
}
*incoming_bits = ((ModemStat&MS_CTS_ON) ? TMXR_MDM_CTS : 0) |
((ModemStat&MS_DSR_ON) ? TMXR_MDM_DSR : 0) |
((ModemStat&MS_RING_ON) ? TMXR_MDM_RNG : 0) |
((ModemStat&MS_RLSD_ON) ? TMXR_MDM_DCD : 0);
}
return SCPE_OK;
}
/* Read from a serial port.
The port is checked for available characters. If any are present, they are
copied to the passed buffer, and the count of characters is returned. If no
characters are available, 0 is returned. If an error occurs, -1 is returned.
If a BREAK is detected on the communications line, the corresponding flag in
the "brk" array is set.
Implementation notes:
1. The "ClearCommError" function will set the CE_BREAK flag in the returned
errors value if a BREAK has occurred. However, we do not know where in
the serial stream it happened, as CE_BREAK isn't associated with a
specific character. Because the "brk" array does want a flag associated
with a specific character, we guess at the proper location by setting
the "brk" entry corresponding to the first NUL in the character stream.
If no NUL is present, then the "brk" entry associated with the first
character is set.
*/
int32 sim_read_serial (SERHANDLE port, char *buffer, int32 count, char *brk)
{
DWORD read;
DWORD commerrors;
COMSTAT cs;
char *bptr;
memset (brk, 0, count); /* start with no break indicators */
if (!ClearCommError (port->hPort, &commerrors, &cs)) { /* get the comm error flags */
sim_error_serial ("ClearCommError", /* function failed; report unexpected error */
(int) GetLastError ());
return -1; /* return failure to caller */
}
if (!ReadFile (port->hPort, (LPVOID) buffer, /* read any available characters */
(DWORD) count, &read, &port->oReadSync)) {
sim_error_serial ("ReadFile", /* function failed; report unexpected error */
(int) GetLastError ());
return -1; /* return failure to caller */
}
if (commerrors & CE_BREAK) { /* was a BREAK detected? */
bptr = (char *) memchr (buffer, 0, read); /* search for the first NUL in the buffer */
if (bptr) /* was one found? */
brk = brk + (bptr - buffer); /* calculate corresponding position */
*brk = 1; /* set the BREAK flag */
}
return read; /* return the number of characters read */
}
/* Write to a serial port.
"Count" characters are written from "buffer" to the serial port. The actual
number of characters written to the port is returned. If an error occurred
on writing, -1 is returned.
*/
int32 sim_write_serial (SERHANDLE port, char *buffer, int32 count)
{
if ((!WriteFile (port->hPort, (LPVOID) buffer, /* write the buffer to the serial port */
(DWORD) count, NULL, &port->oWriteSync)) &&
(GetLastError () != ERROR_IO_PENDING)) {
sim_error_serial ("WriteFile", /* function failed; report unexpected error */
(int) GetLastError ());
return -1; /* return failure to caller */
}
return count; /* return number of characters written/queued */
}
/* Close a serial port.
The serial port is closed. Errors are ignored.
*/
static void sim_close_os_serial (SERHANDLE port)
{
if (port->oWriteReady.hEvent)
CloseHandle (port->oWriteReady.hEvent); /* close the event handle */
if (port->oReadSync.hEvent)
CloseHandle (port->oReadSync.hEvent); /* close the event handle */
if (port->oWriteSync.hEvent)
CloseHandle (port->oWriteSync.hEvent); /* close the event handle */
if (port->hPort)
CloseHandle (port->hPort); /* close the port */
free (port);
}
#elif defined (__unix__) || defined(__APPLE__) || defined(__hpux)
struct SERPORT {
int port;
};
#if defined(__linux) || defined(__linux__)
#include <dirent.h>
#include <libgen.h>
#include <unistd.h>
#include <sys/stat.h>
#endif /* __linux__ */
/* UNIX implementation */
/* Enumerate the available serial ports.
The serial port names generated by attempting to open /dev/ttyS0 thru
/dev/ttyS63 and /dev/ttyUSB0 thru /dev/ttyUSB63 and /dev/tty.serial0
thru /dev/tty.serial63. Ones we can open and are ttys (as determined
by isatty()) are added to the list. The list is sorted alphabetically
by device name.
*/
static int sim_serial_os_devices (int max, SERIAL_LIST* list)
{
int i;
int port;
int ports = 0;
memset(list, 0, max*sizeof(*list));
#if defined(__linux) || defined(__linux__)
if (1) {
struct dirent **namelist = NULL;
struct stat st;
i = scandir("/sys/class/tty/", &namelist, NULL, NULL);
while (0 < i--) {
if (strcmp(namelist[i]->d_name, ".") &&
strcmp(namelist[i]->d_name, "..")) {
char path[1024], devicepath[1024], driverpath[1024];
snprintf (path, sizeof (path), "/sys/class/tty/%s", namelist[i]->d_name);
snprintf (devicepath, sizeof (devicepath), "/sys/class/tty/%s/device", namelist[i]->d_name);
snprintf (driverpath, sizeof (driverpath), "/sys/class/tty/%s/device/driver", namelist[i]->d_name);
if ((lstat(devicepath, &st) == 0) && S_ISLNK(st.st_mode)) {
char buffer[1024];
memset (buffer, 0, sizeof(buffer));
if (readlink(driverpath, buffer, sizeof(buffer)) > 0) {
snprintf (list[ports].name, sizeof (list[ports].name), "/dev/%s", basename (path));
port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK); /* open the port */
if (port != -1) { /* open OK? */
if ((ports < max) && /* room for another? */
(isatty (port))) /* is device a TTY? */
++ports;
close (port);
}
}
}
}
free (namelist[i]);
}
free (namelist);
}
#elif defined(__hpux)
for (i=0; (ports < max) && (i < 64); ++i) {
snprintf (list[ports].name, sizeof (list[ports].name), "/dev/tty%dp%d", i/8, i%8);
port = open (list[ports].name, O_RDWR | O_NOCTTY | O_NONBLOCK); /* open the port */
if (port != -1) { /* open OK? */
if (isatty (port)) /* is device a TTY? */
++ports;
close (port);
}
}
#else /* Non Linux/HP-UX, just try some well known device names */