[go: up one dir, main page]

File: serial.cpp

package info (click to toggle)
libcommoncpp2 1.6.2-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 4,732 kB
  • ctags: 3,482
  • sloc: cpp: 27,170; sh: 9,607; ansic: 1,121; makefile: 223; xml: 5
file content (1874 lines) | stat: -rw-r--r-- 32,821 bytes parent folder | download
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
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
// Copyright (C) 1999-2005 Open Source Telecom Corporation.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 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 General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// As a special exception, you may use this file as part of a free software
// library without restriction.  Specifically, if other files instantiate
// templates or use macros or inline functions from this file, or you compile
// this file and link it with other files to produce an executable, this
// file does not by itself cause the resulting executable to be covered by
// the GNU General Public License.  This exception does not however
// invalidate any other reasons why the executable file might be covered by
// the GNU General Public License.
//
// This exception applies only to the code released under the name GNU
// Common C++.  If you copy code from other releases into a copy of GNU
// Common C++, as the General Public License permits, the exception does
// not apply to the code that you add in this way.  To avoid misleading
// anyone as to the status of such modified files, you must delete
// this exception notice from them.
//
// If you write modifications of your own for GNU Common C++, it is your choice
// whether to permit this exception to apply to your modifications.
// If you do not wish that, delete this exception notice.
//

#include <cc++/config.h>
#ifdef	CCXX_WITHOUT_EXTRAS
#include <cc++/export.h>
#endif
#include <cc++/exception.h>
#include <cc++/thread.h>
#include <cc++/file.h>
#ifndef	CCXX_WITHOUT_EXTRAS
#include <cc++/export.h>
#endif
#include <cc++/serial.h>
#include "private.h"
#include <cstdlib>
#include <climits>

#ifdef	WIN32

#define	B256000		CBR_256000
#define	B128000		CBR_128000
#define	B115200		CBR_115200
#define B57600		CBR_57600
#define	B56000		CBR_56000
#define	B38400		CBR_38400
#define	B19200		CBR_19200
#define	B14400		CBR_14400
#define	B9600		CBR_9600
#define	B4800		CBR_4800
#define	B2400		CBR_2400
#define	B1200		CBR_1200
#define	B600		CBR_600
#define	B300		CBR_300
#define	B110		CBR_110

#include <io.h>
#include <fcntl.h>
#else
#include <sys/ioctl.h>
#include <termios.h>
#endif

#include <cerrno>
#include <iostream>

