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