demo: make the GUI preemptive-safe.
[bertos.git] / bertos / drv / kbd.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2005 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 1999, 2003 Bernie Innocenti
31  *
32  * -->
33  *
34  * \brief Keyboard driver (implementation)
35  *
36  * \version $Id$
37  *
38  * \author Bernie Innocenti <bernie@codewiz.org>
39  * \author Stefano Fedrigo <aleph@develer.com>
40  * \author Francesco Sacchi <batt@develer.com>
41  *
42  */
43
44 #include "hw/hw_kbd.h"
45
46 #include "cfg/cfg_kbd.h"
47 #include <cfg/debug.h>
48 #include <cfg/module.h>
49
50 #include <drv/timer.h>
51 #include <drv/kbd.h>
52
53
54 /* Configuration sanity checks */
55 #if !defined(CONFIG_KBD_POLL) || (CONFIG_KBD_POLL != KBD_POLL_SOFTINT)
56         #error CONFIG_KBD_POLL must be defined to either KBD_POLL_SOFTINT
57 #endif
58 #if !defined(CONFIG_KBD_BEEP) || (CONFIG_KBD_BEEP != 0 && CONFIG_KBD_BEEP != 1)
59         #error CONFIG_KBD_BEEP must be defined to either 0 or 1
60 #endif
61 #if !defined(CONFIG_KBD_OBSERVER) || (CONFIG_KBD_OBSERVER != 0 && CONFIG_KBD_OBSERVER != 1)
62         #error CONFIG_KBD_OBSERVER must be defined to either 0 or 1
63 #endif
64 #if !defined(CONFIG_KBD_LONGPRESS) || (CONFIG_KBD_LONGPRESS != 0 && CONFIG_KBD_LONGPRESS != 1)
65         #error CONFIG_KBD_LONGPRESS must be defined to either 0 or 1
66 #endif
67
68 #if CONFIG_KBD_BEEP
69         #include <drv/buzzer.h>
70 #endif
71
72 #define KBD_CHECK_INTERVAL  10  /**< (ms) Timing for kbd softint */
73 #define KBD_DEBOUNCE_TIME   30  /**< (ms) Debounce time */
74 #define KBD_BEEP_TIME        5  /**< (ms) Duration of keybeep */
75
76 #define KBD_REPEAT_DELAY   400  /**< (ms) Keyboard repeat delay for first character */
77 #define KBD_REPEAT_RATE    100  /**< (ms) Initial interchar delay for keyboard repeat */
78 #define KBD_REPEAT_MAXRATE  20  /**< (ms) Minimum delay for keyboard repeat */
79 #define KBD_REPEAT_ACCEL     5  /**< (ms) Keyboard repeat speed increase */
80
81 #define KBD_LNG_DELAY     1000  /**< (ms) Keyboard long pression keys delay */
82
83
84 /** Status for keyboard repeat state machine */
85 static enum { KS_IDLE, KS_REPDELAY, KS_REPEAT } kbd_rptStatus;
86
87
88 static volatile keymask_t kbd_buf; /**< Single entry keyboard buffer */
89 static volatile keymask_t kbd_cnt; /**< Number of keypress events in \c kbd_buf */
90 static keymask_t kbd_rpt_mask;     /**< Mask of repeatable keys. */
91
92 #if CONFIG_KBD_POLL == KBD_POLL_SOFTINT
93 static Timer kbd_timer;            /**< Keyboard softtimer */
94 #endif
95
96 static List kbd_rawHandlers;       /**< Raw keyboard handlers */
97 static List kbd_handlers;          /**< Cooked keyboard handlers */
98
99 static KbdHandler kbd_defHandler;  /**< The default keyboard handler */
100 static KbdHandler kbd_debHandler;  /**< The debounce keyboard handler */
101 static KbdHandler kbd_rptHandler;  /**< Auto-repeat keyboard handler */
102
103 #if CONFIG_KBD_LONGPRESS
104 static KbdHandler kbd_lngHandler;  /**< Long pression keys handler */
105 #endif
106
107 #if CONFIG_KBD_OBSERVER
108         #include <mware/observer.h>
109         Subject kbd_subject;
110 #endif
111
112
113 /**
114  * Poll keyboard and dispatch keys to handlers.
115  *
116  * Read the key states and invoke all keyboard
117  * handlers to process the new state.
118  *
119  * Call this function periodically using a software
120  * timer, an interrupt or a process.
121  */
122 static void kbd_poll(void)
123 {
124         /** Currently depressed key */
125         static keymask_t current_key;
126
127         struct KbdHandler *handler;
128         keymask_t key = kbd_readkeys();
129
130         /* Call raw input handlers */
131         FOREACH_NODE(handler, &kbd_rawHandlers)
132                 key = handler->hook(key);
133
134         /* If this key was not previously pressed */
135         if (key != current_key)
136         {
137                 /* Remember last key */
138                 current_key = key;
139
140                 /* Call cooked input handlers */
141                 FOREACH_NODE(handler, &kbd_handlers)
142                         key = handler->hook(key);
143         }
144 }
145
146 #if CONFIG_KBD_POLL == KBD_POLL_SOFTINT
147
148 /**
149  * Keyboard soft-irq handler.
150  */
151 static void kbd_softint(UNUSED_ARG(iptr_t, arg))
152 {
153         kbd_poll();
154         timer_add(&kbd_timer);
155 }
156
157 #else
158         #error "Define keyboard poll method"
159
160 #endif /* CONFIG_KBD_POLL */
161
162 /**
163  * \brief Read a key from the keyboard buffer.
164  *
165  * When a key is kept depressed between calls of this function a value
166  * is returned only after the time specified with KBD_REPAT_DELAY to
167  * avoid too fast keyboard repeat.
168  *
169  * \note Calls \c schedule() internally.
170  *
171  * \note This function is \b not interrupt safe!
172  *
173  * \return The mask of depressed keys or 0 if no keys are depressed.
174  *
175  */
176 keymask_t kbd_peek(void)
177 {
178         keymask_t key = 0;
179
180 #if CONFIG_KBD_SCHED
181         timer_delay(1);
182 #endif
183
184         /* Extract an event from the keyboard buffer */
185         IRQ_DISABLE;
186         if (kbd_cnt)
187         {
188                 --kbd_cnt;
189                 key = kbd_buf;
190         }
191         IRQ_ENABLE;
192
193         return key;
194 }
195
196 /**
197  * Wait for a keypress and return the mask of depressed keys.
198  *
199  * \note This function is \b not interrupt safe!
200  */
201 keymask_t kbd_get(void)
202 {
203         keymask_t key;
204
205         while (!(key = kbd_peek())) {}
206
207         return key;
208 }
209
210
211 /**
212  * Wait up to \c timeout ms for a keypress
213  * and return the mask of depressed keys, or K_TIMEOUT
214  * if the timeout was reacked.
215  */
216 keymask_t kbd_get_timeout(mtime_t timeout)
217 {
218         keymask_t key;
219
220         ticks_t start = timer_clock();
221         ticks_t stop  = ms_to_ticks(timeout);
222         do
223         {
224                 if ((key = kbd_peek()))
225                         return key;
226         }
227         while (timer_clock() - start < stop);
228
229         return K_TIMEOUT;
230 }
231
232
233 void kbd_addHandler(struct KbdHandler *handler)
234 {
235         KbdHandler *node;
236         List *list;
237
238         cpu_flags_t flags;
239         IRQ_SAVE_DISABLE(flags);
240
241         /* Choose between raw and coocked handlers list */
242         list = (handler->flags & KHF_RAWKEYS) ?
243                 &kbd_rawHandlers : &kbd_handlers;
244
245         /*
246          * Search for the first node whose priority
247          * is lower than the timer we want to add.
248          */
249         FOREACH_NODE(node,list)
250                 if (node->pri < handler->pri)
251                         break;
252
253         /* Enqueue handler in the handlers chain */
254         INSERT_BEFORE(&handler->link, &node->link);
255
256         IRQ_RESTORE(flags);
257 }
258
259
260 void kbd_remHandler(struct KbdHandler *handler)
261 {
262         /* Remove the handler */
263         ATOMIC(REMOVE(&handler->link));
264 }
265
266
267 /**
268  * This is the default key handler, called after
269  * all other handlers have had their chance to
270  * do their special processing. This handler
271  * pushes all input in the keyboard FIFO buffer.
272  */
273 static keymask_t kbd_defHandlerFunc(keymask_t key)
274 {
275         if (key)
276         {
277                 /* Force a single event in kbd buffer */
278                 kbd_buf = key;
279                 kbd_cnt = 1;
280
281                 #if CONFIG_KBD_OBSERVER
282                         observer_notify(&kbd_subject, KBD_EVENT_KEY, &key);
283                 #endif
284
285                 #if CONFIG_KBD_BEEP
286                         if (!(key & K_REPEAT))
287                                 buz_beep(KBD_BEEP_TIME);
288                 #endif
289         }
290
291         /* Eat all input */
292         return 0;
293 }
294
295 /**
296  * Handle keyboard debounce
297  */
298 static keymask_t kbd_debHandlerFunc(keymask_t key)
299 {
300         /** Buffer for debounce */
301         static keymask_t debounce_key;
302
303         /** Timer for keyboard debounce */
304         static ticks_t debounce_time;
305
306         /** Key aquired after debounce */
307         static keymask_t new_key;
308
309
310         ticks_t now = timer_clock();
311
312         if (key != debounce_key)
313         {
314                 /* Reset debounce timer */
315                 debounce_key = key;
316                 debounce_time = now;
317         }
318         else if ((new_key != debounce_key)
319                 && (now - debounce_time > ms_to_ticks(KBD_DEBOUNCE_TIME)))
320         {
321                 new_key = debounce_key;
322                 debounce_time = now;
323         }
324
325         return new_key;
326 }
327
328 #if CONFIG_KBD_LONGPRESS
329 /**
330  * Handle long pression keys.
331  */
332 static keymask_t kbd_lngHandlerFunc(keymask_t key)
333 {
334         static ticks_t start;
335         ticks_t now = timer_clock();
336
337         if (key & K_LNG_MASK)
338         {
339                 if (now - start > ms_to_ticks(KBD_LNG_DELAY))
340                         key |= K_LONG;
341         }
342         else
343                 start = now;
344         return key;
345 }
346 #endif
347
348 /**
349  * Set current mask of repeatable keys.
350  */
351 keymask_t kbd_setRepeatMask(keymask_t mask)
352 {
353         keymask_t oldmask = kbd_rpt_mask;
354         ATOMIC(kbd_rpt_mask = mask);
355         return oldmask;
356 }
357
358 /**
359  * Handle keyboard repeat
360  */
361 static keymask_t kbd_rptHandlerFunc(keymask_t key)
362 {
363         /* Timer for keyboard repeat events. */
364         static ticks_t repeat_time;
365
366         /* Current repeat rate (for acceleration). */
367         static ticks_t repeat_rate; /** Current repeat rate (for acceleration) */
368
369         ticks_t now = timer_clock();
370
371         switch (kbd_rptStatus)
372         {
373                 case KS_IDLE:
374                         if (key & kbd_rpt_mask)
375                         {
376                                 repeat_time = now;
377                                 kbd_rptStatus = KS_REPDELAY;
378                         }
379                         break;
380
381                 case KS_REPDELAY:
382                         if (key & kbd_rpt_mask)
383                         {
384                                 if (now - repeat_time > ms_to_ticks(KBD_REPEAT_DELAY))
385                                 {
386                                         key = (key & kbd_rpt_mask) | K_REPEAT;
387                                         repeat_time = now;
388                                         repeat_rate = ms_to_ticks(KBD_REPEAT_RATE);
389                                         kbd_rptStatus = KS_REPEAT;
390                                 }
391                                 else
392                                         key = 0;
393                         }
394                         else
395                                 kbd_rptStatus = KS_IDLE;
396                         break;
397
398                 case KS_REPEAT:
399                         if (key & kbd_rpt_mask)
400                         {
401                                 if (now - repeat_time > repeat_rate)
402                                 {
403                                         /* Enqueue a new event in the buffer */
404                                         key = (key & kbd_rpt_mask) | K_REPEAT;
405                                         repeat_time = now;
406
407                                         /* Repeat rate acceleration */
408                                         if (repeat_rate > ms_to_ticks(KBD_REPEAT_MAXRATE))
409                                                 repeat_rate -= ms_to_ticks(KBD_REPEAT_ACCEL);
410                                 }
411                                 else
412                                         key = 0;
413                         }
414                         else
415                                 kbd_rptStatus = KS_IDLE;
416
417                         break;
418         }
419
420         return key;
421 }
422
423
424 MOD_DEFINE(kbd)
425
426 /**
427  * Initialize keyboard ports and softtimer
428  */
429 void kbd_init(void)
430 {
431 #if CONFIG_KBD_BEEP
432         MOD_CHECK(buzzer);
433 #endif
434
435         KBD_HW_INIT;
436
437         /* Init handlers lists */
438         LIST_INIT(&kbd_handlers);
439         LIST_INIT(&kbd_rawHandlers);
440
441         /* Add debounce keyboard handler */
442         kbd_debHandler.hook = kbd_debHandlerFunc;
443         kbd_debHandler.pri = 100; /* high priority */
444         kbd_debHandler.flags = KHF_RAWKEYS;
445         kbd_addHandler(&kbd_debHandler);
446
447         #if CONFIG_KBD_LONGPRESS
448         /* Add long pression keyboard handler */
449         kbd_lngHandler.hook = kbd_lngHandlerFunc;
450         kbd_lngHandler.pri = 90; /* high priority */
451         kbd_lngHandler.flags = KHF_RAWKEYS;
452         kbd_addHandler(&kbd_lngHandler);
453         #endif
454
455         /* Add repeat keyboard handler */
456         kbd_rptHandler.hook = kbd_rptHandlerFunc;
457         kbd_rptHandler.pri = 80; /* high priority */
458         kbd_rptHandler.flags = KHF_RAWKEYS;
459         kbd_addHandler(&kbd_rptHandler);
460
461         /* Add default keyboard handler */
462         kbd_defHandler.hook = kbd_defHandlerFunc;
463         kbd_defHandler.pri = -128; /* lowest priority */
464         kbd_addHandler(&kbd_defHandler);
465
466 #if CONFIG_KBD_OBSERVER
467         observer_InitSubject(&kbd_subject);
468 #endif
469
470 #if CONFIG_KBD_POLL == KBD_POLL_SOFTINT
471
472         MOD_CHECK(timer);
473
474         /* Add kbd handler to soft timers list */
475         event_initSoftint(&kbd_timer.expire, kbd_softint, NULL);
476         timer_setDelay(&kbd_timer, ms_to_ticks(KBD_CHECK_INTERVAL));
477         timer_add(&kbd_timer);
478
479 #else
480         #error "Define keyboard poll method"
481
482 #endif
483
484         MOD_INIT(kbd);
485 }