#ifdef	CCXX_NAMESPACES
namespace ost {
using std::streambuf;
using std::iostream;
using std::ios;
#endif

#ifndef	MAX_INPUT
#define	MAX_INPUT 255
#endif

#ifndef MAX_CANON
#define MAX_CANON MAX_INPUT
#endif

#ifdef	__FreeBSD__
#undef	_PC_MAX_INPUT
#undef	_PC_MAX_CANON
#endif

#if defined(__QNX__)
#define CRTSCTS (IHFLOW | OHFLOW)
#endif

#if defined(_THR_UNIXWARE) || defined(__hpux) || defined(_AIX)
#include <sys/termiox.h>
#define	CRTSCTS	(CTSXON | RTSXOFF)
#endif


// IRIX

#ifndef	CRTSCTS
#ifdef	CNEW_RTSCTS
#define	CRTSCTS (CNEW_RTSCTS)
#endif
#endif

#if defined(CTSXON) && defined(RTSXOFF) && !defined(CRTSCTS)
#define	CRTSCTS (CTSXON | RTSXOFF)
#endif

#ifndef	CRTSCTS
#define	CRTSCTS	0
#endif

Serial::Serial(const char *fname)
{
	initSerial();

	open(fname);

#ifdef	WIN32
	if(dev == INVALID_HANDLE_VALUE)
#else
	if(dev < 0)
#endif
	{
		error(errOpenFailed);
		return;
	}

#ifdef	WIN32
	COMMTIMEOUTS  CommTimeOuts ;

	GetCommTimeouts(dev, &CommTimeOuts);

//    CommTimeOuts.ReadIntervalTimeout = MAXDWORD;
	CommTimeOuts.ReadIntervalTimeout = 0;

	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 0;
	CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.WriteTotalTimeoutConstant = 1000;

	SetCommTimeouts(dev, &CommTimeOuts) ;

#else

	if(!isatty(dev)) {
		Serial::close();
		error(errOpenNoTty);
		return;
	}
#endif
	}

Serial::~Serial()
{
	endSerial();
	}

void Serial::initConfig(void)
{
#ifdef	WIN32

#define ASCII_XON       0x11
#define ASCII_XOFF      0x13

	DCB * attr = (DCB *)current;
	DCB * orig = (DCB *)original;

	attr->DCBlength = sizeof(DCB);
	orig->DCBlength = sizeof(DCB);

	GetCommState(dev, orig);
	GetCommState(dev, attr);

	attr->DCBlength = sizeof(DCB);
	attr->BaudRate = 1200;
	attr->Parity = NOPARITY;
	attr->ByteSize = 8;

	attr->XonChar = ASCII_XON;
	attr->XoffChar = ASCII_XOFF;
	attr->XonLim = 100;
	attr->XoffLim = 100;
	attr->fOutxDsrFlow = 0;
	attr->fDtrControl = DTR_CONTROL_ENABLE;
	attr->fOutxCtsFlow = 1;
	attr->fRtsControl = RTS_CONTROL_ENABLE;
	attr->fInX = attr->fOutX = 0;

	attr->fBinary = true;
	attr->fParity = true;

	SetCommState(dev, attr);

#else
	struct termios *attr = (struct termios *)current;
	struct termios *orig = (struct termios *)original;
	long ioflags = fcntl(dev, F_GETFL);

	tcgetattr(dev, (struct termios *)original);
	tcgetattr(dev, (struct termios *)current);

	attr->c_oflag = attr->c_lflag = 0;
	attr->c_cflag = CLOCAL | CREAD | HUPCL;
	attr->c_iflag = IGNBRK;

	memset(attr->c_cc, 0, sizeof(attr->c_cc));
	attr->c_cc[VMIN] = 1;

	// inherit original settings, maybe we should keep more??
	cfsetispeed(attr, cfgetispeed(orig));
	cfsetospeed(attr, cfgetospeed(orig));
	attr->c_cflag |= orig->c_cflag & (CRTSCTS | CSIZE | PARENB | PARODD | CSTOPB);
	attr->c_iflag |= orig->c_iflag & (IXON | IXANY | IXOFF);

	tcsetattr(dev, TCSANOW, attr);
	fcntl(dev, F_SETFL, ioflags & ~O_NDELAY);

#if defined(TIOCM_RTS) && defined(TIOCMODG)
	int mcs = 0;
	ioctl(dev, TIOCMODG, &mcs);
	mcs |= TIOCM_RTS;
	ioctl(dev, TIOCMODS, &mcs);
#endif

#ifdef	_COHERENT
	ioctl(dev, TIOCSRTS, 0);
#endif

#endif	// WIN32
	}

void Serial::restore(void)
{
#ifdef	WIN32
	memcpy(current, original, sizeof(DCB));
	SetCommState(dev, (DCB *)current);
#else
	memcpy(current, original, sizeof(struct termios));
	tcsetattr(dev, TCSANOW, (struct termios *)current);
#endif
	}

void Serial::initSerial(void)
{
	flags.thrown = false;
	flags.linebuf = false;
	errid = errSuccess;
	errstr = NULL;

	dev = INVALID_HANDLE_VALUE;
#ifdef	WIN32
	current = new DCB;
	original = new DCB;
#else
	current = new struct termios;
	original = new struct termios;
#endif
	}

void Serial::endSerial(void)
{
#ifdef	WIN32
	if(dev == INVALID_HANDLE_VALUE && original)
		SetCommState(dev, (DCB *)original);

	if(current)
		delete (DCB *)current;

	if(original)
		delete (DCB *)original;
#else
	if(dev < 0 && original)
		tcsetattr(dev, TCSANOW, (struct termios *)original);

	if(current)
		delete (struct termios *)current;

	if(original)
		delete (struct termios *)original;
#endif
	Serial::close();

	current = NULL;
	original = NULL;

	}

Serial::Error Serial::error(Error err, char *errs)
{
	errid = err;
	errstr = errs;
	if(!err)
		return err;

	if(flags.thrown)
		return err;

	// prevents recursive throws

	flags.thrown = true;
#ifdef	CCXX_EXCEPTIONS
	if(Thread::getException() == Thread::throwObject)
	        throw((Serial *)this);
#ifdef	COMMON_STD_EXCEPTION
	else if(Thread::getException() == Thread::throwException) {
		if(!errs)
			errs = "";
		throw SerException(String(errs));
	}
#endif
#endif
	return err;
	}

int Serial::setPacketInput(int size, unsigned char btimer)
{
#ifdef	WIN32
	//	Still to be done......
	return 0;
#else

#ifdef	_PC_MAX_INPUT
	int max = fpathconf(dev, _PC_MAX_INPUT);
#else
	int max = MAX_INPUT;
#endif
	struct termios *attr = (struct termios *)current;

	if(size > max)
		size = max;

	attr->c_cc[VEOL] = attr->c_cc[VEOL2] = 0;
	attr->c_cc[VMIN] = (unsigned char)size;
	attr->c_cc[VTIME] = btimer;
	attr->c_lflag &= ~ICANON;
	tcsetattr(dev, TCSANOW, attr);
	bufsize = size;
	return size;
#endif
	}

int Serial::setLineInput(char newline, char nl1)
{
#ifdef	WIN32
	//	Still to be done......
	return 0;
#else

	struct termios *attr = (struct termios *)current;
	attr->c_cc[VMIN] = attr->c_cc[VTIME] = 0;
	attr->c_cc[VEOL] = newline;
	attr->c_cc[VEOL2] = nl1;
	attr->c_lflag |= ICANON;
	tcsetattr(dev, TCSANOW, attr);
#ifdef _PC_MAX_CANON
	bufsize = fpathconf(dev, _PC_MAX_CANON);
#else
	bufsize = MAX_CANON;
#endif
	return bufsize;
#endif

	}

void Serial::flushInput(void)
{
#ifdef	WIN32
	PurgeComm(dev, PURGE_RXABORT | PURGE_RXCLEAR);
#else
	tcflush(dev, TCIFLUSH);
#endif
	}

void Serial::flushOutput(void)
{
#ifdef	WIN32
	PurgeComm(dev, PURGE_TXABORT | PURGE_TXCLEAR);
#else
	tcflush(dev, TCOFLUSH);
#endif
	}

void Serial::waitOutput(void)
{
#ifdef	WIN32

#else
	tcdrain(dev);
#endif
	}

Serial &Serial::operator=(const Serial &ser)
{
	Serial::close();

	if(ser.dev < 0)
		return *this;

#ifdef	WIN32
	HANDLE process = GetCurrentProcess();

	int result = DuplicateHandle(process, ser.dev, process, &dev, DUPLICATE_SAME_ACCESS, 0, 0);

	if (0 == result) {
		memcpy(current, ser.current, sizeof(DCB));
		memcpy(original, ser.original, sizeof(DCB));
	}
#else
	dev = dup(ser.dev);

	memcpy(current, ser.current, sizeof(struct termios));
	memcpy(original, ser.original, sizeof(struct termios));
#endif
	return *this;
	}


void Serial::open(const char * fname)
{

#ifndef	WIN32
	int cflags = O_RDWR | O_NDELAY;
	dev = ::open(fname, cflags);
	if(dev > -1)
		initConfig();
#else
	// open COMM device
	dev = CreateFile(fname,
		GENERIC_READ | GENERIC_WRITE,
		0,                    // exclusive access
		NULL,                 // no security attrs
		OPEN_EXISTING,
		FILE_FLAG_OVERLAPPED | FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING,
		NULL);
	if(dev != INVALID_HANDLE_VALUE)
		initConfig();
#endif
	}

#ifdef	WIN32
int Serial::aRead(char * Data, const int Length)
{

	unsigned long	dwLength = 0, dwError, dwReadLength;
	COMSTAT	cs;
	OVERLAPPED ol;

	// Return zero if handle is invalid
	if(dev == INVALID_HANDLE_VALUE)
		return 0;

	// Read max length or only what is available
	ClearCommError(dev, &dwError, &cs);

	// If not requiring an exact byte count, get whatever is available
	if(Length > (int)cs.cbInQue)
		dwReadLength = cs.cbInQue;
	else
		dwReadLength = Length;

	memset(&ol, 0, sizeof(OVERLAPPED));
	ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if(dwReadLength > 0) {
		if(ReadFile(dev, Data, dwReadLength, &dwLength, &ol) == FALSE) {
			if(GetLastError() == ERROR_IO_PENDING) {
				WaitForSingleObject(ol.hEvent, INFINITE);
				GetOverlappedResult(dev, &ol, &dwLength, TRUE);
				}
			else
				ClearCommError(dev, &dwError, &cs);
			}
		}

	if(ol.hEvent != INVALID_HANDLE_VALUE)
		CloseHandle(ol.hEvent);

	return dwLength;
	}

int Serial::aWrite(const char * Data, const int Length)
{
	COMSTAT	cs;
	unsigned long dwError = 0;
	OVERLAPPED ol;

	// Clear the com port of any error condition prior to read
	ClearCommError(dev, &dwError, &cs);

	unsigned long retSize = 0;

	memset(&ol, 0, sizeof(OVERLAPPED));
	ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

	if(WriteFile(dev, Data, Length, &retSize, &ol) == FALSE) {
		if(GetLastError() == ERROR_IO_PENDING) {
			WaitForSingleObject(ol.hEvent, INFINITE);
			GetOverlappedResult(dev, &ol, &retSize, TRUE);
			}
		else
			ClearCommError(dev, &dwError, &cs);
		}

	if(ol.hEvent != INVALID_HANDLE_VALUE)
		CloseHandle(ol.hEvent);

	return retSize;
	}
#else
int Serial::aRead(char *Data, const int Length)
{
	return ::read(dev, Data, Length);
	}

int Serial::aWrite(const char *Data, const int Length)
{
	return ::write(dev, Data, Length);
	}
#endif

void Serial::close()
{
#ifdef	WIN32
	CloseHandle(dev);
#else
	::close(dev);
#endif

	dev = INVALID_HANDLE_VALUE;
	}
























/*
const int iAsync::getTimeOuts(unsigned long & readTimeout, unsigned long & writeTimeout)
{
	return GetCommTimeouts(_TheHandle, &CommTimeOuts);
	}

const int iAsync::setTimeOuts(unsigned long readTimeout, unsigned long writeTimeout)
{
	COMMTIMEOUTS  CommTimeOuts ;

	getTimeOuts(CommTimeOuts);

	CommTimeOuts.ReadIntervalTimeout = readTimeout;
	CommTimeOuts.ReadTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.ReadTotalTimeoutConstant = 0;
	CommTimeOuts.WriteTotalTimeoutMultiplier = 0 ;
	CommTimeOuts.WriteTotalTimeoutConstant = 1000;

	return GetCommTimeouts(_TheHandle, &CommTimeOuts);
	}
	return SetCommTimeouts(_TheHandle, &CommTimeOuts) ;
{
	DCB        dcb ;

	dcb.DCBlength = sizeof(DCB) ;

	GetCommState(_TheHandle, &dcb) ;

	// hardcode this stuff for now.....
	dcb.BaudRate = _TheBaudrate;
	dcb.ByteSize = 8;
	dcb.Parity   = NOPARITY;
	dcb.StopBits = ONESTOPBIT;
	dcb.fOutxDsrFlow = 0;
	dcb.fDtrControl = DTR_CONTROL_ENABLE ;
	dcb.fOutxCtsFlow = 1;
	dcb.fRtsControl = RTS_CONTROL_HANDSHAKE ;
	dcb.fInX = dcb.fOutX = 0;

	dcb.XonChar = ASCII_XON;
	dcb.XoffChar = ASCII_XOFF;
	dcb.XonLim = 100;
	dcb.XoffLim = 100;

	// other various settings

	dcb.fBinary = TRUE;
	dcb.fParity = TRUE;

	GetCommState(_TheHandle, &dcb) ;
	dcb.DCBlength = sizeof(DCB) ;
	dcb.BaudRate = _TheBaudrate;
	SetCommState(_TheHandle, &dcb) ;

	}
*/

Serial::Error Serial::setSpeed(unsigned long speed)
{
	unsigned long rate;

	switch(speed) {
#ifdef B115200
		case 115200:
				rate = B115200;
				break;
#endif
#ifdef B57600
		case 57600:
				rate = B57600;
				break;
#endif
#ifdef B38400
		case 38400:
				rate = B38400;
				break;
#endif
		case 19200:
				rate = B19200;
				break;
		case 9600:
				rate = B9600;
				break;
		case 4800:
				rate = B4800;
				break;
		case 2400:
				rate = B2400;
				break;
		case 1200:
				rate = B1200;
				break;
		case 600:
				rate = B600;
				break;
		case 300:
				rate = B300;
				break;
		case 110:
				rate = B110;
				break;
#ifdef	B0
		case 0:
				rate = B0;
				break;
#endif
	default:
		return error(errSpeedInvalid);
	}

#ifdef	WIN32

	DCB		* dcb = (DCB *)current;
	dcb->DCBlength = sizeof(DCB);
	GetCommState(dev, dcb);

	dcb->BaudRate = rate;
	SetCommState(dev, dcb) ;

#else
	struct termios *attr = (struct termios *)current;
	cfsetispeed(attr, rate);
	cfsetospeed(attr, rate);
	tcsetattr(dev, TCSANOW, attr);
#endif
	return errSuccess;
	}

Serial::Error Serial::setFlowControl(Flow flow)
{
#ifdef	WIN32

	DCB * attr = (DCB *)current;
	attr->XonChar = ASCII_XON;
	attr->XoffChar = ASCII_XOFF;
	attr->XonLim = 100;
	attr->XoffLim = 100;

	switch(flow) {
	case flowSoft:
		attr->fInX = attr->fOutX = 1;
		break;
	case flowBoth:
		attr->fInX = attr->fOutX = 1;
	case flowHard:
		attr->fOutxCtsFlow = 1;
		attr->fRtsControl = RTS_CONTROL_HANDSHAKE;
		break;
	case flowNone:
		break;
	default:
		return error(errFlowInvalid);
	}

	SetCommState(dev, attr);
#else

	struct termios *attr = (struct termios *)current;

	attr->c_cflag &= ~CRTSCTS;
	attr->c_iflag &= ~(IXON | IXANY | IXOFF);

	switch(flow) {
	case flowSoft:
		attr->c_iflag |= (IXON | IXANY | IXOFF);
		break;
	case flowBoth:
		attr->c_iflag |= (IXON | IXANY | IXOFF);
	case flowHard:
		attr->c_cflag |= CRTSCTS;
		break;
	case flowNone:
		break;
	default:
		return error(errFlowInvalid);
	}

	tcsetattr(dev, TCSANOW, attr);

#endif
	return errSuccess;
	}

Serial::Error Serial::setStopBits(int bits)
{
#ifdef	WIN32

	DCB * attr = (DCB *)current;
	switch(bits) {
	case 1:
		attr->StopBits = ONESTOPBIT;
		break;
	case 2:
		attr->StopBits = TWOSTOPBITS;
		break;
	default:
		return error(errStopbitsInvalid);
	}

	SetCommState(dev, attr);
#else
	struct termios *attr = (struct termios *)current;
	attr->c_cflag &= ~CSTOPB;

	switch(bits) {
	case 1:
		break;
	case 2:
		attr->c_cflag |= CSTOPB;
		break;
	default:
		return error(errStopbitsInvalid);
	}
	tcsetattr(dev, TCSANOW, attr);
#endif
	return errSuccess;
	}

Serial::Error Serial::setCharBits(int bits)
{
#ifdef	WIN32

	DCB * attr = (DCB *)current;
	switch(bits) {
	case 5:
	case 6:
	case 7:
	case 8:
		attr->ByteSize = bits;
		break;
	default:
		return error(errCharsizeInvalid);
	}
	SetCommState(dev, attr);
#else
	struct termios *attr = (struct termios *)current;
	attr->c_cflag &= ~CSIZE;

	switch(bits) {
	case 5:
		attr->c_cflag |= CS5;
		break;
	case 6:
		attr->c_cflag |= CS6;
		break;
	case 7:
		attr->c_cflag |= CS7;
		break;
	case 8:
		attr->c_cflag |= CS8;
		break;
	default:
		return error(errCharsizeInvalid);
	}
	tcsetattr(dev, TCSANOW, attr);
#endif
	return errSuccess;
	}

Serial::Error Serial::setParity(Parity parity)
{
#ifdef	WIN32

	DCB * attr = (DCB *)current;
	switch(parity) {
	case parityEven:
		attr->Parity = EVENPARITY;
		break;
	case parityOdd:
		attr->Parity = ODDPARITY;
		break;
	case parityNone:
		attr->Parity = NOPARITY;
		break;
	default:
		return error(errParityInvalid);
	}
	SetCommState(dev, attr);
#else
	struct termios *attr = (struct termios *)current;
	attr->c_cflag &= ~(PARENB | PARODD);

	switch(parity) {
	case parityEven:
		attr->c_cflag |= PARENB;
		break;
	case parityOdd:
		attr->c_cflag |= (PARENB | PARODD);
		break;
	case parityNone:
		break;
	default:
		return error(errParityInvalid);
	}
	tcsetattr(dev, TCSANOW, attr);
#endif
	return errSuccess;
	}

void Serial::sendBreak(void)
{
#ifdef	WIN32
	SetCommBreak(dev);
	Thread::sleep(100L);
	ClearCommBreak(dev);
#else
	tcsendbreak(dev, 0);
#endif
	}

void Serial::toggleDTR(timeout_t millisec)
{
#ifdef	WIN32
	EscapeCommFunction(dev, CLRDTR);
	if(millisec) {
		Thread::sleep(millisec);
		EscapeCommFunction(dev, SETDTR);
	}

#else
	struct termios tty, old;
	tcgetattr(dev, &tty);
	tcgetattr(dev, &old);
	cfsetospeed(&tty, B0);
	cfsetispeed(&tty, B0);
	tcsetattr(dev, TCSANOW, &tty);

	if(millisec) {
		Thread::sleep(millisec);
		tcsetattr(dev, TCSANOW, &old);
	}
#endif
	}

bool Serial::isPending(Pending pending, timeout_t timeout)
{
#ifdef	WIN32
	unsigned long	dwError;
	COMSTAT	cs;

	ClearCommError(dev, &dwError, &cs);

	if(timeout == 0 || ((pending == pendingInput) && (0 != cs.cbInQue)) ||
	   ((pending == pendingOutput) && (0 != cs.cbOutQue)) || (pending == pendingError))
	{
		switch(pending) {
		case pendingInput:
			return (0 != cs.cbInQue);
		case pendingOutput:
			return (0 != cs.cbOutQue);
		case pendingError:
			return false;
		}
		}
	else {
		Thread::Cancel save = Thread::enterCancel();
		OVERLAPPED ol;
		DWORD dwMask;
		DWORD dwEvents = 0;
		BOOL suc;

		memset(&ol, 0, sizeof(OVERLAPPED));
		ol.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);

		if(pending == pendingInput)
			dwMask = EV_RXCHAR;
		else if(pending == pendingOutput)
			dwMask = EV_TXEMPTY;
		else   // on error
			dwMask = EV_ERR;

		SetCommMask(dev, dwMask);
		// let's wait for event or timeout
		if((suc = WaitCommEvent(dev, &dwEvents, &ol)) == FALSE) {
			if(GetLastError() == ERROR_IO_PENDING) {
				DWORD transferred;

				dwError = WaitForSingleObject(ol.hEvent, timeout);
				if (dwError != WAIT_OBJECT_0)
					SetCommMask(dev, 0);

				suc = GetOverlappedResult(dev, &ol, &transferred, TRUE);
				if (suc)
					suc = (dwEvents & dwMask) ? TRUE : FALSE;
				}
			else
				ClearCommError(dev, &dwError, &cs);
			}

		if(ol.hEvent != INVALID_HANDLE_VALUE)
			CloseHandle(ol.hEvent);

		Thread::exitCancel(save);
		if(suc == FALSE)
				return false;
		return true;
		}
#else


