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