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