-
Notifications
You must be signed in to change notification settings - Fork 586
/
KeyboardGpioDriver.cs
376 lines (331 loc) · 11.7 KB
/
KeyboardGpioDriver.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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
// 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.Generic;
using System.Device.Gpio;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
namespace Iot.Device.Board
{
/// <summary>
/// A GPIO Driver for testing on Windows
/// This driver uses the keyboard for simulating GPIO pins.
/// Pins 0-2 are output only and represent the keyboard LEDs (Caps lock, Scroll Lock and Num Lock).
/// Setting a value to any of these pins toggles the LEDs on the keyboard (if they're physically present).
/// Pins above 8 are input only and represent the keyboard keys. To get the pin number,
/// cast the corresponding <see cref="ConsoleKey"/> to int, e.g. int pinNumber = (int)ConsoleKey.A
/// </summary>
public class KeyboardGpioDriver : GpioDriver
{
private enum LedKey
{
NumLock,
CapsLock,
ScrollLock,
}
private const int SupportedPinCount = 256;
private readonly Dictionary<int, PinValue> _pinValues = new Dictionary<int, PinValue>();
private KeyState[] _state;
private Thread? _pollThread;
private bool _terminateThread;
/// <summary>
/// Creates an instance of the KeyboardGpioDriver
/// </summary>
public KeyboardGpioDriver()
{
_state = new KeyState[SupportedPinCount];
for (int i = 0; i < SupportedPinCount; i++)
{
_state[i] = new KeyState((ConsoleKey)i, i);
}
_pollThread = null;
_terminateThread = true;
foreach (var key in Enum.GetValues(typeof(LedKey)))
{
_pinValues.Add((int)key!, GetLedState((LedKey)key).KeyValue);
}
}
/// <inheritdoc />
protected override int PinCount
{
get
{
// The ConsoleKey enum is used to index into our pins, if needed. This one does not use values below 8, so
// we'll use 3 for the LEDs.
return SupportedPinCount;
}
}
/// <inheritdoc />
protected override int ConvertPinNumberToLogicalNumberingScheme(int pinNumber)
{
return pinNumber;
}
/// <inheritdoc />
protected override void OpenPin(int pinNumber)
{
}
/// <inheritdoc />
protected override void ClosePin(int pinNumber)
{
}
/// <inheritdoc />
protected override void SetPinMode(int pinNumber, PinMode mode)
{
if (IsPinModeSupported(pinNumber, mode))
{
_state[pinNumber].Mode = mode;
}
else
{
throw new NotSupportedException($"Pin {pinNumber} does not support mode {mode}");
}
}
/// <inheritdoc />
protected override PinMode GetPinMode(int pinNumber)
{
return _state[pinNumber].Mode;
}
/// <inheritdoc />
protected override bool IsPinModeSupported(int pinNumber, PinMode mode)
{
if (pinNumber < 3)
{
// Output-only pins (the three LEDs on the keyboard)
if (mode == PinMode.Output)
{
return true;
}
return false;
}
if (pinNumber >= 8)
{
if (mode == PinMode.Input || mode == PinMode.InputPullDown || mode == PinMode.InputPullUp)
{
return true;
}
}
return false;
}
private bool IsKeyPressed(ConsoleKey key)
{
short state = Interop.GetKeyState((int)key);
return (state & 0xFFFE) != 0; // any bits except the lowest
}
private void SetLedState(LedKey key, PinValue state)
{
(int virtualKey, int currentKeyState) = GetLedState(key);
_pinValues[(int)key] = state;
if ((state == PinValue.High && currentKeyState == 0) ||
(state == PinValue.Low && currentKeyState != 0))
{
// Simulate a key press
Interop.keybd_event((byte)virtualKey,
0x45,
Interop.KEYEVENTF_EXTENDEDKEY,
IntPtr.Zero);
// Simulate a key release
Interop.keybd_event((byte)virtualKey,
0x45,
Interop.KEYEVENTF_EXTENDEDKEY | Interop.KEYEVENTF_KEYUP,
IntPtr.Zero);
}
}
private (int VirtualKey, int KeyValue) GetLedState(LedKey key)
{
int virtualKey = 0;
if (key == LedKey.NumLock)
{
virtualKey = Interop.VK_NUMLOCK;
}
else if (key == LedKey.CapsLock)
{
virtualKey = Interop.VK_CAPITAL;
}
else if (key == LedKey.ScrollLock)
{
virtualKey = Interop.VK_SCROLL;
}
else
{
throw new NotSupportedException("No such key");
}
// Bit 1 indicates whether the LED is currently on or off (or, whether Scroll lock, num lock, caps lock is on)
return (virtualKey, Interop.GetKeyState(virtualKey) & 1);
}
/// <inheritdoc />
protected override PinValue Read(int pinNumber)
{
short currentKeyState = Interop.GetAsyncKeyState(pinNumber);
if ((currentKeyState & 0xFFFE) != 0)
{
return PinValue.High;
}
else
{
return PinValue.Low;
}
}
/// <inheritdoc />
protected override void Toggle(int pinNumber) => Write(pinNumber, !_pinValues[pinNumber]);
/// <inheritdoc />
protected override void Write(int pinNumber, PinValue value)
{
if (pinNumber == 0)
{
SetLedState(LedKey.NumLock, value);
}
if (pinNumber == 1)
{
SetLedState(LedKey.ScrollLock, value);
}
if (pinNumber == 2)
{
SetLedState(LedKey.CapsLock, value);
}
}
/// <inheritdoc />
protected override WaitForEventResult WaitForEvent(int pinNumber, PinEventTypes eventTypes, CancellationToken cancellationToken)
{
PinValue oldState = Read(pinNumber);
while (!cancellationToken.IsCancellationRequested)
{
PinValue newState = Read(pinNumber);
if (oldState != newState)
{
if (eventTypes == PinEventTypes.Rising && newState == PinValue.High)
{
return new WaitForEventResult()
{
EventTypes = PinEventTypes.Rising,
TimedOut = false
};
}
else if (eventTypes == PinEventTypes.Falling && newState == PinValue.Low)
{
return new WaitForEventResult()
{
EventTypes = PinEventTypes.Falling,
TimedOut = false
};
}
else
{
return new WaitForEventResult()
{
EventTypes = newState == PinValue.High ? PinEventTypes.Rising : PinEventTypes.Falling,
TimedOut = false
};
}
}
}
return new WaitForEventResult()
{
TimedOut = true
};
}
/// <inheritdoc />
protected override void AddCallbackForPinValueChangedEvent(int pinNumber, PinEventTypes eventTypes, PinChangeEventHandler callback)
{
lock (_state)
{
if (_pollThread == null)
{
_terminateThread = false;
_pollThread = new Thread(PollingKeyThread);
_pollThread.IsBackground = true;
_pollThread.Start();
}
_state[pinNumber].State = Read(pinNumber);
_state[pinNumber].EventModes = _state[pinNumber].EventModes | eventTypes;
_state[pinNumber].Callback += callback;
}
}
/// <inheritdoc />
protected override void RemoveCallbackForPinValueChangedEvent(int pinNumber, PinChangeEventHandler callback)
{
bool terminate;
lock (_state)
{
_state[pinNumber].Callback -= callback;
if (_state[pinNumber].CallbacksExist == false)
{
_state[pinNumber].EventModes = PinEventTypes.None;
}
terminate = _state.All(x => x.CallbacksExist == false);
}
// Can't do this within the lock - would risk a deadlock
if (terminate && _pollThread != null)
{
_terminateThread = true;
_pollThread.Join();
_pollThread = null;
}
}
/// <summary>
/// Poor man's interrupt handling. This class is not for real production use, so doesn't really matter
/// </summary>
private void PollingKeyThread()
{
while (!_terminateThread)
{
lock (_state)
{
foreach (var s in _state)
{
if (s.EventModes != PinEventTypes.None)
{
var newState = Read(s.PinNumber);
if (s.State != newState)
{
s.State = newState;
// Fire either way - the client has to handle that anyway (because other clients may request the other edge)
s.FireCallback(this, new PinValueChangedEventArgs(newState == PinValue.High ? PinEventTypes.Rising : PinEventTypes.Falling, s.PinNumber));
}
}
}
}
Thread.Sleep(10);
}
}
private sealed class KeyState
{
public KeyState(ConsoleKey key, int pinNumber)
{
Key = key;
PinNumber = pinNumber;
State = PinValue.Low;
}
public event PinChangeEventHandler? Callback;
public ConsoleKey Key
{
get;
}
public int PinNumber { get; }
public PinMode Mode
{
get;
set;
}
public PinValue State
{
get;
set;
}
public PinEventTypes EventModes { get; set; }
public bool CallbacksExist
{
get
{
return Callback != null;
}
}
public void FireCallback(object sender, PinValueChangedEventArgs pinValueChangedEventArgs)
{
Callback?.Invoke(sender, pinValueChangedEventArgs);
}
}
}
}