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