Import protocol module from triface prj.
[bertos.git] / bertos / net / 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 2003, 2004, 2006 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2000 Bernie Innocenti <bernie@codewiz.org>
31  *
32  * -->
33  *
34  * \brief Implementation of the command protocol between the board and the host
35  *
36  *
37  * \author Giovanni Bajo <rasky@develer.com>
38  * \author Marco Benelli <marco@develer.com>
39  * \author Bernie Innocenti <bernie@codewiz.org>
40  * \author Daniele Basile <asterix@develer.com>
41  */
42
43 #include "protocol.h"
44 #include "verstag.h"
45
46 #include "cfg/cfg_parser.h"
47 #include <cfg/compiler.h>
48 #include <cfg/debug.h>
49
50 #include <drv/timer.h>
51 #include <drv/ser.h>
52
53 #include <mware/readline.h>
54 #include <mware/parser.h>
55
56 #include <io/kfile.h>
57
58 #include <stdlib.h>
59 #include <string.h>
60
61 // Define the format string for ADC
62 #define ADC_FORMAT_STR "dddd"
63 #define ADC_CHANNEL_NUM    4
64
65 // DEBUG: set to 1 to force interactive mode
66 #define FORCE_INTERACTIVE         1
67
68 /**
69  * True if we are in interactive mode, false if we are in protocol mode.
70  * In interactive mode, commands are read through readline() (prompt,
71  * completion, history) without IDs, and replies/errors are sent to the serial
72  * output.
73  * In protocol mode, we implement the default protocol
74  */
75 static bool interactive;
76
77 /// Readline context, used for interactive mode.
78 static struct RLContext rl_ctx;
79
80 uint8_t reg_status_dout;
81 /**
82  * Send a NAK asking the host to send the current message again.
83  *
84  * \a fd kfile handler for serial.
85  * \a err  human-readable description of the error for debug purposes.
86  */
87 INLINE void NAK(KFile *fd, const char *err)
88 {
89 #ifdef _DEBUG
90         kfile_printf(fd, "NAK \"%s\"\r\n", err);
91 #else
92         kfile_printf(fd, "NAK\r\n");
93 #endif
94 }
95
96 static void protocol_prompt(KFile *fd)
97 {
98         kfile_print(fd, ">> ");
99 }
100
101 /*
102  * Print args on s, with format specified in t->result_fmt.
103  * Return number of valid arguments or -1 in case of error.
104  */
105 static bool protocol_reply(KFile *fd, const struct CmdTemplate *t,
106                           const parms *args)
107 {
108         unsigned short offset = strlen(t->arg_fmt) + 1;
109         unsigned short nres = strlen(t->result_fmt);
110
111         for (unsigned short i = 0; i < nres; ++i)
112         {
113                 if (t->result_fmt[i] == 'd')
114                 {
115                         kfile_printf(fd, " %ld", args[offset+i].l);
116                 }
117                 else if (t->result_fmt[i] == 's')
118                 {
119                         kfile_printf(fd, " %s", args[offset+i].s);
120                 }
121
122                 else
123                 {
124                         abort();
125                 }
126         }
127         kfile_printf(fd, "\r\n");
128         return true;
129 }
130
131 static void protocol_parse(KFile *fd, const char *buf)
132 {
133         const struct CmdTemplate *templ;
134
135         /* Command check.  */
136         templ = parser_get_cmd_template(buf);
137         if (!templ)
138         {
139                 kfile_print(fd, "-1 Invalid command.\r\n");
140                 protocol_prompt(fd);
141                 return;
142         }
143
144         parms args[CONFIG_PARSER_MAX_ARGS];
145
146         /* Args Check.  TODO: Handle different case. see doc/PROTOCOL .  */
147         if (!parser_get_cmd_arguments(buf, templ, args))
148         {
149                 kfile_print(fd, "-2 Invalid arguments.\r\n");
150                 protocol_prompt(fd);
151                 return;
152         }
153
154         /* Execute. */
155         if(!parser_execute_cmd(templ, args))
156         {
157                 NAK(fd, "Error in executing command.");
158         }
159         if (!protocol_reply(fd, templ, args))
160         {
161                 NAK(fd, "Invalid return format.");
162         }
163
164         protocol_prompt(fd);
165         return;
166 }
167
168 void protocol_run(KFile *fd)
169 {
170         /**
171          * \todo to be removed, we could probably access the serial FIFO
172          * directly
173          */
174         static char linebuf[80];
175
176         if (!interactive)
177         {
178                 kfile_gets(fd, linebuf, sizeof(linebuf));
179
180                 // reset serial port error anyway
181                 kfile_clearerr(fd);
182
183                 // check message minimum length
184                 if (linebuf[0])
185                 {
186                         /* If we enter lines beginning with sharp(#)
187                         they are stripped out from commands */
188                         if(linebuf[0] != '#')
189                         {
190                                 if (linebuf[0] == 0x1B && linebuf[1] == 0x1B)  // ESC
191                                 {
192                                         interactive = true;
193                                         kfile_printf(fd, "Entering interactive mode\r\n");
194                                 }
195                                 else
196                                 {
197                                         protocol_parse(fd, linebuf);
198                                 }
199                         }
200                 }
201         }
202         else
203         {
204                 const char *buf;
205
206                 /*
207                  * Read a line from serial. We use a temporary buffer
208                  * because otherwise we would have to extract a message
209                  * from the port immediately: there might not be any
210                  * available, and one might get free while we read
211                  * the line. We also add a fake ID at the start to
212                  * fool the parser.
213                  */
214                 buf = rl_readline(&rl_ctx);
215
216                 /* If we enter lines beginning with sharp(#)
217                 they are stripped out from commands */
218                 if(buf && buf[0] != '#')
219                 {
220                         if (buf[0] != '\0')
221                         {
222                                 // exit special case to immediately change serial input
223                                 if (!strcmp(buf, "exit") || !strcmp(buf, "quit"))
224                                 {
225                                         rl_clear_history(&rl_ctx);
226                                         kfile_printf(fd, "Leaving interactive mode...\r\n");
227                                         interactive = FORCE_INTERACTIVE;
228                                 }
229                                 else
230                                 {
231                                         //TODO: remove sequence numbers
232                                         linebuf[0] = '0';
233                                         linebuf[1] = ' ';
234
235                                         strncpy(linebuf + 2, buf, sizeof(linebuf) - 3);
236                                         linebuf[sizeof(linebuf) - 1] = '\0';
237                                         protocol_parse(fd, linebuf);
238                                 }
239                         }
240                 }
241         }
242 }
243
244 /*
245  * Commands.
246  * TODO: Command declarations and definitions should be in another file(s).
247  * Maybe we should use CMD_HUNK_TEMPLATE.
248  *
249  */
250
251 MAKE_CMD(ver, "", "ddd",
252 ({
253         args[1].l = VERS_MAJOR;
254         args[2].l = VERS_MINOR;
255         args[3].l = VERS_REV;
256         0;
257 }), 0);
258
259
260 /* Register commands.  */
261 static void protocol_registerCmds(void)
262 {
263         REGISTER_CMD(ver);
264 }
265
266 /* Initialization: readline context, parser and register commands.  */
267 void protocol_init(KFile *fd)
268 {
269         interactive = FORCE_INTERACTIVE;
270
271         rl_init_ctx(&rl_ctx);
272         //rl_setprompt(&rl_ctx, ">> ");
273         rl_sethook_get(&rl_ctx, (getc_hook)kfile_getc, fd);
274         rl_sethook_put(&rl_ctx, (putc_hook)kfile_putc, fd);
275         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
276         rl_sethook_clear(&rl_ctx, (clear_hook)kfile_clearerr,fd);
277
278         parser_init();
279
280         protocol_registerCmds();
281
282         protocol_prompt(fd);
283 }