	int status;
#ifdef HAVE_POLL
	struct pollfd pfd;

	pfd.fd = dev;
	pfd.revents = 0;
	switch(pending) {
	case pendingInput:
		pfd.events = POLLIN;
		break;
	case pendingOutput:
		pfd.events = POLLOUT;
		break;
	case pendingError:
		pfd.events = POLLERR | POLLHUP;
		break;
	}

	status = 0;
	while(status < 1) {
		if(timeout == TIMEOUT_INF)
			status = poll(&pfd, 1, -1);
		else
			status = poll(&pfd, 1, timeout);

		if(status < 1) {
			if(status == -1 && errno == EINTR)
				continue;
			return false;
		}
	}

	if(pfd.revents & pfd.events)
		return true;

#else
	struct timeval tv;
	fd_set grp;
	struct timeval *tvp = &tv;

	if(timeout == TIMEOUT_INF)
		tvp = NULL;
	else {
		tv.tv_usec = (timeout % 1000) * 1000;
		tv.tv_sec = timeout / 1000;
	}

	FD_ZERO(&grp);
	FD_SET(dev, &grp);
	switch(pending) {
	case pendingInput:
		status = select(dev + 1, &grp, NULL, NULL, tvp);
		break;
	case pendingOutput:
		status = select(dev + 1, NULL, &grp, NULL, tvp);
		break;
	case pendingError:
		status = select(dev + 1, NULL, NULL, &grp, tvp);
		break;
	}
	if(status < 1)
		return false;

