Usage examples of MAKE_CMD.
[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.6  2006/09/20 13:54:04  marco
20  *#* Usage examples of MAKE_CMD.
21  *#*
22  *#* Revision 1.5  2006/06/14 01:03:01  marco
23  *#* Add response code. Add command ping.
24  *#*
25  *#* Revision 1.4  2006/06/14 00:26:48  marco
26  *#* Use new macros for defining commands.
27  *#*
28  *#* Revision 1.3  2006/06/13 19:07:31  marco
29  *#* Fixed a bug in protocol_reply. Simplified rpc.
30  *#*
31  *#* Revision 1.2  2006/06/12 21:37:02  marco
32  *#* implemented some commands (ver and sleep)
33  *#*
34  *#* Revision 1.1  2006/06/01 12:29:21  marco
35  *#* Add first simple protocol command (version request).
36  *#*
37  *#*/
38
39 #include "protocol.h"
40
41 #include <drv/ser.h>
42 #include <drv/timer.h>
43 #include <mware/readline.h>
44 #include <mware/parser.h>
45 #include <cfg/compiler.h>
46 #include <cfg/debug.h>
47 #include <verstag.h>
48
49 #include <stdlib.h>
50 #include <string.h>
51
52 //#include <cmd_hunk.h>
53
54 #include "cmd_ctor.h"  // MAKE_CMD, REGISTER_CMD
55
56 // DEBUG: set to 1 to force interactive mode
57 #define FORCE_INTERACTIVE         1
58
59 /**
60  * True if we are in interactive mode, false if we are in protocol mode.
61  * In interactive mode, commands are read through readline() (prompt,
62  * completion, history) without IDs, and replies/errors are sent to the serial
63  * output.
64  * In protocol mode, we implement the default protocol
65  */
66 static bool interactive;
67
68 /// Readline context, used for interactive mode.
69 static struct RLContext rl_ctx;
70
71
72 /**
73  * Send a NAK asking the host to send the current message again.
74  *
75  * \param err  human-readable description of the error for debug purposes.
76  */
77 INLINE void NAK(Serial *ser, const char *err)
78 {
79 #ifdef _DEBUG
80         ser_printf(ser, "NAK \"%s\"\r\n", err);
81 #else
82         ser_printf(ser, "NAK\r\n");
83 #endif
84 }
85
86 /*
87  * Print args on s, with format specified in t->result_fmt.
88  * Return number of valid arguments or -1 in case of error.
89  */
90 static bool protocol_reply(Serial *s, const struct CmdTemplate *t,
91                           const parms *args)
92 {
93         unsigned short offset = strlen(t->arg_fmt) + 1;
94         unsigned short nres = strlen(t->result_fmt);
95
96         ser_printf(s, "0");
97         for (unsigned short i = 0; i < nres; ++i)
98         {
99                 if (t->result_fmt[i] == 'd')
100                 {
101                         ser_printf(s, " %ld", args[offset+i].l);
102                 }
103                 else if (t->result_fmt[i] == 's')
104                 {
105                         ser_printf(s, " %s", args[offset+i].s);
106                 }
107                 else
108                 {
109                         abort();
110                 }
111         }
112         ser_printf(s, "\r\n");
113         return true;
114 }
115
116 static void protocol_parse(Serial *ser, const char *buf)
117 {
118         const struct CmdTemplate *templ;
119
120         /* Command check.  */
121         templ = parser_get_cmd_template(buf);
122         if (!templ)
123         {
124                 ser_print(ser, "-1 Invalid command.");
125                 return;
126         }
127
128         parms args[PARSER_MAX_ARGS];
129
130         /* Args Check.  TODO: Handle different case. see doc/PROTOCOL .  */
131         if (!parser_get_cmd_arguments(buf, templ, args))
132         {
133                 ser_print(ser, "-2 Invalid arguments.");
134                 return;
135         }
136
137         /* Execute. */
138         if(!parser_execute_cmd(templ, args))
139         {
140                 NAK(ser, "Error in executing command.");
141         }
142         if (!protocol_reply(ser, templ, args))
143         {
144                 NAK(ser, "Invalid return format.");
145         }
146         return;
147 }
148
149 void protocol_run(Serial *ser)
150 {
151         /**
152          * \todo to be removed, we could probably access the serial FIFO
153          * directly
154          */
155         static char linebuf[80];
156
157         if (!interactive)
158         {
159                 ser_gets(ser, linebuf, sizeof(linebuf));
160
161                 // reset serial port error anyway
162                 ser_setstatus(ser, 0);
163
164                 // check message minimum length
165                 if (linebuf[0])
166                 {
167                         if (linebuf[0] == 0x1B && linebuf[1] == 0x1B)  // ESC
168                         {
169                                 interactive = true;
170                                 ser_printf(ser,
171                                            "Entering interactive mode\r\n");
172                         }
173                         else
174                         {
175                                 protocol_parse(ser, linebuf);
176                         }
177                 }
178         }
179         else
180         {
181                 const char *buf;
182
183                 /*
184                  * Read a line from serial. We use a temporary buffer
185                  * because otherwise we would have to extract a message
186                  * from the port immediately: there might not be any
187                  * available, and one might get free while we read
188                  * the line. We also add a fake ID at the start to
189                  * fool the parser.
190                  */
191                 buf = rl_readline(&rl_ctx);
192
193                 if (buf && buf[0] != '\0')
194                 {
195                         // exit special case to immediately change serial input
196                         if (!strcmp(buf, "exit") || !strcmp(buf, "quit"))
197                         {
198                                 rl_clear_history(&rl_ctx);
199                                 ser_printf(ser,
200                                            "Leaving interactive mode...\r\n");
201                                 interactive = FORCE_INTERACTIVE;
202                         }
203                         else
204                         {
205                                 //TODO: remove sequence numbers
206                                 linebuf[0] = '0';
207                                 linebuf[1] = ' ';
208
209                                 strncpy(linebuf + 2, buf, sizeof(linebuf) - 3);
210                                 linebuf[sizeof(linebuf) - 1] = '\0';
211                                 protocol_parse(ser, linebuf);
212                         }
213                 }
214         }
215 }
216
217 /*
218  * Commands.
219  * TODO: Command declarations and definitions should be in another file(s).
220  * Maybe we should use CMD_HUNK_TEMPLATE.
221  *
222  */
223
224 /* Version. Example of declaring function and passing it to MAKE_CMD.  */
225 static int ver_fn(const char **str)
226 {
227         *str = VERS_TAG;
228         return 0;
229 }
230 MAKE_CMD(ver, "", "s", ver_fn(&args[1].s))
231
232 /* Sleep. Example of declaring function body directly in macro call.  */
233 MAKE_CMD(sleep, "d", "",
234 ({
235         timer_delay((mtime_t)args[1].l);
236         0;
237 }))
238
239 /* Ping.  */
240 MAKE_CMD(ping, "", "",
241 ({
242         0;
243 }))
244
245 /* Register commands.  */
246 static void protocol_registerCmds(void)
247 {
248         REGISTER_CMD(ver);
249         REGISTER_CMD(sleep);
250         REGISTER_CMD(ping);
251 }
252
253 /* Initialization: readline context, parser and register commands.  */
254 void protocol_init(Serial *ser)
255 {
256         interactive = FORCE_INTERACTIVE;
257
258         rl_init_ctx(&rl_ctx);
259         rl_setprompt(&rl_ctx, ">> ");
260         rl_sethook_get(&rl_ctx, (getc_hook)ser_getchar, ser);
261         rl_sethook_put(&rl_ctx, (putc_hook)ser_putchar, ser);
262         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
263
264         parser_init();
265
266         protocol_registerCmds();
267 }