-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArduinoCppMockSerial.cs
More file actions
116 lines (93 loc) · 3.05 KB
/
Copy pathArduinoCppMockSerial.cs
File metadata and controls
116 lines (93 loc) · 3.05 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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using NLog;
using JetBrains.Annotations;
using System;
using System.ComponentModel;
using System.IO.Ports;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
namespace ServoPIDControl.Serial
{
public sealed class ArduinoCppMockSerial : ISerialPort, INotifyPropertyChanged
{
private static readonly Logger Log = LogManager.GetCurrentClassLogger();
// ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
private readonly Action _serialCallback;
private bool _isOpen;
private bool _callBackTriggered;
private bool _disposed;
public event EventHandler Disposed;
public ArduinoCppMockSerial()
{
_serialCallback = () => _callBackTriggered = true;
NativeMethods.SetCallback(_serialCallback);
}
public void Dispose()
{
if (_disposed)
return;
Log.Info($"Disposing {nameof(ArduinoCppMockSerial)}");
_disposed = true;
NativeMethods.SetCallback(null);
Close();
Disposed?.Invoke(this, EventArgs.Empty);
}
public void Open()
{
Log.Debug("Open()");
IsOpen = true;
}
public void Close()
{
Log.Debug("Close()");
IsOpen = false;
}
public bool IsOpen
{
get => _isOpen;
private set
{
if (value == _isOpen) return;
_isOpen = value;
OnPropertyChanged();
}
}
public void SendReceivedEvents()
{
if (_callBackTriggered)
DataReceived?.Invoke(this, MockSerialPort.SerialCharsReceivedEventArgs);
_callBackTriggered = false;
}
public string ReadExisting()
{
var sb = new StringBuilder(1024);
var buf = new byte[1024];
int available;
do
{
NativeMethods.Read(buf, buf.Length, out available);
var str = Encoding.ASCII.GetString(buf, 0, Math.Min(available, buf.Length));
sb.Append(str);
} while (available > buf.Length);
return sb.ToString();
}
public void WriteLine(string s)
{
var bytes = Encoding.ASCII.GetBytes($"{s}\n");
NativeMethods.Write(bytes, bytes.Length);
}
public void Write(byte[] data, int i, int len)
{
if (i != 0)
throw new NotImplementedException("Can only handle index = 0");
NativeMethods.Write(data, len);
}
public event SerialDataReceivedEventHandler DataReceived;
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}