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