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