-
Notifications
You must be signed in to change notification settings - Fork 2
/
serial.d
executable file
·916 lines (741 loc) · 19.8 KB
/
serial.d
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
/**
* Serial port library
*
* Copyright: © 2014-2021
* License: MIT license. License terms written in licence.txt file
*
* Authors: Oleg Nykytenko, onyx.itdevelopment@gmail.com
*
* Version: 0.xx Date: 2014
*/
module onyx.serial;
import onyx.bundle;
import std.string;
import std.conv;
import core.thread;
import std.stdio:StdioException;
/**
* Base Serial port exception
*/
abstract class SerialPortException: StdioException
{
private string _port;
string port() {return _port;}
this(string port, string msg)
{
super(msg);
}
}
/**
* Construct exception with parrent: SerialPortException
*/
template childSerialPortException(string exceptionName)
{
const char[] childSerialPortException =
"class " ~exceptionName~":SerialPortException
{
this(string port, string msg)
{
super(port, msg);
}
}";
}
/**
* Realize child Exceptions
*/
mixin(childSerialPortException!"SerialPortSetupException");
mixin(childSerialPortException!"SerialPortOpenException");
mixin(childSerialPortException!"SerialPortCloseException");
mixin(childSerialPortException!"SerialPortIOException");
mixin(childSerialPortException!"SerialPortTimeOutException");
template getterImplMember(string type, string name)
{
const char[] getterImplMember =
type ~ " " ~ name ~ "()
{
return impl." ~ name ~ ";
}";
}
mixin (genSpeed);
/**
* Serial port.
*
* Hardware independent level
*/
struct OxSerialPort
{
/**
* Low level Serial port implementation
*/
private Impl impl;
mixin(getterImplMember!("string", "name"));
/**
* Create new serial port
*/
pure
nothrow
this(string portName, Speed speed = Speed.S9600, Parity parity = Parity.none, uint timeOut = 0)
{
impl = Impl(portName, speed, parity, timeOut);
}
/**
* Create new serial port
*
* Throws: SerialPortSetupException
*/
deprecated
this(string portName, uint speed = 9600, string parity = "none", uint timeOut = 0)
{
impl = Impl(portName, speed, parity, timeOut);
}
/**
* Create new serial port
*
* Throws: SerialPortSetupException
* Throws: ValueNotFoundException, GlKeyNotFoundException, BundleException
* Throws: ConvException, ConvOverflowException
*/
this(immutable Bundle bundle)
{
string extractName()
{
string name;
try
{
name = bundle.value("port", "name");
}
catch(KeyNotFoundException ke)
{
throw new BundleException("Not found port name: " ~ke.msg);
}
return name;
}
uint extractSpeed()
{
uint portSpeed;
try
{
portSpeed = bundle.value!uint("port", "speed");
}
catch(KeyNotFoundException ke)
{
portSpeed = 9600;
}
return portSpeed;
}
string extractParity()
{
string parity;
try
{
parity = bundle.value("port", "parity");
}
catch(KeyNotFoundException ke)
{
parity = "none";
}
return parity;
}
uint extractTimeOut()
{
uint portTimeOut;
try
{
portTimeOut = bundle.value!uint("port", "time_out");
}
catch(KeyNotFoundException ke)
{
portTimeOut = 0;
}
return portTimeOut;
}
impl = Impl(extractName, extractSpeed, extractParity, extractTimeOut);
}
~this()
{
close();
}
/**
* Open serial port (and setup)
*
* Return true if port opened
*
* Throws: SerialPortOpenException, SerialPortSetupException
*/
bool open()
{
scope(failure) close();
if (!impl.isOpen())
{
impl.open();
impl.setup();
}
else
{
throw new SerialPortOpenException(impl.name, " Port already opened");
}
return impl.isOpen();
}
/**
* Close serial port
*
* Return true if port closed
*
* Throws: SerialPortCloseException
*/
bool close()
{
if (impl.isOpen())
{
impl.close();
}
return !impl.isOpen();
}
/**
* write data to port
*
* Throws: SerialPortIOException
*/
void write(ubyte[] buf)
{
impl.write(buf);
}
/**
* read data from port
*
* Throws: SerialPortIOException, SerialPortTimeOutException
*/
ubyte[] read(int byteCount, ReadMode readMode = ReadMode.waitForTimeout)
{
return impl.read(byteCount, readMode);
}
/**
* read data from port
*
* Throws: SerialPortIOException, SerialPortTimeOutException
*/
deprecated("Please use read(int, ReadMode) instead")
ubyte[] read(int byteCount, bool wait)
{
return impl.read(byteCount, wait ? ReadMode.waitForTimeout : ReadMode.noWait);
}
/**
* Check if port open
*
* Return true if port open
*
*/
bool isOpen() nothrow
{
return impl.isOpen();
}
}
/**
* Parity variants
*
*/
enum Parity:string
{
none = "none",
odd = "odd",
even = "even",
//mark = "mark",
//space = "space",
error = "error"
}
/**
* Generation Speed type
*
* Use example: Speed.s57600
*/
const (char[]) genSpeed()
{
const (char)[] res = "enum Speed:uint {";
foreach (speed; speedsRange)
{
res = res ~ 'S' ~ speed ~ " = " ~ speed ~ ", ";
}
res ~= '}';
return res;
}
/**
* Speed variants
*
*/
version (linux)
{
const char[][] speedsRange = ["0", "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400",
"4800", "9600", "19200", "38400", "57600", "115200", "230400", "460800", "500000", "576000", "921600",
"1000000", "1152000", "1500000", "2000000", "2500000", "3000000", "3500000", "4000000"];
}
else version (OSX)
{
const char[][] speedsRange = ["0", "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400",
"4800", "9600", "19200", "38400", "7200", "14400", "28800", "57600", "76800", "115200", "230400"];
}
else version (FreeBSD)
{
const char[][] speedsRange = ["0", "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400",
"4800", "9600", "19200", "38400", "7200", "14400", "28800", "57600", "76800", "115200", "230400", "460800", "921600"];
}
else version (Solaris)
{
const char[][] speedsRange = ["0", "50", "75", "110", "134", "150", "200", "300", "600", "1200", "1800", "2400",
"4800", "9600", "19200", "38400", "57600", "76800", "115200", "153600", "230400", "307200", "460800", "921600"];
}
/**
* Variants for the read method
*/
enum ReadMode
{
noWait,
waitForTimeout,
waitForData,
waitForAllData
}
version(Posix)
{
alias Impl = PosixImpl;
}
private struct PosixImpl
{
import core.sys.posix.termios;
import core.sys.posix.fcntl;
import core.sys.posix.poll;
alias int Handle;
private Handle handle = -1;
/**
* Port name.
* For posix systems as rule: /dev/tty*
*/
private string _name;
string name() pure nothrow
{
return _name;
}
/**
* Port speed.
* Must be from standard row: 0, 50, 75 .. 4_000_000
*/
private Speed _speed;
Speed speed() pure nothrow
{
return _speed;
}
/**
* Port parity.
* Must be from: "none, odd, even, mark, space"
*/
private Parity _parity;
Parity parity() pure nothrow
{
return _parity;
}
/**
* Port data read timeout.
* in msecs
*/
private uint _readTimeOut;
@property
uint readTimeOut() pure nothrow
{
return _readTimeOut;
}
/**
* Create serial port implementation
*/
this(string name, Speed speed, Parity parity, uint timeOut) pure nothrow
{
_name = name;
_speed = speed;
_parity = parity;
_readTimeOut = timeOut;
}
/**
* Create serial port implementation
*
* Throws: SerialPortSetupException
*/
this(string name, uint speed, string parity, uint timeOut)
{
_name = name;
if (checkSpeed(speed))
{
_speed = getSpeedByNum(speed);
}
else
{
throw new SerialPortSetupException(name, "Invalid speed value: " ~ to!string(speed));
}
if (checkParity(parity))
{
_parity = getParityByName(parity);
}
else
{
throw new SerialPortSetupException(name, "Invalid parity value: " ~ parity);
}
_readTimeOut = timeOut;
}
/**
* Open serial port
*
* Throws: SerialPortOpenException
*/
void open()
{
Handle h = core.sys.posix.fcntl.open(name.toStringz, O_RDWR | O_NOCTTY | O_NONBLOCK);
if (h != -1)
{
handle = h;
}
else
{
throw new SerialPortOpenException(name, "Can't open serial port");
}
}
/**
* Close serial port
*
* Throws: SerialPortCloseException
*/
void close()
{
static import core.sys.posix.unistd;
if (core.sys.posix.unistd.close(handle) == -1)
{
throw new SerialPortCloseException(name, "Can't close serial port");
}
handle = -1;
}
/**
* Setup serial port parameters
*
* Throws: SerialPortSetupException
*/
void setup()
{
/* set flags */
setFlags();
/* set speed */
setSpeed();
setParity();
}
/**
* Set port speed
*
* Throws: SerialPortSetupException
*/
private void setSpeed()
{
auto set = getTermios();
speed_t baud = getBaudRateByNum(speed);
if((cfsetispeed(&set, baud) < 0) || (cfsetospeed(&set, baud) < 0) || (tcsetattr(handle, TCSANOW, &set) == -1))
{
throw new SerialPortSetupException(name, "Can't set speed " ~ to!string(speed) ~ " for serial port");
}
}
/**
* Set port speed
*
* Throws: SerialPortSetupException
*/
private void setParity()
{
auto set = getTermios();
/* clear parity bits */
set.c_cflag &= ~(PARENB | PARODD);
set.c_iflag &= ~INPCK;
auto par = getParityByName(parity);
final switch(par)
{
case Parity.odd:
set.c_cflag |= (PARENB | PARODD);
set.c_iflag |= INPCK;
break;
case Parity.even:
set.c_cflag |= PARENB;
set.c_iflag |= INPCK;
break;
case Parity.none:
break;
case Parity.error:
}
if (tcsetattr(handle, TCSANOW, &set) == -1)
{
throw new SerialPortSetupException(name, "Can't set parity " ~ par ~ " for serial port");
}
}
/**
* Set port flags
*
* Throws: SerialPortSetupException
*/
private void setFlags()
{
auto set = getTermios();
/* set flags */
set.c_cflag |= (CREAD | CLOCAL);
set.c_cflag &= ~CRTSCTS;
set.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOCTL | ECHOPRT | ECHOKE | ISIG | IEXTEN);
set.c_iflag &= ~(IXON | IXOFF | IXANY | IGNPAR | PARMRK | ISTRIP | IGNBRK | BRKINT | INLCR | IGNCR| ICRNL);
set.c_oflag &= ~OPOST;
/* Minimum number of characters as 0 and we don't want to use any timer */
set.c_cc[VMIN] = 0;
set.c_cc[VTIME] = 0;
if (tcsetattr(handle, TCSANOW, &set) == -1)
{
throw new SerialPortSetupException(name, "Can't save setup for serial port");
}
}
/**
* get termios structure
*
* Throws: SerialPortSetupException
*/
private termios getTermios()
{
termios set;
if (tcgetattr(handle, &set) < 0)
{
throw new SerialPortSetupException(name, "Can't setup serial port");
}
return set;
}
/**
* open port check
*/
bool isOpen() nothrow//@safe pure nothrow
{
return (handle > 0)?true:false;
}
/**
* write data to port
*
* Throws: SerialPortIOException
*/
void write(ubyte[] buf)
{
static import core.sys.posix.unistd;
if (core.sys.posix.unistd.write(handle, cast(void *)buf.ptr, buf.length) == -1)
{
throw new SerialPortIOException(name, "Error Writing to serial port");
}
}
/**
* read data from port
*
* Throws: SerialPortIOException, SerialPortTimeOutException
*/
ubyte[] read(uint byteCount, ReadMode readMode)
{
ubyte[] data = new ubyte[byteCount];
size_t byteRemains = byteCount;
enum timeOutTickMax = 10; // msecs
auto timeOutTick = cast(int)((readTimeOut >= timeOutTickMax)?timeOutTickMax:readTimeOut);
/* start time in hnsecs */
import std.datetime;
auto startTime = Clock.currStdTime();
do
{
pollfd pfd = pollfd(handle, POLLIN, 0);
int rc = poll(&pfd, 1, timeOutTick);
if ((rc > 0) && (pfd.revents & POLLIN))
{
static import core.sys.posix.unistd;
ssize_t chanck = core.sys.posix.unistd.read(handle, cast(void*)(data.ptr + byteCount - byteRemains), byteRemains);
if (chanck == -1)
{
throw new SerialPortIOException(name, "Error reading from serial port");
}
byteRemains -= chanck;
}
if (byteRemains > 0)
{
Thread.sleep( dur!("msecs")(timeOutTick));
}
else
{
break;
}
}
while( readMode == ReadMode.waitForTimeout && (readTimeOut > (Clock.currStdTime() - startTime)/(1000*10)) ||
readMode == ReadMode.waitForAllData ||
readMode == ReadMode.waitForData && byteRemains == byteCount);
if (byteRemains == byteCount)
throw new SerialPortTimeOutException(name, "Port data read timeout. ");
data = data[0..(byteCount-byteRemains)];
return data;
}
bool checkParity(string parity) nothrow pure
{
return (getParityByName(parity) != Parity.error)?true:false;
}
Parity getParityByName(string strParity) nothrow pure
{
switch(strParity)
{
case Parity.none:
return Parity.none;
case Parity.odd:
return Parity.odd;
case Parity.even:
return Parity.even;
//case Parity.mark:
// return Parity.mark;
//case Parity.space:
// return Parity.space;
default:
return Parity.error;
}
}
bool checkSpeed(uint speed) nothrow pure
{
return (getBaudRateByNum(speed) != -1)?true:false;
}
static const (char[]) genGetSpeedByNumBody()
{
const (char)[] res = "switch(speedNum) {";
foreach (speed; speedsRange)
{
res = res ~ "case " ~ speed ~ ": return Speed.S" ~ speed ~ "; \n";
}
res ~= "default: return Speed.S0;";
res ~= '}';
return res;
}
/**
* Convert speed number to Speed
*/
Speed getSpeedByNum(uint speedNum) nothrow pure
{
mixin (genGetSpeedByNumBody);
}
static const (char[]) genGetBaudRateByNumBody()
{
const (char)[] res = "switch(speedNum) {";
foreach (speed; speedsRange)
{
res = res ~ "case " ~ speed ~ ": return B" ~ speed ~ "; \n";
}
res ~= "default: return -1;";
res ~= '}';
return res;
}
speed_t getBaudRateByNum(uint speedNum) nothrow pure
{
mixin (genGetBaudRateByNumBody);
}
version(linux)
{
enum B57600 = 0x1001;
enum B115200 = 0x1002;
enum B230400 = 0x1003;
enum B460800 = 0x1004;
enum B500000 = 0x1005;
enum B576000 = 0x1006;
enum B921600 = 0x1007;
enum B1000000 = 0x1008;
enum B1152000 = 0x1009;
enum B1500000 = 0x100A;
enum B2000000 = 0x100B;
enum B2500000 = 0x100C;
enum B3000000 = 0x100D;
enum B3500000 = 0x100E;
enum B4000000 = 0x100F;
enum CRTSCTS = 0x80000000;
enum ECHOCTL = 0x200;
enum ECHOPRT = 0x400;
enum ECHOKE = 0x800;
}
else version (OSX)
{
enum B7200 = 7200;
enum B14400 = 14400;
enum B28800 = 28800;
enum B57600 = 57600;
enum B76800 = 76800;
enum B115200 = 115200;
enum B230400 = 230400;
enum CCTS_OFLOW = 0x00010000; /* CTS flow control of output */
enum CRTS_IFLOW = 0x00020000; /* RTS flow control of input */
enum CRTSCTS = (CCTS_OFLOW | CRTS_IFLOW);
enum ECHOKE = 0x00000001; /* visual erase for line kill */
enum ECHOPRT = 0x00000020; /* visual erase mode for hardcopy */
enum ECHOCTL = 0x00000040; /* echo control chars as ^(Char) */
}
else version (FreeBSD)
{
enum B7200 = 7200;
enum B14400 = 14400;
enum B28800 = 28800;
enum B57600 = 57600;
enum B76800 = 76800;
enum B115200 = 115200;
enum B230400 = 230400;
enum B460800 = 460800;
enum B921600 = 921600;
enum CCTS_OFLOW = 0x00010000; /* CTS flow control of output */
enum CRTS_IFLOW = 0x00020000; /* RTS flow control of input */
enum CRTSCTS = (CCTS_OFLOW | CRTS_IFLOW);
enum ECHOKE = 0x00000001; /* visual erase for line kill */
enum ECHOPRT = 0x00000020; /* visual erase mode for hardcopy */
enum ECHOCTL = 0x00000040; /* echo control chars as ^(Char) */
}
else version (Solaris)
{
//enum CRTSCTS = 0x10000000;
//enum ECHOCTL = 0x200;
//enum ECHOPRT = 0x400;
//enum ECHOKE = 0x800;
}
}
version (vOnyxSerialTest)
{
import std.stdio;
import std.conv;
unittest
{
{
string[] s1 =
["[port]",
"name = /dev/ttyS0",
"speed = 57600",
"data_bits = 8",
"stop_bits = 1",
"parity = none",
"set_RTS = no",
"set_DTR = no",
"time_out = 1500"];
string[] s2 =
["[port]",
"name = /dev/ttyr07",
"speed = 57600",
"data_bits = 8",
"stop_bits = 1",
"parity = none",
"set_RTS = no",
"set_DTR = no",
"time_out = 1500"];
auto port1 = new OxSerialPort(new immutable Bundle(s1));
//auto port2 = new OxSerialPort(new immutable Bundle(s2));
port1.open();
//port2.open();
ubyte[] data = [0x22, 0x33, 0xCC];
port1.write(data);
//ubyte[] buf = port2.read(3);
//assert (buf == data);
port1.close();
//port2.close();
}
{
//import std.stdio;
//writeln(sp);
auto port1 = new OxSerialPort("/dev/ttyS0", Speed.S9600, Parity.none, 1000);
port1.open;
ubyte[] data = [0x22, 0x33, 0xCC];
port1.write(data);
port1.close;
}
}
}