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