MatrixKeyboard.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
377
378
379
380
381
382
383
384
385
386
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using Microsoft.SPOT.Presentation;
using System.Collections;
using System.Threading;

namespace UAM.InformatiX.SPOT.Hardware
{
public class MatrixKeyboard
{
[Serializable]
public struct KeyLocation
{
public int Row;
public int Column;

public KeyLocation(int row, int column)
{
Row = row;
Column = column;
}
internal KeyLocation(int active, int passive, bool activeIsRow)
{
if (activeIsRow)
{
Row = active;
Column = passive;
}
else
{
Row = passive;
Column = active;
}
}

public override string ToString()
{
return "{Key [" + Row + ", " + Column + "]}";
}
public static bool operator ==(KeyLocation k1, KeyLocation k2)
{
return k1.Row == k2.Row && k1.Column == k2.Column;
}
public static bool operator !=(KeyLocation k1, KeyLocation k2)
{
return k1.Row != k2.Row || k1.Column != k2.Column;
}

public override bool Equals(object obj)
{
if (!(obj is KeyLocation)) return false;

return (this == (KeyLocation)obj);
}
public override int GetHashCode()
{
return Row ^ Column;
}

public static explicit operator KeyLocation(long coordinates)
{
KeyLocation location = new KeyLocation();
location.Column = (int)coordinates;
location.Row = (int)(coordinates >> 32);

return location;
}
public static explicit operator long(KeyLocation location)
{
return ((long)location.Row << 32) + location.Column;
}
}
public class KeyStateArray
{
private int _rows;
private int _columns;
private int[] _data;

public KeyStateArray(int rows, int columns)
{
_rows = rows;
_columns = columns;

int bits = rows * columns;
int arrSize = bits / 32;
if (arrSize * 32 < bits) arrSize++;

_data = new int[arrSize];
}
public bool this[int row, int column]
{
get
{
if (row < 0 || row >= _rows) throw new ArgumentOutOfRangeException("row");
if (column < 0 || column >= _columns) throw new ArgumentOutOfRangeException("column");

int bitIndex = row * _columns + column;
int arrIndex = bitIndex / 32;
bitIndex -= arrIndex * 32;

int mask = 1 << bitIndex;
return (_data[arrIndex] & mask) != 0;
}
set
{
if (row < 0 || row >= _rows) throw new ArgumentOutOfRangeException("row");
if (column < 0 || column >= _columns) throw new ArgumentOutOfRangeException("column");

int bitIndex = row * _columns + column;
int arrIndex = bitIndex / 32;
bitIndex -= arrIndex * 32;

int mask = 1 << bitIndex;
if (value) _data[arrIndex] |= mask;
else _data[arrIndex] &= ~mask;
}
}

public override bool Equals(object obj)
{
KeyStateArray other = obj as KeyStateArray;
if (other == null) return false;

if (this._columns != other._columns) return false;
if (this._rows != other._rows) return false;

for (int i = 0; i < this._data.Length; i++)
if (this._data[i] != other._data[i]) return false;

return true;
}
public static bool operator ==(KeyStateArray a, KeyStateArray b)
{
if (a == null) return b == null;
if (b == null) return false;

return a.Equals(b);
}
public static bool operator !=(KeyStateArray a, KeyStateArray b)
{
return !(a == b);
}
public override int GetHashCode()
{
int hash = _rows ^ _columns;
for (int i = 0; i < _data.Length; i++)
hash ^= _data[i];

return hash;
}

public override string ToString()
{
return "{KeyState " + _rows + "�" + _columns + "}";
}

public static bool IsCompatible(KeyStateArray a, KeyStateArray b)
{
return (a._columns == b._columns) && (a._rows == b._rows);
}
public static void FindChanges(KeyStateArray oldState, KeyStateArray newState, out ArrayList pressed, out ArrayList released)
{
if (!IsCompatible(oldState, newState)) throw new ArgumentException("States are not compatible.");

pressed = new ArrayList();
released = new ArrayList();

int arrIndex = 0, bitIndex;
for (int i = 0; i < oldState._data.Length; i++)
{
if (oldState._data[i] != newState._data[i])
{
int oldFragment = oldState._data[i];
int newFragment = newState._data[i];
int changes = oldFragment ^ newFragment;
bitIndex = 0;
while (changes > 0)
{
if ((changes % 2) != 0)
{
int row = (arrIndex + bitIndex) / oldState._columns;
int column = (arrIndex + bitIndex) - row * oldState._columns;
if (((newFragment >> bitIndex) % 2) != 0)
pressed.Add(new KeyLocation(row, column));
else
released.Add(new KeyLocation(row, column));
}
changes >>= 1;
bitIndex++;
}
}
arrIndex += 32;
}
}
}

private OutputPort[] _activePorts;
private InterruptPort[] _passivePorts;
private bool _activeAreRows;

private bool on = true;
private bool off = false;

public MatrixKeyboard(Cpu.Pin[] rowPins, Cpu.Pin[] columnPins, Port.ResistorMode resistorMode)
{
if (rowPins == null) throw new ArgumentNullException("rowPins");
if (columnPins == null) throw new ArgumentNullException("columnPins");

if (rowPins.Length == 0) throw new ArgumentException("rowPins");
if (columnPins.Length == 0) throw new ArgumentException("columnPins");

Cpu.Pin[] activePins, passivePins;
if (resistorMode == Port.ResistorMode.PullUp)
{
on = false;
off = true;
}

_activeAreRows = rowPins.Length < columnPins.Length;
activePins = _activeAreRows ? rowPins : columnPins;
passivePins = _activeAreRows ? columnPins : rowPins;

_activePorts = new OutputPort[activePins.Length];
_passivePorts = new InterruptPort[passivePins.Length];

_lastState = new KeyStateArray(rowPins.Length, columnPins.Length);
_interruptHandler = new NativeEventHandler(OnInterrupt);
_eventThreadEvent = new AutoResetEvent(false);
_eventBuffer = new ArrayList();

for (int i = 0; i < _activePorts.Length; i++)
_activePorts[i] = new OutputPort(activePins[i], off);

for (int i = 0; i < _passivePorts.Length; i++)
_passivePorts[i] = new InterruptPort(passivePins[i], true, resistorMode, Port.InterruptMode.InterruptEdgeBoth);

Thread eventThread = new Thread(EventThread);
eventThread.Start();
}

private KeyStateArray _lastState;
public virtual KeyStateArray GetCurrentState()
{
return _activeAreRows ? GetCurrentStateByRows() : GetCurrentStateByColumns();
}
protected KeyStateArray GetCurrentStateByRows()
{
KeyStateArray current = new KeyStateArray(_activePorts.Length, _passivePorts.Length);

_activePorts[0].Write(on);
for (int p = 0; p < _passivePorts.Length; p++)
if (_passivePorts[p].Read() == on) current[0, p] = true;

for (int a = 1; a < _activePorts.Length; a++)
{
_activePorts[a].Write(on);
_activePorts[a - 1].Write(off);
for (int p = 0; p < _passivePorts.Length; p++)
if (_passivePorts[p].Read() == on) current[a, p] = true;
}

_activePorts[_activePorts.Length - 1].Write(off);
return current;
}
protected KeyStateArray GetCurrentStateByColumns()
{
KeyStateArray current = new KeyStateArray(_passivePorts.Length, _activePorts.Length);

_activePorts[0].Write(on);
for (int p = 0; p < _passivePorts.Length; p++)
if (_passivePorts[p].Read() == on) current[p, 0] = true;

for (int a = 1; a < _activePorts.Length; a++)
{
_activePorts[a].Write(on);
_activePorts[a - 1].Write(off);
for (int p = 0; p < _passivePorts.Length; p++)
if (_passivePorts[p].Read() == on) current[p, a] = true;
}

_activePorts[_activePorts.Length - 1].Write(off);
return current;
}

private NativeEventHandler _interruptHandler;
public virtual void StartListening()
{
for (int i = 0; i < _activePorts.Length; i++)
_activePorts[i].Write(on);

for (int i = 0; i < _passivePorts.Length; i++)
_passivePorts[i].OnInterrupt += _interruptHandler;
}
public virtual void StopListening()
{
for (int i = 0; i < _passivePorts.Length; i++)
_passivePorts[i].OnInterrupt -= _interruptHandler;

for (int i = 0; i < _activePorts.Length; i++)
_activePorts[i].Write(off);
}
protected virtual void OnInterrupt(uint port, uint state, TimeSpan time)
{
StopListening();
KeyStateArray currentState = GetCurrentState();

ArrayList pressed, released;
KeyStateArray.FindChanges(_lastState, currentState, out pressed, out released);
lock (_eventBuffer)
{
for (int i = 0; i < pressed.Count; i++)
_eventBuffer.Add(new EventBufferItem((KeyLocation)pressed[i], true, time));
for (int i = 0; i < released.Count; i++)
_eventBuffer.Add(new EventBufferItem((KeyLocation)released[i], false, time));
}
_lastState = currentState;
StartListening();

_eventThreadEvent.Set();
}

protected virtual void OnKeyPressed(KeyLocation location, TimeSpan time)
{
Debug.Print("DOWN: " + location.ToString());
if (KeyPressed != null)
KeyPressed(this, location, time);
}
protected virtual void OnKeyReleased(KeyLocation location, TimeSpan time)
{
Debug.Print("UP: " + location.ToString());
if (KeyReleased != null)
KeyReleased(this, location, time);
}
public event KeyEventHandler KeyPressed;
public event KeyEventHandler KeyReleased;

private ArrayList _eventBuffer;
private AutoResetEvent _eventThreadEvent;
private void EventThread()
{
EventBufferItem item;
while (true)
{
if (_eventBuffer.Count < 1)
_eventThreadEvent.WaitOne();

lock (_eventBuffer)
{
if (_eventBuffer.Count < 1) continue;

item = (EventBufferItem)_eventBuffer[0];
_eventBuffer.RemoveAt(0);
}

if (item.State)
OnKeyPressed(item.Key, item.Time);
else
OnKeyReleased(item.Key, item.Time);
}
}
private class EventBufferItem
{
public KeyLocation Key;
public bool State;
public TimeSpan Time;

public EventBufferItem(KeyLocation key, bool state, TimeSpan time)
{
Key = key;
State = state;
Time = time;
}
}

private bool _moreButtons;
public bool EnableMoreButtons { get { return _moreButtons; } set { _moreButtons = value; } }

public delegate void KeyEventHandler(MatrixKeyboard keyboard, KeyLocation location, TimeSpan time);

private static UIElement _focusedElement;
public static UIElement FocusedElement { get { return _focusedElement; } }
public static void Focus(UIElement element) { _focusedElement = Microsoft.SPOT.Input.Buttons.Focus(element); }
}
}