d592f069df8731a3739d721fdaccc382ea86eb98
[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 Bernardo Innocenti
31  *
32  * -->
33  *
34  * \brief Keyboard driver (implementation)
35  *
36  * \version $Id$
37  *
38  * \author Bernardo Innocenti <bernie@develer.com>
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 // FIXME: make it optional
181         /* Let other tasks run for a while */
182         extern void schedule(void);
183         schedule();
184
185         /* Extract an event from the keyboard buffer */
186         IRQ_DISABLE;
187         if (kbd_cnt)
188         {
189                 --kbd_cnt;
190                 key = kbd_buf;
191         }
192         IRQ_ENABLE;
193
194         return key;
195 }
196
197 /**
198  * Wait for a keypress and return the mask of depressed keys.
199  *
200  * \note This function is \b not interrupt safe!
201  */
202 keymask_t kbd_get(void)
203 {
204         keymask_t key;
205
206         while (!(key = kbd_peek())) {}
207
208         return key;
209 }
210
211
212 /**
213  * Wait up to \c timeout ms for a keypress
214  * and return the mask of depressed keys, or K_TIMEOUT
215  * if the timeout was reacked.
216  */
217 keymask_t kbd_get_timeout(mtime_t timeout)
218 {
219         keymask_t key;
220
221         ticks_t start = timer_clock();
222         ticks_t stop  = ms_to_ticks(timeout);
223         do
224         {
225                 if ((key = kbd_peek()))
226                         return key;
227         }
228         while (timer_clock() - start < stop);
229
230         return K_TIMEOUT;
231 }
232
233
234 void kbd_addHandler(struct KbdHandler *handler)
235 {
236         KbdHandler *node;
237         List *list;
238
239         cpuflags_t flags;
240         IRQ_SAVE_DISABLE(flags);
241
242         /* Choose between raw and coocked handlers list */
243         list = (handler->flags & KHF_RAWKEYS) ?
244                 &kbd_rawHandlers : &kbd_handlers;
245
246         /*
247          * Search for the first node whose priority
248          * is lower than the timer we want to add.
249          */
250         FOREACH_NODE(node,list)
251                 if (node->pri < handler->pri)
252                         break;
253
254         /* Enqueue handler in the handlers chain */
255         INSERT_BEFORE(&handler->link, &node->link);
256
257         IRQ_RESTORE(flags);
258 }
259
260
261 void kbd_remHandler(struct KbdHandler *handler)
262 {
263         /* Remove the handler */
264         ATOMIC(REMOVE(&handler->link));
265 }
266
267
268 /**
269  * This is the default key handler, called after
270  * all other handlers have had their chance to
271  * do their special processing. This handler
272  * pushes all input in the keyboard FIFO buffer.
273  */
274 static keymask_t kbd_defHandlerFunc(keymask_t key)
275 {
276         if (key)
277         {
278                 /* Force a single event in kbd buffer */
279                 kbd_buf = key;
280                 kbd_cnt = 1;
281
282                 #if CONFIG_KBD_OBSERVER
283                         observer_notify(&kbd_subject, KBD_EVENT_KEY, &key);
284                 #endif
285
286                 #if CONFIG_KBD_BEEP
287                         if (!(key & K_REPEAT))
288                                 buz_beep(KBD_BEEP_TIME);
289                 #endif
290         }
291
292         /* Eat all input */
293         return 0;
294 }
295
296 /**
297  * Handle keyboard debounce
298  */
299 static keymask_t kbd_debHandlerFunc(keymask_t key)
300 {
301         /** Buffer for debounce */
302         static keymask_t debounce_key;
303
304         /** Timer for keyboard debounce */
305         static ticks_t debounce_time;
306
307         /** Key aquired after debounce */
308         static keymask_t new_key;
309
310
311         ticks_t now = timer_clock();
312
313         if (key != debounce_key)
314         {
315                 /* Reset debounce timer */
316                 debounce_key = key;
317                 debounce_time = now;
318         }
319         else if ((new_key != debounce_key)
320                 && (now - debounce_time > ms_to_ticks(KBD_DEBOUNCE_TIME)))
321         {
322                 new_key = debounce_key;
323                 debounce_time = now;
324         }
325
326         return new_key;
327 }
328
329 #if CONFIG_KBD_LONGPRESS
330 /**
331  * Handle long pression keys.
332  */
333 static keymask_t kbd_lngHandlerFunc(keymask_t key)
334 {
335         static ticks_t start;
336         ticks_t now = timer_clock();
337
338         if (key & K_LNG_MASK)
339         {
340                 if (now - start > ms_to_ticks(KBD_LNG_DELAY))
341                         key |= K_LONG;
342         }
343         else
344                 start = now;
345         return key;
346 }
347 #endif
348
349 /**
350  * Set current mask of repeatable keys.
351  */
352 keymask_t kbd_setRepeatMask(keymask_t mask)
353 {
354         keymask_t oldmask = kbd_rpt_mask;
355         ATOMIC(kbd_rpt_mask = mask);
356         return oldmask;
357 }
358
359 /**
360  * Handle keyboard repeat
361  */
362 static keymask_t kbd_rptHandlerFunc(keymask_t key)
363 {
364         /* Timer for keyboard repeat events. */
365         static ticks_t repeat_time;
366
367         /* Current repeat rate (for acceleration). */
368         static ticks_t repeat_rate; /** Current repeat rate (for acceleration) */
369
370         ticks_t now = timer_clock();
371
372         switch (kbd_rptStatus)
373         {
374                 case KS_IDLE:
375                         if (key & kbd_rpt_mask)
376                         {
377                                 repeat_time = now;
378                                 kbd_rptStatus = KS_REPDELAY;
379                         }
380                         break;
381
382                 case KS_REPDELAY:
383                         if (key & kbd_rpt_mask)
384                         {
385                                 if (now - repeat_time > ms_to_ticks(KBD_REPEAT_DELAY))
386                                 {
387                                         key = (key & kbd_rpt_mask) | K_REPEAT;
388                                         repeat_time = now;
389                                         repeat_rate = ms_to_ticks(KBD_REPEAT_RATE);
390                                         kbd_rptStatus = KS_REPEAT;
391                                 }
392                                 else
393                                         key = 0;
394                         }
395                         else
396                                 kbd_rptStatus = KS_IDLE;
397                         break;
398
399                 case KS_REPEAT:
400                         if (key & kbd_rpt_mask)
401                         {
402                                 if (now - repeat_time > repeat_rate)
403                                 {
404                                         /* Enqueue a new event in the buffer */
405                                         key = (key & kbd_rpt_mask) | K_REPEAT;
406                                         repeat_time = now;
407
408                                         /* Repeat rate acceleration */
409                                         if (repeat_rate > ms_to_ticks(KBD_REPEAT_MAXRATE))
410                                                 repeat_rate -= ms_to_ticks(KBD_REPEAT_ACCEL);
411                                 }
412                                 else
413                                         key = 0;
414                         }
415                         else
416                                 kbd_rptStatus = KS_IDLE;
417
418                         break;
419         }
420
421         return key;
422 }
423
424
425 MOD_DEFINE(kbd)
426
427 /**
428  * Initialize keyboard ports and softtimer
429  */
430 void kbd_init(void)
431 {
432 #if CONFIG_KBD_BEEP
433         MOD_CHECK(buzzer);
434 #endif
435
436         KBD_HW_INIT;
437
438         /* Init handlers lists */
439         LIST_INIT(&kbd_handlers);
440         LIST_INIT(&kbd_rawHandlers);
441
442         /* Add debounce keyboard handler */
443         kbd_debHandler.hook = kbd_debHandlerFunc;
444         kbd_debHandler.pri = 100; /* high priority */
445         kbd_debHandler.flags = KHF_RAWKEYS;
446         kbd_addHandler(&kbd_debHandler);
447
448         #if CONFIG_KBD_LONGPRESS
449         /* Add long pression keyboard handler */
450         kbd_lngHandler.hook = kbd_lngHandlerFunc;
451         kbd_lngHandler.pri = 90; /* high priority */
452         kbd_lngHandler.flags = KHF_RAWKEYS;
453         kbd_addHandler(&kbd_lngHandler);
454         #endif
455
456         /* Add repeat keyboard handler */
457         kbd_rptHandler.hook = kbd_rptHandlerFunc;
458         kbd_rptHandler.pri = 80; /* high priority */
459         kbd_rptHandler.flags = KHF_RAWKEYS;
460         kbd_addHandler(&kbd_rptHandler);
461
462         /* Add default keyboard handler */
463         kbd_defHandler.hook = kbd_defHandlerFunc;
464         kbd_defHandler.pri = -128; /* lowest priority */
465         kbd_addHandler(&kbd_defHandler);
466
467 #if CONFIG_KBD_OBSERVER
468         observer_InitSubject(&kbd_subject);
469 #endif
470
471 #if CONFIG_KBD_POLL == KBD_POLL_SOFTINT
472
473         MOD_CHECK(timer);
474
475         /* Add kbd handler to soft timers list */
476         event_initSoftInt(&kbd_timer.expire, kbd_softint, NULL);
477         timer_setDelay(&kbd_timer, ms_to_ticks(KBD_CHECK_INTERVAL));
478         timer_add(&kbd_timer);
479
480 #else
481         #error "Define keyboard poll method"
482
483 #endif
484
485         MOD_INIT(kbd);
486 }