-
Notifications
You must be signed in to change notification settings - Fork 85
/
SerialMonitor.cs
executable file
·95 lines (80 loc) · 3.15 KB
/
SerialMonitor.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Ports;
using System.Windows.Threading;
namespace NintendoSpy
{
public delegate void PacketEventHandler (object sender, byte[] packet);
public class SerialMonitor
{
const int BAUD_RATE = 115200;
const int TIMER_MS = 30;
public event PacketEventHandler PacketReceived;
public event EventHandler Disconnected;
SerialPort _datPort;
List <byte> _localBuffer;
DispatcherTimer _timer;
public SerialMonitor (string portName)
{
_localBuffer = new List <byte> ();
_datPort = new SerialPort (portName, BAUD_RATE);
_datPort.Handshake = Handshake.RequestToSend;
_datPort.DtrEnable = true;
}
public void Start ()
{
if (_timer != null) return;
_localBuffer.Clear ();
_datPort.Open ();
_timer = new DispatcherTimer ();
_timer.Interval = TimeSpan.FromMilliseconds (TIMER_MS);
_timer.Tick += tick;
_timer.Start ();
}
public void Stop ()
{
if (_datPort != null) {
try { // If the device has been unplugged, Close will throw an IOException. This is fine, we'll just keep cleaning up.
_datPort.Close ();
}
catch (IOException) {}
_datPort = null;
}
if (_timer != null) {
_timer.Stop ();
_timer = null;
}
}
void tick (object sender, EventArgs e)
{
if (_datPort == null || !_datPort.IsOpen || PacketReceived == null) return;
// Try to read some data from the COM port and append it to our localBuffer.
// If there's an IOException then the device has been disconnected.
try {
int readCount = _datPort.BytesToRead;
if (readCount < 1) return;
byte[] readBuffer = new byte [readCount];
_datPort.Read (readBuffer, 0, readCount);
_datPort.DiscardInBuffer ();
_localBuffer.AddRange (readBuffer);
}
catch (IOException) {
Stop ();
if (Disconnected != null) Disconnected (this, EventArgs.Empty);
return;
}
// Try and find 2 splitting characters in our buffer.
int lastSplitIndex = _localBuffer.LastIndexOf (0x0A);
if (lastSplitIndex <= 1) return;
int sndLastSplitIndex = _localBuffer.LastIndexOf (0x0A, lastSplitIndex - 1);
if (lastSplitIndex == -1) return;
// Grab the latest packet out of the buffer and fire it off to the receive event listeners.
int packetStart = sndLastSplitIndex + 1;
int packetSize = lastSplitIndex - packetStart;
PacketReceived (this, _localBuffer.GetRange (packetStart, packetSize).ToArray ());
// Clear our buffer up until the last split character.
_localBuffer.RemoveRange (0, lastSplitIndex);
}
}
}