-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathArduino.cs
More file actions
101 lines (86 loc) · 1.78 KB
/
Copy pathArduino.cs
File metadata and controls
101 lines (86 loc) · 1.78 KB
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
using System.IO.Ports;
namespace MarvinsAIRA
{
public class Arduino( byte[] handshake )
{
private readonly SerialPort? _serialPort = ConnectPort( handshake );
public SerialPort? SerialPort { get => _serialPort; }
public void Close()
{
if ( _serialPort != null )
{
if ( _serialPort.IsOpen )
{
_serialPort.Close();
}
}
}
public void SendMessage( string message )
{
if ( _serialPort != null )
{
if ( _serialPort.IsOpen )
{
_serialPort.Write( message );
}
}
}
private static SerialPort? ConnectPort( byte[] handshake )
{
foreach ( var portName in SerialPort.GetPortNames() )
{
var serialPort = new SerialPort( portName );
if ( !serialPort.IsOpen )
{
try
{
serialPort.BaudRate = 9600;
serialPort.WriteTimeout = 500;
serialPort.ReadTimeout = 500;
serialPort.Open();
serialPort.Write( handshake, 0, handshake.Length );
var response = new byte[ handshake.Length ];
var count = 0;
var timedOut = false;
while ( count < handshake.Length )
{
try
{
count += serialPort.Read( response, count, response.Length - count );
}
catch ( TimeoutException )
{
timedOut = true;
break;
}
}
if ( !timedOut && ( count == handshake.Length ) )
{
var handshakeMatches = true;
for ( var i = 0; i < response.Length; i++ )
{
if ( response[ i ] != handshake[ i ] )
{
handshakeMatches = false;
break;
}
}
if ( handshakeMatches )
{
return serialPort;
}
}
}
catch
{
}
if ( serialPort.IsOpen )
{
serialPort.Close();
}
}
}
return null;
}
}
}