-
Notifications
You must be signed in to change notification settings - Fork 587
/
ArduinoGpioControllerDriver.cs
337 lines (297 loc) · 12.5 KB
/
ArduinoGpioControllerDriver.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
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Device.Gpio;
using System.Linq;
using System.Threading;
using Iot.Device.Common;
using Microsoft.Extensions.Logging;
namespace Iot.Device.Arduino
{
internal class ArduinoGpioControllerDriver : GpioDriver
{
private readonly FirmataDevice _device;
private readonly IReadOnlyCollection<SupportedPinConfiguration> _supportedPinConfigurations;
private readonly Dictionary<int, CallbackContainer> _callbackContainers;
private readonly ConcurrentDictionary<int, PinMode> _pinModes;
private readonly ConcurrentDictionary<int, PinValue> _pinValues;
private readonly object _callbackContainersLock;
private readonly AutoResetEvent _waitForEventResetEvent;
private readonly ILogger _logger;
private readonly ConcurrentDictionary<int, PinValue?> _outputPinValues;
internal ArduinoGpioControllerDriver(FirmataDevice device, IReadOnlyCollection<SupportedPinConfiguration> supportedPinConfigurations)
{
_device = device ?? throw new ArgumentNullException(nameof(device));
_supportedPinConfigurations = supportedPinConfigurations ?? throw new ArgumentNullException(nameof(supportedPinConfigurations));
_callbackContainers = new Dictionary<int, CallbackContainer>();
_waitForEventResetEvent = new AutoResetEvent(false);
_callbackContainersLock = new object();
_pinModes = new ConcurrentDictionary<int, PinMode>();
_pinValues = new ConcurrentDictionary<int, PinValue>();
_outputPinValues = new ConcurrentDictionary<int, PinValue?>();
_logger = this.GetCurrentClassLogger();
PinCount = _supportedPinConfigurations.Count;
_device.DigitalPortValueUpdated += FirmataOnDigitalPortValueUpdated;
}
protected override int PinCount { get; }
/// <summary>
/// Arduino does not distinguish between logical and physical numbers, so this always returns identity
/// </summary>
protected override int ConvertPinNumberToLogicalNumberingScheme(int pinNumber)
{
return pinNumber;
}
protected override void OpenPin(int pinNumber)
{
if (pinNumber < 0 || pinNumber >= PinCount)
{
throw new ArgumentOutOfRangeException(nameof(pinNumber), $"Pin {pinNumber} is not valid");
}
_pinValues.TryAdd(pinNumber, PinValue.Low);
}
protected override void ClosePin(int pinNumber)
{
_pinModes.TryRemove(pinNumber, out _);
_pinValues.TryRemove(pinNumber, out _);
}
protected override void SetPinMode(int pinNumber, PinMode mode)
{
SupportedMode firmataMode;
switch (mode)
{
case PinMode.Output:
firmataMode = SupportedMode.DigitalOutput;
break;
case PinMode.InputPullUp:
firmataMode = SupportedMode.InputPullup;
_outputPinValues.TryRemove(pinNumber, out _);
break;
case PinMode.Input:
firmataMode = SupportedMode.DigitalInput;
_outputPinValues.TryRemove(pinNumber, out _);
break;
default:
_logger.LogError($"Mode {mode} is not supported as argument to {nameof(SetPinMode)}");
throw new NotSupportedException($"Mode {mode} is not supported for this operation");
}
SupportedPinConfiguration? pinConfig = _supportedPinConfigurations.FirstOrDefault(x => x.Pin == pinNumber);
if (pinConfig == null || !pinConfig.PinModes.Contains(firmataMode))
{
_logger.LogError($"Mode {mode} is not supported on Pin {pinNumber}");
throw new NotSupportedException($"Mode {mode} is not supported on Pin {pinNumber}.");
}
_device.SetPinMode(pinNumber, firmataMode);
// Cache this value. Since the GpioController calls GetPinMode when trying to write a pin (to verify whether it is set to output),
// that would be very expensive here. And setting output pins should be cheap.
_pinModes[pinNumber] = mode;
}
protected override PinMode GetPinMode(int pinNumber)
{
if (_pinModes.TryGetValue(pinNumber, out PinMode existingValue))
{
return existingValue;
}
byte mode = _device.GetPinMode(pinNumber);
PinMode ret;
if (mode == SupportedMode.DigitalOutput.Value)
{
ret = PinMode.Output;
}
else if (mode == SupportedMode.DigitalInput.Value)
{
ret = PinMode.Input;
}
else if (mode == SupportedMode.InputPullup.Value)
{
ret = PinMode.InputPullUp;
}
else
{
_logger.LogError($"Unexpected pin mode found: {mode}. Is the pin not set to GPIO?");
ret = PinMode.Input;
}
_pinModes[pinNumber] = ret;
return ret;
}
protected override bool IsPinModeSupported(int pinNumber, PinMode mode)
{
SupportedMode firmataMode;
switch (mode)
{
case PinMode.Output:
firmataMode = SupportedMode.DigitalOutput;
break;
case PinMode.InputPullUp:
firmataMode = SupportedMode.InputPullup;
break;
case PinMode.Input:
firmataMode = SupportedMode.DigitalInput;
break;
default:
return false;
}
SupportedPinConfiguration? pinConfig = _supportedPinConfigurations.FirstOrDefault(x => x.Pin == pinNumber);
return pinConfig != null && pinConfig.PinModes.Contains(firmataMode);
}
protected override PinValue Read(int pinNumber)
{
_pinValues[pinNumber] = _device.ReadDigitalPin(pinNumber);
return _pinValues[pinNumber];
}
protected override void Toggle(int pinNumber) => Write(pinNumber, !_pinValues[pinNumber]);
protected override void Write(int pinNumber, PinValue value)
{
if (_outputPinValues.TryGetValue(pinNumber, out PinValue? existingValue) && existingValue != null)
{
// If this output value is already present, don't send a message.
if (value == existingValue.Value)
{
return;
}
}
_device.WriteDigitalPin(pinNumber, value);
_outputPinValues.AddOrUpdate(pinNumber, x => value, (y, z) => value);
_pinValues[pinNumber] = value;
}
protected override WaitForEventResult WaitForEvent(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken)
{
PinEventTypes eventSeen = PinEventTypes.None;
void WaitForEventPortValueUpdated(object sender, PinValueChangedEventArgs e)
{
if (e.PinNumber == pinNumber)
{
if ((eventTypes & PinEventTypes.Rising) == PinEventTypes.Rising && e.ChangeType == PinEventTypes.Rising)
{
eventSeen = PinEventTypes.Rising;
_waitForEventResetEvent.Set();
}
else if ((eventTypes & PinEventTypes.Falling) == PinEventTypes.Falling && e.ChangeType == PinEventTypes.Falling)
{
eventSeen = PinEventTypes.Falling;
_waitForEventResetEvent.Set();
}
}
}
_device.DigitalPortValueUpdated += WaitForEventPortValueUpdated;
try
{
WaitHandle.WaitAny(new[] { cancellationToken.WaitHandle, _waitForEventResetEvent });
if (cancellationToken.IsCancellationRequested)
{
return new WaitForEventResult()
{
EventTypes = PinEventTypes.None,
TimedOut = true
};
}
}
finally
{
_device.DigitalPortValueUpdated -= WaitForEventPortValueUpdated;
}
return new WaitForEventResult()
{
EventTypes = eventSeen,
TimedOut = false
};
}
protected override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEventTypes eventTypes, PinChangeEventHandler callback)
{
lock (_callbackContainersLock)
{
if (_callbackContainers.TryGetValue(pinNumber, out CallbackContainer? cb))
{
cb.EventTypes = cb.EventTypes | eventTypes;
cb.OnPinChanged += callback;
}
else
{
CallbackContainer cb2 = new CallbackContainer(pinNumber, eventTypes);
cb2.OnPinChanged += callback;
_callbackContainers.Add(pinNumber, cb2);
}
}
}
protected override void RemoveCallbackForPinValueChangedEvent(int pinNumber, PinChangeEventHandler callback)
{
lock (_callbackContainersLock)
{
if (_callbackContainers.TryGetValue(pinNumber, out CallbackContainer? cb))
{
cb.OnPinChanged -= callback;
if (cb.NoEventsConnected)
{
_callbackContainers.Remove(pinNumber);
}
}
}
}
private void FirmataOnDigitalPortValueUpdated(object sender, PinValueChangedEventArgs e)
{
CallbackContainer? cb = null;
PinEventTypes eventTypeToFire = PinEventTypes.None;
lock (_callbackContainersLock)
{
if (_callbackContainers.TryGetValue(e.PinNumber, out cb))
{
if (e.ChangeType == PinEventTypes.Rising && cb.EventTypes.HasFlag(PinEventTypes.Rising))
{
eventTypeToFire = PinEventTypes.Rising;
}
else if (e.ChangeType == PinEventTypes.Falling && cb.EventTypes.HasFlag(PinEventTypes.Falling))
{
eventTypeToFire = PinEventTypes.Falling;
}
}
}
if (eventTypeToFire != PinEventTypes.None && cb != null)
{
cb.FireOnPinChanged(eventTypeToFire);
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
lock (_callbackContainersLock)
{
_callbackContainers.Clear();
}
_pinValues.Clear();
_outputPinValues.Clear();
_device.DigitalPortValueUpdated -= FirmataOnDigitalPortValueUpdated;
}
base.Dispose(disposing);
}
private class CallbackContainer
{
public CallbackContainer(int pinNumber, PinEventTypes eventTypes)
{
PinNumber = pinNumber;
EventTypes = eventTypes;
}
public event PinChangeEventHandler? OnPinChanged;
public int PinNumber { get; }
public PinEventTypes EventTypes
{
get;
set;
}
public bool NoEventsConnected
{
get
{
return OnPinChanged == null;
}
}
public void FireOnPinChanged(PinEventTypes eventType)
{
// Copy event instance, prevents problems when elements are added or removed at the same time
PinChangeEventHandler? threadSafeCopy = OnPinChanged;
threadSafeCopy?.Invoke(PinNumber, new PinValueChangedEventArgs(eventType, PinNumber));
}
}
}
}