	if(FD_ISSET(dev, &grp))
		return true;

#endif

#endif	//	WIN32

	return false;
	}





TTYStream::TTYStream(const char *filename, timeout_t to)
	:	streambuf(),
		Serial(filename),
#ifdef	HAVE_OLD_IOSTREAM
		iostream()
#else
		iostream((streambuf *)this)
#endif
{
#ifdef	HAVE_OLD_IOSTREAM
	init((streambuf *)this);
#endif
	gbuf = pbuf = NULL;
	timeout = to;

	if(INVALID_HANDLE_VALUE != dev)
		allocate();
		}

TTYStream::TTYStream()
	:	streambuf(),
		Serial(),
#ifdef	HAVE_OLD_IOSTREAM
		iostream()
#else
		iostream((streambuf *)this)
#endif
{
#ifdef	HAVE_OLD_IOSTREAM
	init((streambuf *)this);
#endif
	timeout = 0;
	gbuf = pbuf = NULL;
			}

TTYStream::~TTYStream()
{
	endStream();
	endSerial();
			}

void TTYStream::endStream(void)
{
	if(bufsize)
		sync();

	if(gbuf) {
		delete[] gbuf;
		gbuf = NULL;
	}
	if(pbuf) {
		delete[] pbuf;
		pbuf = NULL;
	}
	bufsize = 0;
	clear();
			}

