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