-
Notifications
You must be signed in to change notification settings - Fork 0
/
ichb.c
526 lines (480 loc) · 12.4 KB
/
ichb.c
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <linux/input.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
// -----------------------------------------------------------------------------
#define BEEP
#include "ichb.h"
// -----------------------------------------------------------------------------
static char * const *ICHB_CmdTable[cmdMax] =
{
#ifdef BEEP
[cmdBeepAck] = (char * const[]){ "/usr/bin/beep", "beep", "-f", "880", "-n", "-f", "1760", NULL },
[cmdBeepNak] = (char * const[]){ "/usr/bin/beep", "beep", "-f", "1760", "-n", "-f", "880", NULL },
[cmdBeepKey] = (char * const[]){ "/usr/bin/beep", "beep", "-f", "960", "-l", "80", NULL },
#endif
[cmdLs] = (char * const[]){ "/bin/ls", "ls", "-lh", NULL },
};
// -----------------------------------------------------------------------------
static __u16 *ICHB_KeySequenceTable[ksMax] =
{
[ks001] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP1, 0 },
[ks002] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP2, 0 },
[ks003] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP3, 0 },
[ks004] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP4, 0 },
[ks005] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP4, 0 },
[ks006] = (__u16[]){ KEY_KP0, KEY_KP0, KEY_KP6, 0 },
};
// -----------------------------------------------------------------------------
static ICHB_Match ICHB_MatchTable[] =
{
#ifdef BEEP
{ .ksId = ks001, .cmdId = cmdBeepAck },
{ .ksId = ks002, .cmdId = cmdBeepNak },
{ .ksId = ks003, .cmdId = cmdBeepKey },
#endif
{ .ksId = ks004, .cmdId = cmdLs },
};
// -----------------------------------------------------------------------------
static ICHB_Instance ichb =
{
.inputDeviceName = "/dev/input/by-id/usb-04f3_0104-event-kbd",
.pInputDevice = NULL,
.fdInputDevice = -1,
.grabInputDevice = -1,
.readErrorStreak = 0,
.lastScanCode = 0,
.matchState = stateInit
};
// -----------------------------------------------------------------------------
int ICHB_Main(void);
static void ICHB_TryInputDevice(void);
static ICHB_OpenResult ICHB_OpenInputDevice(void);
static void ICHB_CloseInputDevice(void);
static ICHB_ReadResult ICHB_ReadFromInputDevice(void);
static int ICHB_FilterScanCode(__u16 code);
static ICHB_MachineResult ICHB_MatchMachine(void);
static void ICHB_MatchReset(void);
static void ICHB_MatchCollect(void);
static void ICHB_MatchExecute(void);
static void ICHB_Exec(ICHB_CommandId cmdId);
static void ICHB_ExecOrphaned(ICHB_CommandId cmdId);
static void ICHB_PrintCommand(ICHB_CommandId cmdId);
static int ICHB_IsBeepCommand(ICHB_CommandId cmdId);
static void ICHB_ErrorPrint(const char *func, const char *msg, int withErrno);
// -----------------------------------------------------------------------------
int main(int argc, char **argv)
{
// Fork to daemonize the program and signal to systemd that we are done
// starting (i.e. the systemd unit is of type 'forking')
switch (fork())
{
case forkError:
ENOPRINT("Forking failed");
return -1;
case forkChild:;
return ICHB_Main();
default:
return 0;
break;
}
}
// -----------------------------------------------------------------------------
int ICHB_Main(void)
{
while (1)
{
ICHB_TryInputDevice();
if (ICHB_OpenInputDevice() != openOk)
{
ICHB_CloseInputDevice();
continue;
}
printf("Capturing input device events ...\n");
ICHB_ReadResult readResult = ICHB_ReadFromInputDevice();
while (readResult != readError)
{
if (readResult == readKey)
{
ICHB_MachineResult machineResult = ICHB_MatchMachine();
while (machineResult == chainStateSwitch)
{
machineResult = ICHB_MatchMachine();
}
}
readResult = ICHB_ReadFromInputDevice();
}
ICHB_CloseInputDevice();
}
return 0;
}
// -----------------------------------------------------------------------------
static void ICHB_TryInputDevice(void)
{
printf("Checking for input device availability ...\n");
while (!ichb.pInputDevice)
{
ichb.pInputDevice = fopen(ichb.inputDeviceName, "r");
if (!ichb.pInputDevice)
{
sleep(5);
}
}
printf("Input device is now available.\n");
}
// -----------------------------------------------------------------------------
static ICHB_OpenResult ICHB_OpenInputDevice(void)
{
if (!ichb.pInputDevice)
{
ichb.pInputDevice = fopen(ichb.inputDeviceName, "r");
if (!ichb.pInputDevice)
{
ENOPRINT("Could not open input device");
return openFailed;
}
}
ichb.fdInputDevice = fileno(ichb.pInputDevice);
if (ichb.fdInputDevice < 0)
{
ENOPRINT("Could not get file descriptor of input device");
return openFailed;
}
ichb.grabInputDevice = ioctl(ichb.fdInputDevice, EVIOCGRAB, 1);
if (ichb.grabInputDevice < 0)
{
ENOPRINT("Could not get exclusive access to device");
return openFailed;
}
return openOk;
}
// -----------------------------------------------------------------------------
static void ICHB_CloseInputDevice(void)
{
if ((ichb.grabInputDevice >= 0) && (ichb.fdInputDevice >= 0))
{
ioctl(ichb.fdInputDevice, EVIOCGRAB, 0);
ichb.grabInputDevice = -1;
ichb.fdInputDevice = -1;
}
if (ichb.pInputDevice)
{
fclose(ichb.pInputDevice);
ichb.pInputDevice = NULL;
}
}
// -----------------------------------------------------------------------------
static ICHB_ReadResult ICHB_ReadFromInputDevice(void)
{
enum _eKeyEvent
{
keyRelease = 0,
keyPress = 1,
keyRepeat = 2
};
struct input_event event = {0};
size_t const eventSize = sizeof(struct input_event);
size_t const readSize = fread(&event, 1, eventSize, ichb.pInputDevice);
if (readSize != eventSize)
{
int const deviceClosed = feof(ichb.pInputDevice);
if (deviceClosed)
{
ENOPRINT("Input device closed");
return readError;
}
int const deviceError = ferror(ichb.pInputDevice);
if (deviceError)
{
ENOPRINT("Input device read error");
return readError;
}
ichb.readErrorStreak++;
if (ichb.readErrorStreak >= 100)
{
EPRINT("Too many device read errors in a row");
return readError;
}
}
if ((event.type != EV_KEY) || (event.value != keyPress))
{
return readIgnored;
}
ichb.readErrorStreak = 0;
if (ICHB_FilterScanCode(event.code))
{
return readIgnored;
}
printf("type %5u | code %5u | value %10d\n", event.type, event.code, event.value);
ichb.lastScanCode = event.code;
return readKey;
}
// -----------------------------------------------------------------------------
static int ICHB_FilterScanCode(__u16 code)
{
switch (code)
{
// Use a limited subset of simple keys on a numeric keypad
case KEY_BACKSPACE:
case KEY_KPENTER:
case KEY_KP0:
case KEY_KP1:
case KEY_KP2:
case KEY_KP3:
case KEY_KP4:
case KEY_KP5:
case KEY_KP6:
case KEY_KP7:
case KEY_KP8:
case KEY_KP9:
return 0;
// Filter out the rest, NUM-lock, +, -, modifiers, etc.
default:
return 1;
}
}
// -----------------------------------------------------------------------------
static ICHB_MachineResult ICHB_MatchMachine(void)
{
switch (ichb.matchState)
{
case stateCollect:
{
switch (ichb.lastScanCode)
{
case KEY_KPENTER:
{
ichb.matchState = stateExecute;
return chainStateSwitch;
}
break;
case KEY_BACKSPACE:
{
BEEP_ACK;
ichb.matchState = stateReset;
return chainStateSwitch;
}
break;
case 0:
{
ichb.matchState = stateCollect;
return haltMachine;
}
break;
default:
{
BEEP_KEY;
ICHB_MatchCollect();
ichb.matchState = stateCollect;
return haltMachine;
}
break;
}
}
break;
case stateExecute:
{
ICHB_MatchExecute();
ichb.matchState = stateReset;
return chainStateSwitch;
}
break;
case stateInit:
{
__u16 const preservedScanCode = ichb.lastScanCode;
ICHB_MatchReset();
ichb.lastScanCode = preservedScanCode;
ichb.matchState = stateCollect;
return chainStateSwitch;
}
break;
case stateReset: // fall through
default:
{
ICHB_MatchReset();
ichb.matchState = stateCollect;
return haltMachine;
}
break;
}
}
// -----------------------------------------------------------------------------
static void ICHB_MatchReset(void)
{
size_t const matchTableSize = sizeof(ICHB_MatchTable)/sizeof(ICHB_MatchTable[0]);
for (size_t i = 0; i < matchTableSize; i++)
{
// Reset all match pointers to the first scan code of each sequence
ICHB_Match *match = ICHB_MatchTable + i;
match->matchPointer = ICHB_KeySequenceTable[match->ksId];
}
// Consume the scan code
ichb.lastScanCode = 0;
}
// -----------------------------------------------------------------------------
static void ICHB_MatchCollect(void)
{
size_t const matchTableSize = sizeof(ICHB_MatchTable)/sizeof(ICHB_MatchTable[0]);
for (size_t i = 0; i < matchTableSize; i++)
{
ICHB_Match *match = ICHB_MatchTable + i;
if (!match->matchPointer)
{
// Skip matches that already failed.
// They are marked by a NULL pointer.
continue;
}
__u16 const expectedScanCode = *(match->matchPointer);
if (expectedScanCode == ichb.lastScanCode)
{
// The sequence matched all scan codes including the
// last one. Advance the pointer!
match->matchPointer++;
}
else
{
// The sequence did not match the last scan code.
// Set the pointer to NULL to remember.
match->matchPointer = NULL;
}
}
// Consume the scan code
ichb.lastScanCode = 0;
}
// -----------------------------------------------------------------------------
static void ICHB_MatchExecute(void)
{
size_t const matchTableSize = sizeof(ICHB_MatchTable)/sizeof(ICHB_MatchTable[0]);
int anyMatch = 0;
for (size_t i = 0; i < matchTableSize; i++)
{
ICHB_Match *match = ICHB_MatchTable + i;
if (!match->matchPointer)
{
// Skip matches that already failed;
// they are marked by a NULL pointer
continue;
}
__u16 const endOfSequence = *(match->matchPointer);
if (endOfSequence == 0)
{
if (!anyMatch)
{
anyMatch = 1;
if (!ICHB_IsBeepCommand(match->cmdId))
{
BEEP_ACK;
}
}
ICHB_Exec(match->cmdId);
}
}
if (!anyMatch)
{
BEEP_NAK;
}
// Consume the scan code
ichb.lastScanCode = 0;
}
// -----------------------------------------------------------------------------
static void ICHB_Exec(ICHB_CommandId cmdId)
{
// Spawn a child.
switch (fork())
{
case forkError:
ENOPRINT("Forking failed");
break;
case forkChild:
// The child process creates a grandchild for the sole purpose
// of orphaning it and handing it off to the init process.
ICHB_ExecOrphaned(cmdId);
break;
default:;
// The parent waits for the child to terminate after spawning the
// grandchild.
int childExitstatus;
wait(&childExitstatus);
break;
}
}
// -----------------------------------------------------------------------------
static void ICHB_ExecOrphaned(ICHB_CommandId cmdId)
{
// Spawn a grandchild.
switch (fork())
{
case forkError:
ENOPRINT("Forking failed");
break;
case forkChild:;
ICHB_PrintCommand(cmdId);
char * const cmdPath = ICHB_CmdTable[cmdId][0];
char * const *cmdArgv = &(ICHB_CmdTable[cmdId][1]);
execv(cmdPath, cmdArgv);
// We only return here if the system call fails,
// print the error and kill ourselves (the grandchild).
ENOPRINT(cmdPath);
exit(-1);
break;
default:;
// The child (parent of the grandchild) terminates immediately.
// We do not want to track and collect the exit status of the
// grandchild. The grandchild will be orphaned and inherited by
// the init process.
_exit(0);
break;
}
}
// -----------------------------------------------------------------------------
static void ICHB_PrintCommand(ICHB_CommandId cmdId)
{
if (ICHB_IsBeepCommand(cmdId))
{
return;
}
char * const cmdPath = ICHB_CmdTable[cmdId][0];
char * const *cmdArgv = &(ICHB_CmdTable[cmdId][1]);
printf("Executing \"%s", cmdPath);
char * const *pArg = cmdArgv;
pArg++;
while (*pArg)
{
printf(" %s", *pArg);
pArg++;
}
printf("\"\n");
}
// -----------------------------------------------------------------------------
static int ICHB_IsBeepCommand(ICHB_CommandId cmdId)
{
#ifdef BEEP
switch (cmdId)
{
case cmdBeepAck:
case cmdBeepNak:
case cmdBeepKey:
return 1;
default:
return 0;
}
#endif
return 0;
}
// -----------------------------------------------------------------------------
static void ICHB_ErrorPrint(const char *func, const char *msg, int withErrno)
{
if (withErrno)
{
fprintf(stderr, "%s: %s; %s (%d)\n", func, msg, strerror(errno), errno);
}
else
{
fprintf(stderr, "%s: %s\n", func, msg);
}
}
// -----------------------------------------------------------------------------