void TTYStream::allocate(void)
{
	if(INVALID_HANDLE_VALUE == dev)
		return;

#ifdef _PC_MAX_INPUT
	bufsize = fpathconf(dev, _PC_MAX_INPUT);
#else
	bufsize = MAX_INPUT;
#endif

	gbuf = new char[bufsize];
	pbuf = new char[bufsize];

	if(!pbuf || !gbuf) {
		error(errResourceFailure);
		return;
	}

	clear();

#if !(defined(STLPORT) || defined(__KCC))
	setg(gbuf, gbuf + bufsize, 0);
#endif

	setg(gbuf, gbuf + bufsize, gbuf + bufsize);
	setp(pbuf, pbuf + bufsize);
			}

int TTYStream::doallocate()
{
	if(bufsize)
		return 0;

	allocate();
	return 1;
			}

void TTYStream::interactive(bool iflag)
{
#ifdef	WIN32
	if(dev == INVALID_HANDLE_VALUE)
#else
	if(dev < 0)
#endif
		return;

	if(bufsize >= 1)
		endStream();

	if(iflag) {
		// setting to unbuffered mode

		bufsize = 1;
		gbuf = new char[bufsize];

#if !(defined(STLPORT) || defined(__KCC))
#if defined(__GNUC__) && (__GNUC__ < 3)
		setb(0,0);
#endif
#endif
		setg(gbuf, gbuf+bufsize, gbuf+bufsize);
		setp(pbuf, pbuf);
		return;
	}

	if(bufsize < 2)
		allocate();
			}

