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