17274e2290fe9239e464d808c7eef00bb492dd20
[litex.git] / litex / soc / misoc / software / libbase / console.c
1 #include <uart.h>
2 #include <console.h>
3 #include <stdio.h>
4 #include <stdarg.h>
5
6 FILE *stdin, *stdout, *stderr;
7
8 static console_write_hook write_hook;
9 static console_read_hook read_hook;
10 static console_read_nonblock_hook read_nonblock_hook;
11
12 void console_set_write_hook(console_write_hook h)
13 {
14 write_hook = h;
15 }
16
17 void console_set_read_hook(console_read_hook r, console_read_nonblock_hook rn)
18 {
19 read_hook = r;
20 read_nonblock_hook = rn;
21 }
22
23 int putchar(int c)
24 {
25 uart_write(c);
26 if(write_hook != NULL)
27 write_hook(c);
28 return c;
29 }
30
31 char readchar(void)
32 {
33 while(1) {
34 if(uart_read_nonblock())
35 return uart_read();
36 if((read_nonblock_hook != NULL) && read_nonblock_hook())
37 return read_hook();
38 }
39 }
40
41 int readchar_nonblock(void)
42 {
43 return (uart_read_nonblock()
44 || ((read_nonblock_hook != NULL) && read_nonblock_hook()));
45 }
46
47 int puts(const char *s)
48 {
49 while(*s) {
50 putchar(*s);
51 s++;
52 }
53 putchar('\n');
54 return 1;
55 }
56
57 void putsnonl(const char *s)
58 {
59 while(*s) {
60 putchar(*s);
61 s++;
62 }
63 }
64
65 #define PRINTF_BUFFER_SIZE 256
66
67 int printf(const char *fmt, ...)
68 {
69 va_list args;
70 int len;
71 char outbuf[PRINTF_BUFFER_SIZE];
72
73 va_start(args, fmt);
74 len = vscnprintf(outbuf, sizeof(outbuf), fmt, args);
75 va_end(args);
76 outbuf[len] = 0;
77 putsnonl(outbuf);
78
79 return len;
80 }