int TTYStream::uflow(void)
{
	int rlen;
	unsigned char ch;

	if(bufsize < 2) {
		if(timeout) {
			if(Serial::isPending(pendingInput, timeout))
				rlen = aRead((char *)&ch, 1);
			else
				rlen = -1;
		}
		else
			rlen = aRead((char *)&ch, 1);
		if(rlen < 1) {
			if(rlen < 0)
				clear(ios::failbit | rdstate());
			return EOF;
		}
		return ch;
	}
	else {
		ch = underflow();
		gbump(1);
		return ch;
	}
			}

int TTYStream::underflow(void)
{
	ssize_t rlen = 1;

	if(!gptr())
		return EOF;

	if(gptr() < egptr())
		return (unsigned char)*gptr();

	rlen = (ssize_t)((gbuf + bufsize) - eback());
	if(timeout && !Serial::isPending(pendingInput, timeout))
		rlen = -1;
	else
		rlen = aRead((char *)eback(), rlen);

	if(rlen < 1) {
		if(rlen < 0) {
			clear(ios::failbit | rdstate());
			error(errInput);
		}
		return EOF;
	}

	setg(eback(), eback(), eback() + rlen);
	return (unsigned char) *gptr();
			}

int TTYStream::sync(void)
{
	if(bufsize > 1 && pbase() && ((pptr() - pbase()) > 0)) {
		overflow(0);
		waitOutput();
		setp(pbuf, pbuf + bufsize);
	}
	setg(gbuf, gbuf + bufsize, gbuf + bufsize);
	return 0;
			}

int TTYStream::overflow(int c)
{
	unsigned char ch;
	ssize_t rlen, req;

	if(bufsize < 2) {
		if(c == EOF)
			return 0;

		ch = (unsigned char)(c);
		rlen = aWrite((char *)&ch, 1);
		if(rlen < 1) {
			if(rlen < 0)
				clear(ios::failbit | rdstate());
			return EOF;
		}
		else
			return c;
	}

	if(!pbase())
		return EOF;

	req = (ssize_t)(pptr() - pbase());
	if(req) {
		rlen = aWrite((char *)pbase(), req);
		if(rlen < 1) {
			if(rlen < 0)
				clear(ios::failbit | rdstate());
			return EOF;
		}
		req -= rlen;
	}

	if(req)
//		memmove(pptr(), pptr() + rlen, req);
		memmove(pbuf, pbuf + rlen, req);
	setp(pbuf + req, pbuf + bufsize);

	if(c != EOF) {
		*pptr() = (unsigned char)c;
		pbump(1);
	}
	return c;
			}

bool TTYStream::isPending(Pending pending, timeout_t timer)
{
//	if(pending == pendingInput && in_avail())
//		return true;
//	else if(pending == pendingOutput)
//		flush();

	return Serial::isPending(pending, timer);
			}






ttystream::ttystream() :
TTYStream()
{
	setError(false);
			}

ttystream::ttystream(const char *name) :
TTYStream()
{
	setError(false);
	open(name);
			}

void ttystream::close(void)
{
#ifdef	WIN32
	if (INVALID_HANDLE_VALUE == dev)
#else
	if(dev < 0)
#endif
		return;

	endStream();
	restore();
	TTYStream::close();
			}

