Fixed a bug in protocol_reply. Simplified rpc.
[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.3  2006/06/13 19:07:31  marco
20  *#* Fixed a bug in protocol_reply. Simplified rpc.
21  *#*
22  *#* Revision 1.2  2006/06/12 21:37:02  marco
23  *#* implemented some commands (ver and sleep)
24  *#*
25  *#* Revision 1.1  2006/06/01 12:29:21  marco
26  *#* Add first simple protocol command (version request).
27  *#*
28  *#*/
29
30 #include "protocol.h"
31
32 #include <drv/ser.h>
33 #include <drv/timer.h>
34 #include <mware/readline.h>
35 #include <mware/parser.h>
36 #include <cfg/compiler.h>
37 #include <cfg/debug.h>
38 #include <verstag.h>
39
40 #include <string.h>
41
42 #include <cmd_hunk.h>
43
44
45 // DEBUG: set to 1 to force interactive mode
46 #define FORCE_INTERACTIVE         1
47
48 /**
49  * True if we are in interactive mode, false if we are in protocol mode.
50  * In interactive mode, commands are read through readline() (prompt,
51  * completion, history) without IDs, and replies/errors are sent to the serial
52  * output.
53  * In protocol mode, we implement the default protocol
54  */
55 static bool interactive;
56
57 /// Readline context, used for interactive mode.
58 static struct RLContext rl_ctx;
59
60
61 /**
62  * Send a NAK asking the host to send the current message again.
63  *
64  * \param err  human-readable description of the error for debug purposes.
65  */
66 INLINE void NAK(Serial *ser, const char *err)
67 {
68 #ifdef _DEBUG
69         ser_printf(ser, "NAK \"%s\"\r\n", err);
70 #else
71         ser_printf(ser, "NAK\r\n");
72 #endif
73 }
74
75 /*
76  * Print args on s, with format specified in t->result_fmt.
77  * Return number of valid arguments or -1 in case of error.
78  */
79 static int protocol_reply(Serial *s, const struct CmdTemplate *t,
80                           const parms *args)
81 {
82         unsigned short offset = strlen(t->arg_fmt) + 1;
83         unsigned short nres = strlen(t->result_fmt);
84
85         if (nres > 0)
86         {
87                 for (unsigned short i = 0; i < nres; ++i)
88                 {
89                         if (t->result_fmt[i] == 'd')
90                         {
91                                 ser_printf(s, "%ld", args[offset+i].l);
92                         }
93                         else if (t->result_fmt[i] == 's')
94                         {
95                                 ser_printf(s, "%s ", args[offset+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
220
221 static ResultCode cmd_ver(parms *args)
222 {
223         args[1].s = VERS_TAG;
224         return 0;
225 }
226 const struct CmdTemplate cmd_ver_template =
227 {
228         "ver", "", "s", cmd_ver, 0
229 };
230
231 /* Sleep.  */ 
232
233 static ResultCode cmd_sleep(parms *args)
234 {
235         timer_delay((mtime_t)args[1].l);
236         return 0;
237 }
238 const struct CmdTemplate cmd_sleep_template =
239 {
240         "sleep", "d", "", cmd_sleep, 0
241 };
242
243 /* Register commands.  */
244 static void protocol_registerCmds(void)
245 {
246 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(quit));
247 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(exit));
248 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(wait));
249 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(delay));
250 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(SYN));
251 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(RST));
252 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(skip_end));
253 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(restart));
254 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(ver));
255 //      parser_register_cmd(&CMD_HUNK_TEMPLATE(power_off));
256
257         parser_register_cmd(&cmd_ver_template);
258         parser_register_cmd(&cmd_sleep_template);
259 }
260 void protocol_init(Serial *ser)
261 {
262         interactive = FORCE_INTERACTIVE;
263
264         // Initialize the readline context used for interactive mode
265         rl_init_ctx(&rl_ctx);
266         rl_setprompt(&rl_ctx, ">> ");
267         rl_sethook_get(&rl_ctx, (getc_hook)ser_getchar, ser);
268         rl_sethook_put(&rl_ctx, (putc_hook)ser_putchar, ser);
269         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
270
271         parser_init();
272
273         protocol_registerCmds();
274 }