Introduce old redir program
[lcapit-junk-code.git] / linux-kernel / fake-serial / user-land / fsemul.c
blob8022e21c5f70285f00fd5a73836e24ce183d9fad
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <assert.h>
5 #include <readline/readline.h>
6 #include <readline/history.h>
8 #define ULCMD_PROMPT "ulcmd>>> "
9 #define FAKE_DEV_IBUFF_LEN 12
10 #define END_CMD_CHAR '%'
12 struct fake_device {
13 char *ibuf;
14 char *lresult;
15 int idx;
16 size_t len;
19 static char *responses[] = {
20 "AT+A: hehehe\r",
21 "AT+AB: muuu\r",
22 "AT+FOO: bar\n",
23 NULL
26 static char *commands[] = {
27 "AT+A%",
28 "AT+AB%",
29 "AT+FOO%",
30 NULL
33 static char *command_error = "ERROR: sua mula\r";
35 static void fake_device_rst_counters(struct fake_device *fake, int print_msg)
37 if (print_msg)
38 printf("-> Resetting counters\n");
39 fake->idx = 0;
40 fake->len = FAKE_DEV_IBUFF_LEN;
43 static int fake_device_init(struct fake_device *fake, int print_msg)
45 fake_device_rst_counters(fake, print_msg);
46 fake->lresult = NULL;
47 fake->ibuf = malloc(fake->len);
48 if (!fake->ibuf)
49 return -1;
50 return 0;
53 static void fake_device_del(struct fake_device *fake)
55 free(fake->ibuf);
58 static void fake_device_ibuf_dump(struct fake_device *fake, FILE *stream)
60 char *p;
62 if (!fake->idx) {
63 fprintf(stream, "-> ibuf dump: Nothing to dump.\n");
64 return;
67 fprintf(stream, "-> ibuf dump:\n");
69 for (p = fake->ibuf; (p - fake->ibuf) < fake->idx; p++)
70 fprintf(stream, "--> (%ld) 0x%x %c\n", p - fake->ibuf, *p, *p);
72 fprintf(stream, "--> idx: %d | len: %d\n", fake->idx, (int) fake->len);
75 static int fake_device_handler(struct fake_device *fake)
77 char *p;
78 int i, found = 0;
80 for (p = fake->ibuf; (p - fake->ibuf) < fake->idx; p++)
81 if (*p == END_CMD_CHAR) {
82 found = 1;
83 break;
86 if (!found) {
87 if (!fake->len)
88 fake_device_rst_counters(fake, 1);
89 return 0;
93 * End of a command has been found
96 for (i = 0; commands[i]; i++)
97 if (!strncmp(fake->ibuf, commands[i],
98 (size_t) (p - fake->ibuf) + 1)) {
99 fake->lresult = responses[i];
100 goto out;
103 /* No valid command found */
104 fake->lresult = command_error;
105 out:
106 fake_device_rst_counters(fake, 1);
107 return 1;
110 int main(void)
112 int ret;
113 char *line;
114 size_t line_len;
115 struct fake_device fake;
117 fake_device_init(&fake, 0);
119 for (;;) {
120 line = readline(ULCMD_PROMPT);
121 if (!line) {
122 printf("\nExiting...\n");
123 return 0;
125 printf("-> Line read is: %s\n", line);
127 line_len = strlen(line);
128 strncpy(fake.ibuf + fake.idx, line, fake.len);
129 if (line_len > fake.len) {
130 fake.idx += fake.len;
131 fake.len = 0;
132 } else {
133 fake.idx += line_len;
134 fake.len -= line_len;
137 fake_device_ibuf_dump(&fake, stdout);
138 ret = fake_device_handler(&fake);
139 if (ret) {
140 assert(fake.lresult != NULL);
141 printf("-> Command response: %s\n", fake.lresult);
142 fake.lresult = NULL;
146 fake_device_del(&fake);
147 return 0;