implemented some commands (ver and sleep)
[bertos.git] / app / triface / protocol.c
1 /**
2  * \file
3  * <!--
4  * Copyright 2006 Develer S.r.l. (http://www.develer.com/)
5  * -->
6  *
7  * \brief Implementation of the command protocol between the board and the host
8  *
9  *
10  * \version $Id$
11  *
12  * \author Giovanni Bajo <rasky@develer.com>
13  * \author Marco Benelli <marco@develer.com>
14  * \author Bernardo Innocenti <bernie@develer.com>
15  */
16
17 /*#*
18  *#* $Log$
19  *#* Revision 1.2  2006/06/12 21:37:02  marco
20  *#* implemented some commands (ver and sleep)
21  *#*
22  *#* Revision 1.1  2006/06/01 12:29:21  marco
23  *#* Add first simple protocol command (version request).
24  *#*
25  *#*/
26
27 #include "protocol.h"
28
29 #include <drv/ser.h>
30 #include <drv/timer.h>
31 #include <mware/readline.h>
32 #include <mware/parser.h>
33 #include <cfg/compiler.h>
34 #include <cfg/debug.h>
35 #include <verstag.h>
36
37 #include <stdlib.h> /* malloc()
38                        TODO: substitute with a more appropriate
39                        memory allocator. */
40
41 #include <string.h>
42
43 #include <cmd_hunk.h>
44
45
46 // DEBUG: set to 1 to force interactive mode
47 #define FORCE_INTERACTIVE         1
48
49 /**
50  * True if we are in interactive mode, false if we are in protocol mode.
51  * In interactive mode, commands are read through readline() (prompt,
52  * completion, history) without IDs, and replies/errors are sent to the serial
53  * output.
54  * In protocol mode, we implement the default protocol
55  */
56 static bool interactive;
57
58 /// Readline context, used for interactive mode.
59 static struct RLContext rl_ctx;
60
61
62 /**
63  * Send a NAK asking the host to send the current message again.
64  *
65  * \param err  human-readable description of the error for debug purposes.
66  */
67 INLINE void NAK(Serial *ser, const char *err)
68 {
69 #ifdef _DEBUG
70         ser_printf(ser, "NAK \"%s\"\r\n", err);
71 #else
72         ser_printf(ser, "NAK\r\n");
73 #endif
74 }
75
76 /*
77  * Print args on s, with format specified in t->result_fmt.
78  * Return number of valid arguments or -1 in case of error.
79  */
80 static int protocol_reply(Serial *s, const struct CmdTemplate *t,
81                           const parms *args)
82 {
83         int nres = strlen(t->result_fmt);
84
85         if (nres > 0)
86         {
87                 for (int i = strlen(t->arg_fmt); i < nres; ++i)
88                 {
89                         if (t->result_fmt[i] == 'd')
90                         {
91                                 ser_printf(s, "%ld", args[i].l);
92                         }
93                         else if (t->result_fmt[i] == 's')
94                         {
95                                 ser_printf(s, "%s ", args[i].s);
96                         }
97                         else
98                         {
99                                 return -1;
100                         }
101                 }
102         }
103         ser_print(s, "\r\n");
104         return nres;
105 }
106
107 static void protocol_parse(Serial *ser, const char *buf)
108 {
109         const struct CmdTemplate *templ;
110
111         /* Command check.  */
112         templ = parser_get_cmd_template(buf);
113         if (!templ)
114         {
115                 NAK(ser, "Invalid command.");
116                 return;
117         }
118
119         parms args[PARSER_MAX_ARGS];
120
121         /* Args Check.  */
122         if (!parser_get_cmd_arguments(buf, templ, args))
123         {
124                 NAK(ser, "Invalid arguments.");
125                 return;
126         }
127
128         /* Execute. */
129         if (!parser_execute_cmd(templ, args))
130         {
131                 NAK(ser, "Command failed.");
132         }
133         else
134         {
135                 if (protocol_reply(ser, templ, args) < 0)
136                 {
137                         NAK(ser, "Invalid return format.");
138                 }
139         }
140         return;
141 }
142
143 void protocol_run(Serial *ser)
144 {
145         /**
146          * \todo to be removed, we could probably access the serial FIFO
147          * directly
148          */
149         static char linebuf[80];
150
151         if (!interactive)
152         {
153                 ser_gets(ser, linebuf, sizeof(linebuf));
154
155                 // reset serial port error anyway
156                 ser_setstatus(ser, 0);
157
158                 // check message minimum length
159                 if (linebuf[0])
160                 {
161                         if (linebuf[0] == 0x1B && linebuf[1] == 0x1B)  // ESC
162                         {
163                                 interactive = true;
164                                 ser_printf(ser,
165                                            "Entering interactive mode\r\n");
166                         }
167                         else
168                         {
169                                 protocol_parse(ser, linebuf);
170                         }
171                 }
172         }
173         else
174         {
175                 const char *buf;
176
177                 /*
178                  * Read a line from serial. We use a temporary buffer
179                  * because otherwise we would have to extract a message
180                  * from the port immediately: there might not be any
181                  * available, and one might get free while we read
182                  * the line. We also add a fake ID at the start to
183                  * fool the parser.
184                  */
185                 buf = rl_readline(&rl_ctx);
186
187                 if (buf && buf[0] != '\0')
188                 {
189                         // exit special case to immediately change serial input
190                         if (!strcmp(buf, "exit") || !strcmp(buf, "quit"))
191                         {
192                                 rl_clear_history(&rl_ctx);
193                                 ser_printf(ser,
194                                            "Leaving interactive mode...\r\n");
195                                 interactive = FORCE_INTERACTIVE;
196                         }
197                         else
198                         {
199                                 //TODO: remove sequence numbers
200                                 linebuf[0] = '0';
201                                 linebuf[1] = ' ';
202
203                                 strncpy(linebuf + 2, buf, sizeof(linebuf) - 3);
204                                 linebuf[sizeof(linebuf) - 1] = '\0';
205                                 protocol_parse(ser, linebuf);
206                         }
207                 }
208         }
209 }
210
211 /*
212  * Commands.
213  * TODO: Command declarations and definitions should be in another file(s).
214  * Maybe we should use CMD_HUNK_TEMPLATE.
215  *
216  */
217
218 /* Version.  */
219 static ResultCode cmd_ver(const char **str)
220 {
221         *str = VERS_TAG;
222         return 0;
223 }
224 static ResultCode cmd_ver_hunk(parms args_results[])
225 {
226         return cmd_ver(&args_results[0].s);
227 }
228
229 const struct CmdTemplate cmd_ver_template =
230 {
231         "ver", "", "s", cmd_ver_hunk, 0
232 };
233
234 //DECLARE_CMD_HUNK(ver, (NIL), (string)(NIL));
235
236 /* Sleep.  */
237
238 static ResultCode cmd_sleep(const long ms)
239 {
240         timer_delay((mtime_t)ms);
241         return 0;
242 }
243
244 static ResultCode cmd_sleep_hunk(parms args[])
245 {
246         return cmd_sleep(args[1].l);
247 }
248
249 const struct CmdTemplate cmd_sleep_template =
250 {
251         "sleep", "d", "", cmd_sleep_hunk, 0
252 };
253
254 /* Register commands.  */
255 static void protocol_registerCmds(void)
256 {
257 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(quit));
258 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(exit));
259 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(wait));
260 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(delay));
261 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(SYN));
262 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(RST));
263 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(skip_end));
264 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(restart));
265 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(ver));
266 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(power_off));
267
268         parser_register_cmd(&cmd_ver_template);
269         parser_register_cmd(&cmd_sleep_template);
270 }
271 void protocol_init(Serial *ser)
272 {
273         interactive = FORCE_INTERACTIVE;
274
275         // Initialize the readline context used for interactive mode
276         rl_init_ctx(&rl_ctx);
277         rl_setprompt(&rl_ctx, ">> ");
278         rl_sethook_get(&rl_ctx, (getc_hook)ser_getchar, ser);
279         rl_sethook_put(&rl_ctx, (putc_hook)ser_putchar, ser);
280         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
281
282         parser_init();
283
284         protocol_registerCmds();
285 }