basic terminal
[cortex-from-scratch] / term.c
1 #include <stdbool.h>
2 #include <stddef.h>
3 #include <stdint.h>
4 #include <stm32.h>
5 #include <mmap.h>
6
7 #define SERIAL 1
8 #define BUFSIZE 256
9
10 static char buf[BUFSIZE];
11
12 /* Abstraction layer for I/O communication */
13
14 char getchar(void) {
15         char c;
16         if (SERIAL) {
17                  while ((c = uart_getc()) == 0);
18                 /* do nothing */
19         }
20         return c;
21 }
22
23 void cputchar(char c) {
24
25         if (SERIAL) {
26                 uart_putc(c);
27         }
28
29 }
30
31 void cputs(unsigned char *str) {
32      
33      int i;
34      for (i = 0; i < strlen(str); i++)     {
35          cputchar(str[i]);
36     }
37
38 }
39
40 void terminal() {
41  
42         char *buf;
43         cputs("Terminal running!\n");
44  
45          while (1) {
46                  buf = readline("> ");
47                  /* if (buf != NULL)
48                          if (runcmd(buf, tf) < 0)
49                                  break; */
50          }
51 }
52
53 char * readline(char *prompt)
54 {
55         int i, c, echoing;
56
57         if (prompt != NULL)
58                 cputs(prompt); 
59
60         i = 0;
61         echoing = 1;
62         while (1) {
63                 c = getchar();
64                 if (c < 0) {
65                         cputs("read error");
66                         return NULL;
67                 } else if ((c == '\b' || c == '\x7f') && i > 0) {
68                         if (echoing)
69                                 cputchar('\b');
70                         i--;
71                 } else if (c >= ' ' && i < BUFSIZE-1) {
72                         if (echoing)
73                                 cputchar(c);
74                         buf[i++] = c;
75                 } else if (c == '\n' || c == '\r') {
76                         if (echoing)
77                                 cputchar('\n');
78                         buf[i] = 0;
79                         return buf;
80                 }
81         }
82 }