doc: Add documentation for parser module.
[bertos.git] / bertos / mware / parser.h
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, 2006 Develer S.r.l. (http://www.develer.com/)
30  * All Rights Reserved.
31  * -->
32  *
33  * \defgroup parser Simple RPC machinery
34  * \ingroup mware
35  * \{
36  *
37  * \brief Channel protocol parser and commands.
38  *
39  * This module provides a simple text based RPC implementation.
40  * Often there is the need to give a command to the device and receive results
41  * back. Each command may have a variable number of input and output
42  * parameters, with variable type, and a return code which indicates if the
43  * command was successfully executed or not; this module provides the machinery
44  * to facilitate the above RPC scenario.
45  * You will need to write the RPC input and reply code as well as
46  * the definition of the commands.
47  *
48  * Commands are defined using a CmdTemplate struct containing:
49  * - command name: the string that will be matched by the parser;
50  * - command arguments: a string representing type and number of input
51  *   arguments;
52  * - command output: a string representing type and number of output arguments;
53  * - function callback: function implementing the command.
54  *
55  * Once you have declared the commands, you need to register them in the
56  * parser with the function parser_register_cmd().
57  * You are strongly encouraged to use MAKE_CMD() (or alternatively
58  * MAKE_TEMPLATE()) and REGISTER_CMD() to declare and register commands.
59  *
60  * A command line can be parsed with the following steps:
61  * - find the corresponding command template with parser_get_cmd_template()
62  * - extract command arguments with parser_get_cmd_arguments()
63  * - execute the command with parser_execute_cmd()
64  *
65  * You can also provide interactive command line completion using
66  * parser_rl_match().
67  *
68  * Example:
69  * \code
70  * // Declare a buzzer command
71  * MAKE_CMD(beep, "d", "",
72  * ({
73  *      buz_beep(args[1].l);
74  *      RC_OK;
75  * }), 0)
76  *
77  * // initialize the parser
78  * parser_init();
79  * REGISTER_CMD(beep);
80  *
81  * // parse an input line
82  * char buf[80];
83  * // read line from somewhere
84  * rpc_get(buf);
85  * // now parse the line
86  * const struct CmdTemplate *templ;
87  * templ = parser_get_cmd_template(buf);
88  *
89  * // Take arguments (optionally check errors)
90  * parms args[PARSER_MAX_ARGS];
91  * parser_get_cmd_arguments(buf, templ, args);
92  * //Execute command
93  * if(!parser_execute_cmd(templ, args))
94  * {
95  *      // error
96  * }
97  * // Now args contain the outputs of the function, you can send it
98  * // back to the caller
99  * rpc_reply(args)
100  *
101  * \endcode
102  *
103  * \author Bernie Innocenti <bernie@codewiz.org>
104  * \author Stefano Fedrigo <aleph@develer.com>
105  * \author Giovanni Bajo <rasky@develer.com>
106  *
107  * $WIZ$ module_name = "parser"
108  * $WIZ$ module_configuration = "bertos/cfg/cfg_parser.h"
109  * $WIZ$ module_depends = "kfile", "hashtable"
110  */
111
112
113 #ifndef MWARE_PARSER_H
114 #define MWARE_PARSER_H
115
116 #include "cfg/cfg_parser.h"
117
118 #include <cpu/types.h>
119
120 /**
121  * Error generated by the commands through the return code.
122  */
123 typedef enum
124 {
125         RC_ERROR  = -1, ///< Reply with error.
126         RC_OK     = 0,  ///< No reply (ignore reply arguments).
127         RC_REPLY  = 1,  ///< Reply command arguments.
128         RC_SKIP   = 2   ///< Skip following commands
129 } ResultCode;
130
131 /** union that contains parameters passed to and from commands */
132 typedef union { long l; const char *s; } parms;
133 /** pointer to commands */
134 typedef ResultCode (*CmdFuncPtr)(parms args_results[]);
135
136 /**
137  * Define a command that can be tokenized by the parser.
138  *
139  * The format strings are sequences of characters, one for each
140  * parameter/result. Valid characters are:
141  *
142  *  d - a long integer, in decimal format
143  *  s - a var string (in RAM)
144  *
145  * \note To create and fill an instance for this function, it is strongly
146  * advised to use \c DECLARE_CMD_HUNK (cmd_hunk.h).
147  */
148 struct CmdTemplate
149 {
150         const char *name;          ///< Name of command
151         const char *arg_fmt;       ///< Format string for the input
152         const char *result_fmt;    ///< Format string for the output
153         CmdFuncPtr func;           ///< Pointer to the handler function
154         uint16_t   flags;          ///< Currently unused.
155 };
156
157 #define REGISTER_FUNCTION parser_register_cmd
158
159 /**
160  * Utility function to register a command.
161  *
162  * \param NAME Command name to register
163  */
164 #define REGISTER_CMD(NAME) REGISTER_FUNCTION(&cmd_ ## NAME ## _template)
165
166 /**
167  * Utility macro to create a command template.
168  *
169  * It requires that a callback function with name \a cmd_NAME
170  * is already defined.
171  * \param NAME Command name
172  * \param ARGS Input arguments
173  * \param RES Output arguments
174  * \param FLAGS Command flags
175  */
176 #define MAKE_TEMPLATE(NAME, ARGS, RES, FLAGS)          \
177 const struct CmdTemplate cmd_ ## NAME ## _template =   \
178 {                                                      \
179         #NAME, ARGS, RES, cmd_ ## NAME, FLAGS          \
180 };
181
182 /**
183  * Utility macro to create command templates and callback functions.
184  *
185  * Example for a version command:
186  * \code
187  * MAKE_CMD(ver, "", "ddd",
188  * ({
189  *      args[1].l = VERS_MAJOR;
190  *      args[2].l = VERS_MINOR;
191  *      args[3].l = VERS_REV;
192  *      RC_OK;
193  * }), 0);
194  * \endcode
195  *
196  * Remember that input and output parameters start from index 1, since
197  * args[0] is the command itself.
198  * The last line is the return value of the function.
199  *
200  * \param NAME Command name matched by the parser
201  * \param ARGS Input arguments to the command
202  * \param RES Output arguments of the command
203  * \param BODY Command body, expressed with C 'statement expression'
204  * \param FLAGS Command flags
205  */
206 #define MAKE_CMD(NAME, ARGS, RES, BODY, FLAGS)  \
207 static ResultCode cmd_ ## NAME (parms *args)    \
208 {                                               \
209         return (ResultCode)BODY;                \
210 }                                               \
211 MAKE_TEMPLATE(NAME, ARGS, RES, FLAGS)
212
213 /**
214  * Initialize the parser module
215  *
216  * \note This function must be called before any other function in this module
217  */
218 void parser_init(void);
219
220
221 /**
222  * Register a new command into the parser
223  *
224  * \param cmd Command template describing the command
225  *
226  */
227 void parser_register_cmd(const struct CmdTemplate* cmd);
228
229
230 /**
231  * Hook for readline to provide completion support for the commands
232  * registered in the parser.
233  *
234  * \note This is meant to be used with mware/readline.c. See the
235  * documentation there for a description of this hook.
236  */
237 const char* parser_rl_match(void* dummy, const char* word, int word_len);
238
239
240 /**
241  * \brief Command input handler.
242  *
243  * Process the input, calling the requested command
244  * (if found) and calling printResult() to give out
245  * the result (on device specified with parameter fd).
246  *
247  * \param line Text line to be processed (ASCIIZ)
248  *
249  * \return true if everything is OK, false in case of errors
250  */
251 bool parser_process_line(const char* line);
252
253
254 /**
255  * Execute a command with its arguments, and fetch its results.
256  *
257  * The \a args paramenter is value-result: it provides input arguments to
258  * the callback function and it stores output values on return.
259  *
260  * \param templ Template of the command to be executed
261  * \param args Arguments for the command, and will contain the results
262  *
263  * \return False if the command returned an error, true otherwise
264  */
265 INLINE bool parser_execute_cmd(const struct CmdTemplate* templ, parms args[CONFIG_PARSER_MAX_ARGS])
266 {
267         return (templ->func(args) == 0);
268 }
269
270
271 /**
272  * Find the template for the command contained in the text line.
273  * The template can be used to tokenize the command and interpret
274  * it.
275  *
276  * This function can be used to find out which command is contained
277  * in a given text line without parsing all the parameters and
278  * executing it.
279  *
280  * \param line Text line to be processed (ASCIIZ)
281  *
282  * \return The command template associated with the command contained
283  * in the line, or NULL if the command is invalid.
284  */
285 const struct CmdTemplate* parser_get_cmd_template(const char* line);
286
287
288 /**
289  * Extract the arguments for the command contained in the text line.
290  *
291  * The first argument will always be the command name, so the actual arguments
292  * will start at index 1.
293  *
294  * \param line Text line to be processed (ASCIIZ)
295  * \param templ Command template for this line
296  * \param args Will contain the extracted parameters
297  *
298  * \return True if everything OK, false in case of parsing error.
299  */
300 bool parser_get_cmd_arguments(const char* line, const struct CmdTemplate* templ, parms args[CONFIG_PARSER_MAX_ARGS]);
301
302
303 #if CONFIG_ENABLE_COMPAT_BEHAVIOUR
304 /**
305  * Extract the ID from the command text line.
306  *
307  * \param line Text line to be processed (ASCIIZ)
308  * \param ID Will contain the ID extracted.
309  *
310  * \return True if everything ok, false if there is no ID
311  *
312  */
313 bool parser_get_cmd_id(const char* line, unsigned long* ID);
314 #endif
315
316
317 /** \} */ // defgroup parser
318 #endif /* MWARE_PARSER_H */
319