Updated copiright notice.
[bertos.git] / app / triface / protocol.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2006 Develer S.r.l. (http://www.develer.com/)
30  * -->
31  *
32  * \brief Implementation of the command protocol between the board and the host
33  *
34  *
35  * \version $Id$
36  *
37  * \author Giovanni Bajo <rasky@develer.com>
38  * \author Marco Benelli <marco@develer.com>
39  * \author Bernardo Innocenti <bernie@develer.com>
40  */
41
42 /*#*
43  *#* $Log$
44  *#* Revision 1.7  2007/01/09 09:00:16  bernie
45  *#* Doxygen fix.
46  *#*
47  *#* Revision 1.6  2006/09/20 13:54:04  marco
48  *#* Usage examples of MAKE_CMD.
49  *#*
50  *#* Revision 1.5  2006/06/14 01:03:01  marco
51  *#* Add response code. Add command ping.
52  *#*
53  *#* Revision 1.4  2006/06/14 00:26:48  marco
54  *#* Use new macros for defining commands.
55  *#*
56  *#* Revision 1.3  2006/06/13 19:07:31  marco
57  *#* Fixed a bug in protocol_reply. Simplified rpc.
58  *#*
59  *#* Revision 1.2  2006/06/12 21:37:02  marco
60  *#* implemented some commands (ver and sleep)
61  *#*
62  *#* Revision 1.1  2006/06/01 12:29:21  marco
63  *#* Add first simple protocol command (version request).
64  *#*
65  *#*/
66
67 #include "protocol.h"
68
69 #include <drv/ser.h>
70 #include <drv/timer.h>
71 #include <mware/readline.h>
72 #include <mware/parser.h>
73 #include <cfg/compiler.h>
74 #include <cfg/debug.h>
75 #include <verstag.h>
76
77 #include <stdlib.h>
78 #include <string.h>
79
80 //#include <cmd_hunk.h>
81
82 #include "cmd_ctor.h"  // MAKE_CMD, REGISTER_CMD
83
84 // DEBUG: set to 1 to force interactive mode
85 #define FORCE_INTERACTIVE         1
86
87 /**
88  * True if we are in interactive mode, false if we are in protocol mode.
89  * In interactive mode, commands are read through readline() (prompt,
90  * completion, history) without IDs, and replies/errors are sent to the serial
91  * output.
92  * In protocol mode, we implement the default protocol
93  */
94 static bool interactive;
95
96 /// Readline context, used for interactive mode.
97 static struct RLContext rl_ctx;
98
99
100 /**
101  * Send a NAK asking the host to send the current message again.
102  *
103  * \param ser  serial port handle to output to.
104  * \param err  human-readable description of the error for debug purposes.
105  */
106 INLINE void NAK(Serial *ser, const char *err)
107 {
108 #ifdef _DEBUG
109         ser_printf(ser, "NAK \"%s\"\r\n", err);
110 #else
111         ser_printf(ser, "NAK\r\n");
112 #endif
113 }
114
115 /*
116  * Print args on s, with format specified in t->result_fmt.
117  * Return number of valid arguments or -1 in case of error.
118  */
119 static bool protocol_reply(Serial *s, const struct CmdTemplate *t,
120                           const parms *args)
121 {
122         unsigned short offset = strlen(t->arg_fmt) + 1;
123         unsigned short nres = strlen(t->result_fmt);
124
125         ser_printf(s, "0");
126         for (unsigned short i = 0; i < nres; ++i)
127         {
128                 if (t->result_fmt[i] == 'd')
129                 {
130                         ser_printf(s, " %ld", args[offset+i].l);
131                 }
132                 else if (t->result_fmt[i] == 's')
133                 {
134                         ser_printf(s, " %s", args[offset+i].s);
135                 }
136                 else
137                 {
138                         abort();
139                 }
140         }
141         ser_printf(s, "\r\n");
142         return true;
143 }
144
145 static void protocol_parse(Serial *ser, const char *buf)
146 {
147         const struct CmdTemplate *templ;
148
149         /* Command check.  */
150         templ = parser_get_cmd_template(buf);
151         if (!templ)
152         {
153                 ser_print(ser, "-1 Invalid command.");
154                 return;
155         }
156
157         parms args[PARSER_MAX_ARGS];
158
159         /* Args Check.  TODO: Handle different case. see doc/PROTOCOL .  */
160         if (!parser_get_cmd_arguments(buf, templ, args))
161         {
162                 ser_print(ser, "-2 Invalid arguments.");
163                 return;
164         }
165
166         /* Execute. */
167         if(!parser_execute_cmd(templ, args))
168         {
169                 NAK(ser, "Error in executing command.");
170         }
171         if (!protocol_reply(ser, templ, args))
172         {
173                 NAK(ser, "Invalid return format.");
174         }
175         return;
176 }
177
178 void protocol_run(Serial *ser)
179 {
180         /**
181          * \todo to be removed, we could probably access the serial FIFO
182          * directly
183          */
184         static char linebuf[80];
185
186         if (!interactive)
187         {
188                 ser_gets(ser, linebuf, sizeof(linebuf));
189
190                 // reset serial port error anyway
191                 ser_setstatus(ser, 0);
192
193                 // check message minimum length
194                 if (linebuf[0])
195                 {
196                         if (linebuf[0] == 0x1B && linebuf[1] == 0x1B)  // ESC
197                         {
198                                 interactive = true;
199                                 ser_printf(ser,
200                                            "Entering interactive mode\r\n");
201                         }
202                         else
203                         {
204                                 protocol_parse(ser, linebuf);
205                         }
206                 }
207         }
208         else
209         {
210                 const char *buf;
211
212                 /*
213                  * Read a line from serial. We use a temporary buffer
214                  * because otherwise we would have to extract a message
215                  * from the port immediately: there might not be any
216                  * available, and one might get free while we read
217                  * the line. We also add a fake ID at the start to
218                  * fool the parser.
219                  */
220                 buf = rl_readline(&rl_ctx);
221
222                 if (buf && buf[0] != '\0')
223                 {
224                         // exit special case to immediately change serial input
225                         if (!strcmp(buf, "exit") || !strcmp(buf, "quit"))
226                         {
227                                 rl_clear_history(&rl_ctx);
228                                 ser_printf(ser,
229                                            "Leaving interactive mode...\r\n");
230                                 interactive = FORCE_INTERACTIVE;
231                         }
232                         else
233                         {
234                                 //TODO: remove sequence numbers
235                                 linebuf[0] = '0';
236                                 linebuf[1] = ' ';
237
238                                 strncpy(linebuf + 2, buf, sizeof(linebuf) - 3);
239                                 linebuf[sizeof(linebuf) - 1] = '\0';
240                                 protocol_parse(ser, linebuf);
241                         }
242                 }
243         }
244 }
245
246 /*
247  * Commands.
248  * TODO: Command declarations and definitions should be in another file(s).
249  * Maybe we should use CMD_HUNK_TEMPLATE.
250  *
251  */
252
253 /* Version. Example of declaring function and passing it to MAKE_CMD.  */
254 static int ver_fn(const char **str)
255 {
256         *str = VERS_TAG;
257         return 0;
258 }
259 MAKE_CMD(ver, "", "s", ver_fn(&args[1].s))
260
261 /* Sleep. Example of declaring function body directly in macro call.  */
262 MAKE_CMD(sleep, "d", "",
263 ({
264         timer_delay((mtime_t)args[1].l);
265         0;
266 }))
267
268 /* Ping.  */
269 MAKE_CMD(ping, "", "",
270 ({
271         0;
272 }))
273
274 /* Register commands.  */
275 static void protocol_registerCmds(void)
276 {
277         REGISTER_CMD(ver);
278         REGISTER_CMD(sleep);
279         REGISTER_CMD(ping);
280 }
281
282 /* Initialization: readline context, parser and register commands.  */
283 void protocol_init(Serial *ser)
284 {
285         interactive = FORCE_INTERACTIVE;
286
287         rl_init_ctx(&rl_ctx);
288         rl_setprompt(&rl_ctx, ">> ");
289         rl_sethook_get(&rl_ctx, (getc_hook)ser_getchar, ser);
290         rl_sethook_put(&rl_ctx, (putc_hook)ser_putchar, ser);
291         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
292
293         parser_init();
294
295         protocol_registerCmds();
296 }