1 module serial_integration_test;
2 
3 version(unittest)
4 {
5     import serial.device;
6     import std.stdio;
7     import std.getopt;
8     import std.math;
9     import std.process;
10     import core.time;
11     import core.thread;
12     
13     void main(string[] args)
14     {
15         auto ports = SerialPort.ports;
16         writeln("You have ", ports.length, " available com ports: ", ports);
17 
18         string portName1;
19         string portName2;
20         getopt(args, 
21         	"port1", &portName1,
22         	"port2", &portName2);
23         
24         version(linux)
25         {
26             Pid sockatPid;
27             if(portName1 == "" || portName2 == "")
28             {
29                 if(portName1 == "" || portName2 == "")
30                 {
31         	        sockatPid = spawnShell("socat PTY,link=ttyS1 PTY,link=ttyS2");
32                 }
33                 portName1 = "ttyS1";
34                 portName2 = "ttyS2";
35             }
36             scope(exit) kill(sockatPid);
37             Thread.sleep(dur!"msecs"(500));
38         } else
39         {
40             if(portName1 == "" || portName2 == "")
41             {
42                 writeln("Please specify testing ports as --port1=<port name> --port2=<port name>");
43                 return;
44             }
45         }
46         
47         auto com1 = new SerialPort(portName1, dur!"seconds"(1), dur!"seconds"(1));
48         auto com2 = new SerialPort(portName2, dur!"seconds"(1), dur!"seconds"(1));
49         scope(exit)
50         {
51             com1.close();
52             com2.close();
53         }
54         
55         writeln("Testing first port available baud rates:");
56         writeln(com1.getBaudRates);
57 
58         writeln("Testing second port available baud rates:");
59         writeln(com2.getBaudRates); 
60 
61         writeln("Testing low-level read-write:");
62         string hello = "Hello, World!";
63         com1.write(cast(void[])hello);
64 
65         ubyte[13] buff;
66         size_t readed = com2.read(buff);
67         string recievedString = cast(string)(buff[0..readed]).idup;
68         assert(recievedString == hello, "Recieved string: "~recievedString);
69         writeln(recievedString);
70         
71         writeln("Testing read timeout:");
72         bool failed = false;
73         auto t = TickDuration.currSystemTick;
74         try 
75         {
76             readed = com2.read(buff);
77         }
78         catch(TimeoutException e) 
79         {
80             assert(approxEqual(t.msecs, TickDuration.currSystemTick.msecs));
81             failed = true;
82         } 
83         assert(failed);
84         writeln("success!");
85     }
86 }