Add missing assert.
[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 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  * \version $Id$
38  *
39  * \author Giovanni Bajo <rasky@develer.com>
40  * \author Marco Benelli <marco@develer.com>
41  * \author Bernie Innocenti <bernie@codewiz.org>
42  * \author Daniele Basile <asterix@develer.com>
43  */
44
45 #include "protocol.h"
46 #include "cmd_ctor.h"  // MAKE_CMD, REGISTER_CMD
47 #include "verstag.h"
48 #include "hw/hw_adc.h"
49 #include "hw/hw_input.h"
50
51 #include <drv/timer.h>
52 #include <drv/ser.h>
53 #include <drv/sipo.h>
54 #include <drv/wdt.h>
55 #include <drv/buzzer.h>
56
57 #include <mware/readline.h>
58 #include <mware/parser.h>
59
60 #include <cfg/compiler.h>
61 #include <cfg/debug.h>
62
63 #include <kern/kfile.h>
64
65 #include <stdlib.h>
66 #include <string.h>
67
68 // Define the format string for ADC
69 #define ADC_FORMAT_STR "dddd"
70
71 // DEBUG: set to 1 to force interactive mode
72 #define FORCE_INTERACTIVE         1
73
74 /**
75  * True if we are in interactive mode, false if we are in protocol mode.
76  * In interactive mode, commands are read through readline() (prompt,
77  * completion, history) without IDs, and replies/errors are sent to the serial
78  * output.
79  * In protocol mode, we implement the default protocol
80  */
81 static bool interactive;
82
83 /// Readline context, used for interactive mode.
84 static struct RLContext rl_ctx;
85
86 uint8_t reg_status_dout;
87 /**
88  * Send a NAK asking the host to send the current message again.
89  *
90  * \a fd kfile handler for serial.
91  * \a err  human-readable description of the error for debug purposes.
92  */
93 INLINE void NAK(KFile *fd, const char *err)
94 {
95 #ifdef _DEBUG
96         kfile_printf(fd, "NAK \"%s\"\r\n", err);
97 #else
98         kfile_printf(fd, "NAK\r\n");
99 #endif
100 }
101
102 static void protocol_prompt(KFile *fd)
103 {
104         kfile_print(fd, ">> ");
105 }
106
107 /*
108  * Print args on s, with format specified in t->result_fmt.
109  * Return number of valid arguments or -1 in case of error.
110  */
111 static bool protocol_reply(KFile *fd, const struct CmdTemplate *t,
112                           const parms *args)
113 {
114         unsigned short offset = strlen(t->arg_fmt) + 1;
115         unsigned short nres = strlen(t->result_fmt);
116
117         for (unsigned short i = 0; i < nres; ++i)
118         {
119                 if (t->result_fmt[i] == 'd')
120                 {
121                         kfile_printf(fd, " %ld", args[offset+i].l);
122                 }
123                 else if (t->result_fmt[i] == 's')
124                 {
125                         kfile_printf(fd, " %s", args[offset+i].s);
126                 }
127
128                 else
129                 {
130                         abort();
131                 }
132         }
133         kfile_printf(fd, "\r\n");
134         return true;
135 }
136
137 static void protocol_parse(KFile *fd, const char *buf)
138 {
139         const struct CmdTemplate *templ;
140
141         /* Command check.  */
142         templ = parser_get_cmd_template(buf);
143         if (!templ)
144         {
145                 kfile_print(fd, "-1 Invalid command.\r\n");
146                 protocol_prompt(fd);
147                 return;
148         }
149
150         parms args[PARSER_MAX_ARGS];
151
152         /* Args Check.  TODO: Handle different case. see doc/PROTOCOL .  */
153         if (!parser_get_cmd_arguments(buf, templ, args))
154         {
155                 kfile_print(fd, "-2 Invalid arguments.\r\n");
156                 protocol_prompt(fd);
157                 return;
158         }
159
160         /* Execute. */
161         if(!parser_execute_cmd(templ, args))
162         {
163                 NAK(fd, "Error in executing command.");
164         }
165         if (!protocol_reply(fd, templ, args))
166         {
167                 NAK(fd, "Invalid return format.");
168         }
169
170         protocol_prompt(fd);
171         return;
172 }
173
174 void protocol_run(KFile *fd)
175 {
176         /**
177          * \todo to be removed, we could probably access the serial FIFO
178          * directly
179          */
180         static char linebuf[80];
181
182         if (!interactive)
183         {
184                 kfile_gets(fd, linebuf, sizeof(linebuf));
185
186                 // reset serial port error anyway
187                 kfile_clearerr(fd);
188
189                 // check message minimum length
190                 if (linebuf[0])
191                 {
192                         /* If we enter lines beginning with sharp(#)
193                         they are stripped out from commands */
194                         if(linebuf[0] != '#')
195                         {
196                                 if (linebuf[0] == 0x1B && linebuf[1] == 0x1B)  // ESC
197                                 {
198                                         interactive = true;
199                                         kfile_printf(fd, "Entering interactive mode\r\n");
200                                 }
201                                 else
202                                 {
203                                         protocol_parse(fd, linebuf);
204                                 }
205                         }
206                 }
207         }
208         else
209         {
210                 const char *buf;
211
212                 /*
213                  * Read a line from serial. We use a temporary buffer
214                  * because otherwise we would have to extract a message
215                  * from the port immediately: there might not be any
216                  * available, and one might get free while we read
217                  * the line. We also add a fake ID at the start to
218                  * fool the parser.
219                  */
220                 buf = rl_readline(&rl_ctx);
221
222                 /* If we enter lines beginning with sharp(#)
223                 they are stripped out from commands */
224                 if(buf && buf[0] != '#')
225                 {
226                         if (buf[0] != '\0')
227                         {
228                                 // exit special case to immediately change serial input
229                                 if (!strcmp(buf, "exit") || !strcmp(buf, "quit"))
230                                 {
231                                         rl_clear_history(&rl_ctx);
232                                         kfile_printf(fd, "Leaving interactive mode...\r\n");
233                                         interactive = FORCE_INTERACTIVE;
234                                 }
235                                 else
236                                 {
237                                         //TODO: remove sequence numbers
238                                         linebuf[0] = '0';
239                                         linebuf[1] = ' ';
240
241                                         strncpy(linebuf + 2, buf, sizeof(linebuf) - 3);
242                                         linebuf[sizeof(linebuf) - 1] = '\0';
243                                         protocol_parse(fd, linebuf);
244                                 }
245                         }
246                 }
247         }
248 }
249
250 /*
251  * Commands.
252  * TODO: Command declarations and definitions should be in another file(s).
253  * Maybe we should use CMD_HUNK_TEMPLATE.
254  *
255  */
256
257 MAKE_CMD(ver, "", "ddd",
258 ({
259         args[1].l = VERS_MAJOR;
260         args[2].l = VERS_MINOR;
261         args[3].l = VERS_REV;
262         0;
263 }), 0);
264
265 /* Sleep. Example of declaring function body directly in macro call.  */
266 MAKE_CMD(sleep, "d", "",
267 ({
268         timer_delay((mtime_t)args[1].l);
269         0;
270 }), 0)
271
272 /* Ping.  */
273 MAKE_CMD(ping, "", "",
274 ({
275         //Silence "args not used" warning.
276         (void)args;
277         0;
278 }), 0)
279
280 /* Dout  */
281 MAKE_CMD(dout, "d", "",
282 ({
283         sipo_putchar((uint8_t)args[1].l);
284
285         //Store status of dout ports.
286         reg_status_dout = (uint8_t)args[1].l;
287         0;
288 }), 0)
289
290 /* rdout  read the status of out ports.*/
291 MAKE_CMD(rdout, "", "d",
292 ({
293         args[1].l = reg_status_dout;
294         0;
295 }), 0)
296
297
298 /* Reset */
299 MAKE_CMD(reset, "", "",
300 ({
301         //Silence "args not used" warning.
302         (void)args;
303         wdt_init(7);
304         wdt_start();
305
306         /*We want to have an infinite loop that lock access on watchdog timer.
307         This piece of code it's equivalent to a while(true), but we have done this because
308         gcc generate a warning message that suggest to use "noreturn" parameter in function reset.*/
309         ASSERT(args);
310         while(args);
311         0;
312
313 }), 0)
314
315 /* Din */
316 MAKE_CMD(din, "", "d",
317 ({
318         args[1].l = INPUT_GET();
319         0;
320 }), 0)
321
322
323
324 /* Ain */
325 MAKE_CMD(ain, "", ADC_FORMAT_STR,
326 ({
327         STATIC_ASSERT((sizeof(ADC_FORMAT_STR) - 1) == ADC_CHANNEL_NUM);
328         for(int i = 0; i < ADC_CHANNEL_NUM; i++)
329                 args[i+1].l = adc_read_ai_channel(i);
330
331         0;
332 }), 0)
333
334 /* Beep  */
335 MAKE_CMD(beep, "d", "",
336 ({
337         buz_beep(args[1].l);
338         0;
339 }), 0)
340
341 /* Register commands.  */
342 static void protocol_registerCmds(void)
343 {
344         REGISTER_CMD(ver);
345         REGISTER_CMD(sleep);
346         REGISTER_CMD(ping);
347         REGISTER_CMD(dout);
348         //Set off all dout ports.
349         reg_status_dout = 0;
350         REGISTER_CMD(rdout);
351         REGISTER_CMD(reset);
352         REGISTER_CMD(din);
353         REGISTER_CMD(ain);
354         REGISTER_CMD(beep);
355 }
356
357 /* Initialization: readline context, parser and register commands.  */
358 void protocol_init(KFile *fd)
359 {
360         interactive = FORCE_INTERACTIVE;
361
362         rl_init_ctx(&rl_ctx);
363         //rl_setprompt(&rl_ctx, ">> ");
364         rl_sethook_get(&rl_ctx, (getc_hook)kfile_getc, fd);
365         rl_sethook_put(&rl_ctx, (putc_hook)kfile_putc, fd);
366         rl_sethook_match(&rl_ctx, parser_rl_match, NULL);
367         rl_sethook_clear(&rl_ctx, (clear_hook)kfile_clearerr,fd);
368
369         parser_init();
370
371         protocol_registerCmds();
372
373         protocol_prompt(fd);
374 }