altos: Massive product config cleanup
[fw/altos] / src / core / ao_stdio.c
1 /*
2  * Copyright © 2009 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; version 2 of the License.
7  *
8  * This program is distributed in the hope that it will be useful, but
9  * WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11  * General Public License for more details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
16  */
17
18 #include "ao.h"
19
20 /*
21  * Basic I/O functions to support SDCC stdio package
22  */
23
24 #ifdef SERIAL_STDIN_PORT
25 #define USE_SERIAL_STDIN 1
26 #else
27 #define USE_SERIAL_STDIN 0
28 #endif
29
30 #define AO_NUM_STDIOS   (HAS_USB + PACKET_HAS_SLAVE + USE_SERIAL_STDIN)
31
32 __xdata struct ao_stdio ao_stdios[AO_NUM_STDIOS];
33 __pdata int8_t ao_cur_stdio;
34 __pdata int8_t ao_num_stdios;
35
36 void
37 putchar(char c)
38 {
39 #if LOW_LEVEL_DEBUG
40         if (!ao_cur_task) {
41                 extern void ao_debug_out(char c);
42                 if (c == '\n')
43                         ao_debug_out('\r');
44                 ao_debug_out(c);
45                 return;
46         }
47 #endif
48         if (c == '\n')
49                 (*ao_stdios[ao_cur_stdio].putchar)('\r');
50         (*ao_stdios[ao_cur_stdio].putchar)(c);
51 }
52
53 void
54 flush(void)
55 {
56         if (ao_stdios[ao_cur_stdio].flush)
57                 ao_stdios[ao_cur_stdio].flush();
58 }
59
60 __xdata uint8_t ao_stdin_ready;
61
62 char
63 getchar(void) __reentrant __critical
64 {
65         char c;
66         int8_t stdio = ao_cur_stdio;
67
68         for (;;) {
69                 c = ao_stdios[stdio].pollchar();
70                 if (c != AO_READ_AGAIN)
71                         break;
72                 if (++stdio == ao_num_stdios)
73                         stdio = 0;
74                 if (stdio == ao_cur_stdio)
75                         ao_sleep(&ao_stdin_ready);
76         }
77         ao_cur_stdio = stdio;
78         return c;
79 }
80
81 uint8_t
82 ao_echo(void)
83 {
84         return ao_stdios[ao_cur_stdio].echo;
85 }
86
87 int8_t
88 ao_add_stdio(char (*pollchar)(void),
89              void (*putchar)(char),
90              void (*flush)(void)) __reentrant
91 {
92         if (ao_num_stdios == AO_NUM_STDIOS)
93                 ao_panic(AO_PANIC_STDIO);
94         ao_stdios[ao_num_stdios].pollchar = pollchar;
95         ao_stdios[ao_num_stdios].putchar = putchar;
96         ao_stdios[ao_num_stdios].flush = flush;
97         ao_stdios[ao_num_stdios].echo = 1;
98         return ao_num_stdios++;
99 }