void ttystream::open(const char *name)
{
	const char *cpp;
	char *cp;
	char pathname[256];
	size_t namelen;
	long opt;

	if (INVALID_HANDLE_VALUE != dev) {
		restore();
		close();
	}

	cpp = strrchr(name, ':');
	if(cpp)
		namelen = cpp - name;
	else
		namelen = strlen(name);

	cp = pathname;

#ifndef	WIN32
	if(*name != '/') {
		strcpy(pathname, "/dev/");
		cp += 5;
	}

	if((cp - pathname) + namelen > 255) {
		error(errResourceFailure);
		return;
	}
#endif
	setString(cp, pathname - cp + sizeof(pathname), name);
	cp += namelen;
#ifdef	WIN32
	*cp++ = ':';
#endif
	*cp = 0;

	Serial::open(pathname);

	if(INVALID_HANDLE_VALUE == dev) {
		error(errOpenFailed);
		return;
	}

	allocate();

	setString(pathname, sizeof(pathname), name + namelen);
	cp = pathname + 1;

	if(*pathname == ':')
		cp = strtok(cp, ",");
	else
		cp = NULL;

	while(cp) {
		switch(*cp) {
		case 'h':
		case 'H':
			setFlowControl(flowHard);
			break;
		case 's':
		case 'S':
			setFlowControl(flowSoft);
			break;
		case 'b':
		case 'B':
			setFlowControl(flowBoth);
			break;
		case 'n':
		case 'N':
			setParity(parityNone);
			break;
		case 'O':
		case 'o':
			setParity(parityOdd);
			break;
		case 'e':
		case 'E':
			setParity(parityEven);
			break;
		case '0':
		case '1':
		case '2':
		case '3':
		case '4':
		case '5':
		case '6':
		case '7':
		case '8':
		case '9':
			opt = atol(cp);
			if(opt == 1 || opt == 2) {
				setStopBits((int)opt);
				break;
			}
			if(opt > 4 && opt < 9) {
				setCharBits((int)opt);
				break;
			}
			setSpeed(opt);
			break;
		default:
			error(errOptionInvalid);
		}
		cp = strtok(NULL, ",");
	}
			}

TTYSession::TTYSession(const char *filename, int pri, int stack) :
Thread(pri, stack), TTYStream(filename)
{
	setError(false);
			}


TTYSession::~TTYSession()
{
	terminate();
	endSerial();
			}

#ifndef	WIN32
//	Not supporting this right now........
//

SerialPort::SerialPort(SerialService *svc, const char *name) :
Serial(name),
detect_pending(true),
detect_output(false),
detect_disconnect(true)
{
	next = prev = NULL;
	service = NULL;

#ifdef	WIN32
	if(INVALID_HANDLE_VALUE != dev)
#else
	if(dev > -1)
#endif
	{
		setError(false);
		service = svc;
		svc->attach(this);
	}
				}

SerialPort::~SerialPort()
{
	if(service)
		service->detach(this);

	endSerial();
				}

void SerialPort::expired(void)
{
				}

void SerialPort::pending(void)
{
				}

void SerialPort::disconnect(void)
{
				}

void SerialPort::output(void)
{
				}

void SerialPort::setTimer(timeout_t ptimer)
{
	TimerPort::setTimer(ptimer);
	service->update();
				}

void SerialPort::incTimer(timeout_t ptimer)
{
	TimerPort::incTimer(ptimer);
	service->update();
				}


void SerialPort::setDetectPending( bool val )
{
	if ( detect_pending != val ) {
		detect_pending = val;
#ifdef USE_POLL
		if ( ufd ) {
			if ( val ) {
				ufd->events |= POLLIN;
			} else {
				ufd->events &= ~POLLIN;
			}
		}
#endif
		service->update();
	}
				}

void SerialPort::setDetectOutput( bool val )
{
	if ( detect_output != val ) {
		detect_output = val;
#ifdef  USE_POLL
		if ( ufd ) {
			if ( val ) {
				ufd->events |= POLLOUT;
			} else {
				ufd->events &= ~POLLOUT;
			}
		}
#endif
		service->update();
	}
				}


SerialService::SerialService(int pri, size_t stack, const char *id) :
Thread(pri, stack), Mutex(id)
{
	long opt;

	first = last = NULL;
	count = 0;
	FD_ZERO(&connect);
	if(::pipe(iosync)) {
#ifdef  CCXX_EXCEPTIONS
				switch(Thread::getException()) {
				case throwObject:
						throw(this);
						return;
#ifdef  COMMON_STD_EXCEPTION
				case throwException:
						throw(ThrException("no service pipe"));
						return;
#endif
				default:
						return;
						}
#else
				return;
#endif
	}
	hiwater = iosync[0] + 1;
	FD_SET(iosync[0], &connect);

	opt = fcntl(iosync[0], F_GETFL);
	fcntl(iosync[0], F_SETFL, opt | O_NDELAY);
				}

SerialService::~SerialService()
{
	update(0);
	terminate();

	while(first)
		delete first;
				}

void SerialService::onUpdate(unsigned char flag)
{
				}

void SerialService::onEvent(void)
{
				}

void SerialService::onCallback(SerialPort *port)
{
				}

void SerialService::attach(SerialPort *port)
{
	enterMutex();
#ifdef	USE_POLL
	port->ufd = 0;
#endif
	if(last)
		last->next = port;

	port->prev = last;
	last = port;
	FD_SET(port->dev, &connect);
	if(port->dev >= hiwater)
		hiwater = port->dev + 1;

	if(!first) {
		first = port;
		leaveMutex();
		++count;
		start();
	}
	else {
		leaveMutex();
		update();
		++count;
	}
				}

void SerialService::detach(SerialPort *port)
{
	enterMutex();

#ifndef USE_POLL
	FD_CLR(port->dev, &connect);
#endif

	if(port->prev)
		port->prev->next = port->next;
	else
		first = port->next;

	if(port->next)
		port->next->prev = port->prev;
	else
		last = port->prev;

	--count;
	leaveMutex();
	update();
				}

void SerialService::update(unsigned char flag)
{
	if(::write(iosync[1], (char *)&flag, 1) < 1) {

#ifdef  CCXX_EXCEPTIONS
				switch(Thread::getException()) {
				case throwObject:
						throw(this);
						return;
#ifdef  COMMON_STD_EXCEPTION
				case throwException:
						throw(ThrException("update failed"));
						return;
#endif
				default:
						return;
						}
#else
				return;
#endif
	}
				}


void SerialService::run(void)
{
	timeout_t timer, expires;
	SerialPort *port;
	unsigned char buf;

#ifdef	USE_POLL

	Poller	mfd;
	pollfd *p_ufd;
	int lastcount = 0;

	// initialize ufd in all attached ports :
	// probably don't need this but it can't hurt.
	enterMutex();
	port = first;
	while(port) {
		port->ufd = 0;
		port = port->next;
	}
	leaveMutex();

#else
	struct timeval timeout, *tvp;
	fd_set inp, out, err;
	int dev;
	FD_ZERO(&inp);
	FD_ZERO(&out);
	FD_ZERO(&err);
#endif

	setCancel(cancelDeferred);
	for(;;) {
		timer = TIMEOUT_INF;
		while(1 == ::read(iosync[0], (char *)&buf, 1)) {
			if(buf) {
				onUpdate(buf);
				continue;
			}

			setCancel(cancelImmediate);
			sleep(TIMEOUT_INF);
			exit();
		}

#ifdef	USE_POLL

		bool	reallocate = false;

		enterMutex();
		onEvent();
		port = first;
		while(port) {
			onCallback(port);
			if ( ( p_ufd = port->ufd ) ) {

				if ( ( POLLHUP | POLLNVAL ) & p_ufd->revents ) {
					// Avoid infinite loop from disconnected sockets
					port->detect_disconnect = false;
					p_ufd->events &= ~POLLHUP;
					port->disconnect();
				}

				if ( ( POLLIN | POLLPRI ) & p_ufd->revents )
					port->pending();

				if ( POLLOUT & p_ufd->revents )
					port->output();

			} else {
				reallocate = true;
			}

retry:
			expires = port->getTimer();
			if(expires > 0)
				if(expires < timer)
					timer = expires;

			if(!expires) {
				port->endTimer();
				port->expired();
				goto retry;
			}

			port = port->next;
		}

		//
		// reallocate things if we saw a ServerPort without
		// ufd set !
		if ( reallocate || ( ( count + 1 ) != lastcount ) ) {
			lastcount = count + 1;
			p_ufd = mfd.getList( count + 1 );

			// Set up iosync polling
			p_ufd->fd = iosync[0];
			p_ufd->events = POLLIN | POLLHUP;
			p_ufd ++;

			port = first;
			while(port) {
				p_ufd->fd = port->dev;
				p_ufd->events =
					( port->detect_disconnect ? POLLHUP : 0 )
					| ( port->detect_output ? POLLOUT : 0 )
					| ( port->detect_pending ? POLLIN : 0 )
				;
				port->ufd = p_ufd;
				p_ufd ++;
				port = port->next;
			}
		}
		leaveMutex();

		poll( mfd.getList(), count + 1, timer );

#else
		enterMutex();
		onEvent();
		port = first;

		while(port) {
			onCallback(port);
			dev = port->dev;
			if(FD_ISSET(dev, &err)) {
				port->detect_disconnect = false;
				port->disconnect();
			}

			if(FD_ISSET(dev, &inp))
				port->pending();

			if(FD_ISSET(dev, &out))
				port->output();

retry:
			expires = port->getTimer();
			if(expires > 0)
				if(expires < timer)
					timer = expires;

			if(!expires) {
				port->endTimer();
				port->expired();
				goto retry;
			}

			port = port->next;
		}

		FD_ZERO(&inp);
		FD_ZERO(&out);
		FD_ZERO(&err);
		int so;
		port = first;
		while(port) {
			so = port->dev;

			if(port->detect_pending)
				FD_SET(so, &inp);

			if(port->detect_output)
				FD_SET(so, &out);

			if(port->detect_disconnect)
				FD_SET(so, &err);

			port = port->next;
		}

		leaveMutex();
		if(timer == TIMEOUT_INF)
			tvp = NULL;
		else {
			tvp = &timeout;
			timeout.tv_sec = timer / 1000;
			timeout.tv_usec = (timer % 1000) * 1000;
		}
		select(hiwater, &inp, &out, &err, tvp);
#endif
	}
				}

#endif

#ifdef	CCXX_NAMESPACES
			}
#endif

/** EMACS **
 * Local variables:
 * mode: c++
 * c-basic-offset: 8
 * End:
 */