2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) <Year>, <Your Name Here>
6 * <Your Name Here> <<Your Email Here>>
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
18 * Please follow coding guidelines
19 * https://wiki.asterisk.org/wiki/display/AST/Coding+Guidelines
24 * \brief Skeleton application
26 * \author\verbatim <Your Name Here> <<Your Email Here>> \endverbatim
28 * This is a skeleton for development of an Asterisk application
29 * \ingroup applications
32 /*! \li \ref app_skel.c uses configuration file \ref app_skel.conf
33 * \addtogroup configuration_file Configuration Files
37 * \page app_skel.conf app_skel.conf
38 * \verbinclude app_skel.conf.sample
42 <defaultenabled>no</defaultenabled>
43 <support_level>core</support_level>
48 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
50 #include <math.h> /* log10 */
51 #include "asterisk/file.h"
52 #include "asterisk/channel.h"
53 #include "asterisk/pbx.h"
54 #include "asterisk/module.h"
55 #include "asterisk/lock.h"
56 #include "asterisk/app.h"
57 #include "asterisk/config.h"
58 #include "asterisk/config_options.h"
59 #include "asterisk/say.h"
60 #include "asterisk/astobj2.h"
61 #include "asterisk/acl.h"
62 #include "asterisk/netsock2.h"
63 #include "asterisk/strings.h"
64 #include "asterisk/cli.h"
67 <application name="SkelGuessNumber" language="en_US">
69 An example number guessing game
72 <parameter name="level" required="true"/>
73 <parameter name="options">
76 <para>The computer should cheat</para>
79 <para>How many games to play before hanging up</para>
85 <para>This simple number guessing application is a template to build other applications
86 from. It shows you the basic structure to create your own Asterisk applications.</para>
90 <configInfo name="app_skel" language="en_US">
91 <configFile name="app_skel.conf">
92 <configObject name="globals">
93 <synopsis>Options that apply globally to app_skel</synopsis>
94 <configOption name="games">
95 <synopsis>The number of games a single execution of SkelGuessNumber will play</synopsis>
97 <configOption name="cheat">
98 <synopsis>Should the computer cheat?</synopsis>
99 <description><para>If enabled, the computer will ignore winning guesses.</para></description>
102 <configObject name="sounds">
103 <synopsis>Prompts for SkelGuessNumber to play</synopsis>
104 <configOption name="prompt" default="please-enter-your&number&queue-less-than">
105 <synopsis>A prompt directing the user to enter a number less than the max number</synopsis>
107 <configOption name="wrong_guess" default="vm-pls-try-again">
108 <synopsis>The sound file to play when a wrong guess is made</synopsis>
110 <configOption name="right_guess" default="auth-thankyou">
111 <synopsis>The sound file to play when a correct guess is made</synopsis>
113 <configOption name="too_low">
114 <synopsis>The sound file to play when a guess is too low</synopsis>
116 <configOption name="too_high">
117 <synopsis>The sound file to play when a guess is too high</synopsis>
119 <configOption name="lose" default="vm-goodbye">
120 <synopsis>The sound file to play when a player loses</synopsis>
123 <configObject name="level">
124 <synopsis>Defined levels for the SkelGuessNumber game</synopsis>
125 <configOption name="max_number">
126 <synopsis>The maximum in the range of numbers to guess (1 is the implied minimum)</synopsis>
128 <configOption name="max_guesses">
129 <synopsis>The maximum number of guesses before a game is considered lost</synopsis>
136 static char *app = "SkelGuessNumber";
139 OPTION_CHEAT = (1 << 0),
140 OPTION_NUMGAMES = (1 << 1),
145 /* This *must* be the last value in this enum! */
146 OPTION_ARG_ARRAY_SIZE,
149 AST_APP_OPTIONS(app_opts,{
150 AST_APP_OPTION('c', OPTION_CHEAT),
151 AST_APP_OPTION_ARG('n', OPTION_NUMGAMES, OPTION_ARG_NUMGAMES),
154 /*! \brief A structure to hold global configuration-related options */
155 struct skel_global_config {
156 AST_DECLARE_STRING_FIELDS(
157 AST_STRING_FIELD(prompt); /*!< The comma-separated list of sounds to prompt to enter a number */
158 AST_STRING_FIELD(wrong); /*!< The comma-separated list of sounds to indicate a wrong guess */
159 AST_STRING_FIELD(right); /*!< The comma-separated list of sounds to indicate a right guess */
160 AST_STRING_FIELD(high); /*!< The comma-separated list of sounds to indicate a high guess */
161 AST_STRING_FIELD(low); /*!< The comma-separated list of sounds to indicate a low guess */
162 AST_STRING_FIELD(lose); /*!< The comma-separated list of sounds to indicate a lost game */
164 uint32_t num_games; /*!< The number of games to play before hanging up */
165 unsigned char cheat:1; /*!< Whether the computer can cheat or not */
168 /*! \brief A structure to maintain level state across reloads */
169 struct skel_level_state {
170 uint32_t wins; /*!< How many wins for this level */
171 uint32_t losses; /*!< How many losses for this level */
172 double avg_guesses; /*!< The average number of guesses to win for this level */
175 /*! \brief Object to hold level config information.
176 * \note This object should hold a reference to an an object that holds state across reloads.
177 * The other fields are just examples of the kind of data that might be stored in an level.
180 AST_DECLARE_STRING_FIELDS(
181 AST_STRING_FIELD(name); /*!< The name of the level */
183 uint32_t max_num; /*!< The upper value on th range of numbers to guess */
184 uint32_t max_guesses; /*!< The maximum number of guesses before losing */
185 struct skel_level_state *state; /*!< A pointer to level state that must exist across all reloads */
188 /*! \brief Information about a currently running set of games
189 * \note Because we want to be able to show true running information about the games
190 * regardless of whether or not a reload has modified what the level looks like, it
191 * is important to either copy the information we need from the level to the
192 * current_game struct, or as we do here, store a reference to the level as it is for
195 struct skel_current_game {
196 uint32_t total_games; /*! The total number of games for this call to to the app */
197 uint32_t games_left; /*! How many games are left to play in this set */
198 uint32_t cheat; /*! Whether or not cheating was enabled for the game */
199 struct skel_level *level_info; /*! The level information for the running game */
202 /* Treat the levels as an array--there won't be many and this will maintain the order */
203 #define LEVEL_BUCKETS 1
205 /*! \brief A container that holds all config-related information
206 * \note This object should contain a pointer to structs for global data and containers for
207 * any levels that are configured. Objects of this type will be swapped out on reload. If an
208 * level needs to maintain state across reloads, it needs to allocate a refcounted object to
209 * hold that state and ensure that a reference is passed to that state when creating a new
210 * level for reload. */
212 struct skel_global_config *global;
213 struct ao2_container *levels;
216 /* Config Options API callbacks */
218 /*! \brief Allocate a skel_config to hold a snapshot of the complete results of parsing a config
220 * \returns A void pointer to a newly allocated skel_config
222 static void *skel_config_alloc(void);
224 /*! \brief Allocate a skel_level based on a category in a configuration file
225 * \param cat The category to base the level on
226 * \returns A void pointer to a newly allocated skel_level
228 static void *skel_level_alloc(const char *cat);
230 /*! \brief Find a skel level in the specified container
231 * \note This function *does not* look for a skel_level in the active container. It is used
232 * internally by the Config Options code to check if an level has already been added to the
233 * container that will be swapped for the live container on a successul reload.
235 * \param tmp_container A non-active container to search for a level
236 * \param category The category associated with the level to check for
237 * \retval non-NULL The level from the container
238 * \retval NULL The level does not exist in the container
240 static void *skel_level_find(struct ao2_container *tmp_container, const char *category);
242 /*! \brief An aco_type structure to link the "general" category to the skel_global_config type */
243 static struct aco_type global_option = {
246 .item_offset = offsetof(struct skel_config, global),
247 .category_match = ACO_WHITELIST,
248 .category = "^general$",
251 struct aco_type *global_options[] = ACO_TYPES(&global_option);
253 /*! \brief An aco_type structure to link the "sounds" category to the skel_global_config type */
254 static struct aco_type sound_option = {
257 .item_offset = offsetof(struct skel_config, global),
258 .category_match = ACO_WHITELIST,
259 .category = "^sounds$",
262 struct aco_type *sound_options[] = ACO_TYPES(&sound_option);
264 /*! \brief An aco_type structure to link the everything but the "general" and "sounds" categories to the skel_level type */
265 static struct aco_type level_option = {
268 .category_match = ACO_BLACKLIST,
269 .category = "^(general|sounds)$",
270 .item_alloc = skel_level_alloc,
271 .item_find = skel_level_find,
272 .item_offset = offsetof(struct skel_config, levels),
275 struct aco_type *level_options[] = ACO_TYPES(&level_option);
277 struct aco_file app_skel_conf = {
278 .filename = "app_skel.conf",
279 .types = ACO_TYPES(&global_option, &sound_option, &level_option),
282 /*! \brief A global object container that will contain the skel_config that gets swapped out on reloads */
283 static AO2_GLOBAL_OBJ_STATIC(globals);
285 /*! \brief The container of active games */
286 static struct ao2_container *games;
288 /*! \brief Register information about the configs being processed by this module */
289 CONFIG_INFO_STANDARD(cfg_info, globals, skel_config_alloc,
290 .files = ACO_FILES(&app_skel_conf),
293 static void skel_global_config_destructor(void *obj)
295 struct skel_global_config *global = obj;
296 ast_string_field_free_memory(global);
299 static void skel_game_destructor(void *obj)
301 struct skel_current_game *game = obj;
302 ao2_cleanup(game->level_info);
305 static void skel_state_destructor(void *obj)
310 static struct skel_current_game *skel_game_alloc(struct skel_level *level)
312 struct skel_current_game *game;
313 if (!(game = ao2_alloc(sizeof(struct skel_current_game), skel_game_destructor))) {
317 game->level_info = level;
321 static void skel_level_destructor(void *obj)
323 struct skel_level *level = obj;
324 ast_string_field_free_memory(level);
325 ao2_cleanup(level->state);
328 static int skel_level_hash(const void *obj, const int flags)
330 const struct skel_level *level = obj;
331 const char *name = (flags & OBJ_KEY) ? obj : level->name;
332 return ast_str_case_hash(name);
335 static int skel_level_cmp(void *obj, void *arg, int flags)
337 struct skel_level *one = obj, *two = arg;
338 const char *match = (flags & OBJ_KEY) ? arg : two->name;
339 return strcasecmp(one->name, match) ? 0 : (CMP_MATCH | CMP_STOP);
342 /*! \brief A custom bitfield handler
344 * \note It is not possible to take the address of a bitfield, therefor all
345 * bitfields in the config struct will have to use a custom handler
346 * \param opt The opaque config option
347 * \param var The ast_variable containing the option name and value
348 * \param obj The object registerd for this option type
350 * \retval non-zero Failure
352 static int custom_bitfield_handler(const struct aco_option *opt, struct ast_variable *var, void *obj)
354 struct skel_global_config *global = obj;
356 if (!strcasecmp(var->name, "cheat")) {
357 global->cheat = ast_true(var->value);
365 static void play_files_helper(struct ast_channel *chan, const char *prompts)
367 char *prompt, *rest = ast_strdupa(prompts);
369 ast_stopstream(chan);
370 while ((prompt = strsep(&rest, "&")) && !ast_stream_and_wait(chan, prompt, "")) {
371 ast_stopstream(chan);
375 static int app_exec(struct ast_channel *chan, const char *data)
379 RAII_VAR(struct skel_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
380 RAII_VAR(struct skel_level *, level, NULL, ao2_cleanup);
381 RAII_VAR(struct skel_current_game *, game, NULL, ao2_cleanup);
382 char *parse, *opts[OPTION_ARG_ARRAY_SIZE];
383 struct ast_flags flags;
384 AST_DECLARE_APP_ARGS(args,
386 AST_APP_ARG(options);
390 ast_log(LOG_ERROR, "Couldn't access configuratino data!\n");
394 if (ast_strlen_zero(data)) {
395 ast_log(LOG_WARNING, "%s requires an argument (level[,options])\n", app);
399 /* We need to make a copy of the input string if we are going to modify it! */
400 parse = ast_strdupa(data);
402 AST_STANDARD_APP_ARGS(args, parse);
404 if (args.argc == 2) {
405 ast_app_parse_options(app_opts, &flags, opts, args.options);
408 if (ast_strlen_zero(args.level)) {
409 ast_log(LOG_ERROR, "%s requires a level argument\n", app);
413 if (!(level = ao2_find(cfg->levels, args.level, OBJ_KEY))) {
414 ast_log(LOG_ERROR, "Unknown level: %s\n", args.level);
418 if (!(game = skel_game_alloc(level))) {
422 ao2_link(games, game);
424 /* Use app-specified values, or the options specified in [general] if they aren't passed to the app */
425 if (!ast_test_flag(&flags, OPTION_NUMGAMES) ||
426 ast_strlen_zero(opts[OPTION_ARG_NUMGAMES]) ||
427 ast_parse_arg(opts[OPTION_ARG_NUMGAMES], PARSE_UINT32, &game->total_games)) {
428 game->total_games = cfg->global->num_games;
430 game->games_left = game->total_games;
431 game->cheat = ast_test_flag(&flags, OPTION_CHEAT) || cfg->global->cheat;
433 for (game->games_left = game->total_games; game->games_left; game->games_left--) {
434 uint32_t num = ast_random() % level->max_num; /* random number between 0 and level->max_num */
436 ast_debug(1, "They should totally should guess %u\n", num);
438 /* Play the prompt */
439 play_files_helper(chan, cfg->global->prompt);
440 ast_say_number(chan, level->max_num, "", ast_channel_language(chan), "");
442 for (guesses = 0; guesses < level->max_guesses; guesses++) {
443 size_t buflen = log10(level->max_num) + 1;
448 /* Read the number pressed */
449 ast_readstring(chan, buf, buflen - 1, 2000, 10000, "");
450 if (ast_parse_arg(buf, PARSE_INT32 | PARSE_IN_RANGE, &guess, 0, level->max_num)) {
451 if (guesses < level->max_guesses - 1) {
452 play_files_helper(chan, cfg->global->wrong);
457 /* Inform whether the guess was right, low, or high */
458 if (guess == num && !game->cheat) {
461 play_files_helper(chan, cfg->global->right);
464 } else if (guess < num) {
465 play_files_helper(chan, cfg->global->low);
467 play_files_helper(chan, cfg->global->high);
470 if (guesses < level->max_guesses - 1) {
471 play_files_helper(chan, cfg->global->wrong);
475 /* Process game stats */
476 ao2_lock(level->state);
478 ++level->state->wins;
479 level->state->avg_guesses = ((level->state->wins - 1) * level->state->avg_guesses + guesses) / level->state->wins;
482 level->state->losses++;
483 play_files_helper(chan, cfg->global->lose);
485 ao2_unlock(level->state);
488 ao2_unlink(games, game);
493 static struct skel_level *skel_state_alloc(const char *name)
495 struct skel_level *level;
497 if (!(level = ao2_alloc(sizeof(*level), skel_state_destructor))) {
504 static void *skel_level_find(struct ao2_container *tmp_container, const char *category)
506 return ao2_find(tmp_container, category, OBJ_KEY);
509 /*! \brief Look up an existing state object, or create a new one
511 * \note Since the reload code will create a new level from scratch, it
512 * is important for any state that must persist between reloads to be
513 * in a separate refcounted object. This function allows the level alloc
514 * function to get a ref to an existing state object if it exists,
515 * otherwise it will return a reference to a newly allocated state object.
517 static void *skel_find_or_create_state(const char *category)
519 RAII_VAR(struct skel_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
520 RAII_VAR(struct skel_level *, level, NULL, ao2_cleanup);
521 if (!cfg || !cfg->levels || !(level = ao2_find(cfg->levels, category, OBJ_KEY))) {
522 return skel_state_alloc(category);
524 ao2_ref(level->state, +1);
528 static void *skel_level_alloc(const char *cat)
530 struct skel_level *level;
532 if (!(level = ao2_alloc(sizeof(*level), skel_level_destructor))) {
536 if (ast_string_field_init(level, 128)) {
541 /* Since the level has state information that needs to persist between reloads,
542 * it is important to handle that here in the level's allocation function.
543 * If not separated out into its own object, the data would be destroyed on
545 if (!(level->state = skel_find_or_create_state(cat))) {
550 ast_string_field_set(level, name, cat);
555 static void skel_config_destructor(void *obj)
557 struct skel_config *cfg = obj;
558 ao2_cleanup(cfg->global);
559 ao2_cleanup(cfg->levels);
562 static void *skel_config_alloc(void)
564 struct skel_config *cfg;
566 if (!(cfg = ao2_alloc(sizeof(*cfg), skel_config_destructor))) {
570 /* Allocate/initialize memory */
571 if (!(cfg->global = ao2_alloc(sizeof(*cfg->global), skel_global_config_destructor))) {
575 if (ast_string_field_init(cfg->global, 128)) {
579 if (!(cfg->levels = ao2_container_alloc(LEVEL_BUCKETS, skel_level_hash, skel_level_cmp))) {
589 static char *handle_skel_show_config(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
591 RAII_VAR(struct skel_config *, cfg, NULL, ao2_cleanup);
595 e->command = "skel show config";
597 "Usage: skel show config\n"
598 " List app_skel global config\n";
604 if (!(cfg = ao2_global_obj_ref(globals)) || !cfg->global) {
608 ast_cli(a->fd, "games per call: %u\n", cfg->global->num_games);
609 ast_cli(a->fd, "computer cheats: %s\n", AST_CLI_YESNO(cfg->global->cheat));
610 ast_cli(a->fd, "\n");
611 ast_cli(a->fd, "Sounds\n");
612 ast_cli(a->fd, " prompt: %s\n", cfg->global->prompt);
613 ast_cli(a->fd, " wrong guess: %s\n", cfg->global->wrong);
614 ast_cli(a->fd, " right guess: %s\n", cfg->global->right);
619 static char *handle_skel_show_games(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
621 struct ao2_iterator iter;
622 struct skel_current_game *game;
626 e->command = "skel show games";
628 "Usage: skel show games\n"
629 " List app_skel active games\n";
635 #define SKEL_FORMAT "%-15.15s %-15.15s %-15.15s\n"
636 #define SKEL_FORMAT1 "%-15.15s %-15u %-15u\n"
637 ast_cli(a->fd, SKEL_FORMAT, "Level", "Total Games", "Games Left");
638 iter = ao2_iterator_init(games, 0);
639 while ((game = ao2_iterator_next(&iter))) {
640 ast_cli(a->fd, SKEL_FORMAT1, game->level_info->name, game->total_games, game->games_left);
643 ao2_iterator_destroy(&iter);
649 static char *handle_skel_show_levels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
651 RAII_VAR(struct skel_config *, cfg, NULL, ao2_cleanup);
652 struct ao2_iterator iter;
653 struct skel_level *level;
657 e->command = "skel show levels";
659 "Usage: skel show levels\n"
660 " List the app_skel levels\n";
666 if (!(cfg = ao2_global_obj_ref(globals)) || !cfg->levels) {
670 #define SKEL_FORMAT "%-15.15s %-11.11s %-12.12s %-8.8s %-8.8s %-12.12s\n"
671 #define SKEL_FORMAT1 "%-15.15s %-11u %-12u %-8u %-8u %-8f\n"
672 ast_cli(a->fd, SKEL_FORMAT, "Name", "Max number", "Max Guesses", "Wins", "Losses", "Avg Guesses");
673 iter = ao2_iterator_init(cfg->levels, 0);
674 while ((level = ao2_iterator_next(&iter))) {
675 ast_cli(a->fd, SKEL_FORMAT1, level->name, level->max_num, level->max_guesses, level->state->wins, level->state->losses, level->state->avg_guesses);
678 ao2_iterator_destroy(&iter);
685 static struct ast_cli_entry skel_cli[] = {
686 AST_CLI_DEFINE(handle_skel_show_config, "Show app_skel global config options"),
687 AST_CLI_DEFINE(handle_skel_show_levels, "Show app_skel levels"),
688 AST_CLI_DEFINE(handle_skel_show_games, "Show app_skel active games"),
691 static int reload_module(void)
693 if (aco_process_config(&cfg_info, 1) == ACO_PROCESS_ERROR) {
694 return AST_MODULE_LOAD_DECLINE;
700 static int unload_module(void)
702 ast_cli_unregister_multiple(skel_cli, ARRAY_LEN(skel_cli));
703 aco_info_destroy(&cfg_info);
704 ao2_global_obj_release(globals);
706 return ast_unregister_application(app);
710 * \brief Load the module
712 * Module loading including tests for configuration or dependencies.
713 * This function can return AST_MODULE_LOAD_FAILURE, AST_MODULE_LOAD_DECLINE,
714 * or AST_MODULE_LOAD_SUCCESS. If a dependency or environment variable fails
715 * tests return AST_MODULE_LOAD_FAILURE. If the module can not load the
716 * configuration file or other non-critical problem return
717 * AST_MODULE_LOAD_DECLINE. On success return AST_MODULE_LOAD_SUCCESS.
719 static int load_module(void)
721 if (aco_info_init(&cfg_info)) {
724 if (!(games = ao2_container_alloc(1, NULL, NULL))) {
729 aco_option_register(&cfg_info, "games", ACO_EXACT, global_options, "3", OPT_UINT_T, 0, FLDSET(struct skel_global_config, num_games));
730 aco_option_register_custom(&cfg_info, "cheat", ACO_EXACT, global_options, "no", custom_bitfield_handler, 0);
733 aco_option_register(&cfg_info, "prompt", ACO_EXACT, sound_options, "please-enter-your&number&queue-less-than", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, prompt));
734 aco_option_register(&cfg_info, "wrong_guess", ACO_EXACT, sound_options, "vm-pls-try-again", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, wrong));
735 aco_option_register(&cfg_info, "right_guess", ACO_EXACT, sound_options, "auth-thankyou", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, right));
736 aco_option_register(&cfg_info, "too_high", ACO_EXACT, sound_options, "high", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, high));
737 aco_option_register(&cfg_info, "too_low", ACO_EXACT, sound_options, "low", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, low));
738 aco_option_register(&cfg_info, "lose", ACO_EXACT, sound_options, "vm-goodbye", OPT_STRINGFIELD_T, 0, STRFLDSET(struct skel_global_config, lose));
741 aco_option_register(&cfg_info, "max_number", ACO_EXACT, level_options, NULL, OPT_UINT_T, 0, FLDSET(struct skel_level, max_num));
742 aco_option_register(&cfg_info, "max_guesses", ACO_EXACT, level_options, NULL, OPT_UINT_T, 1, FLDSET(struct skel_level, max_guesses));
744 if (aco_process_config(&cfg_info, 0) == ACO_PROCESS_ERROR) {
748 ast_cli_register_multiple(skel_cli, ARRAY_LEN(skel_cli));
749 if (ast_register_application_xml(app, app_exec)) {
752 return AST_MODULE_LOAD_SUCCESS;
755 aco_info_destroy(&cfg_info);
757 return AST_MODULE_LOAD_DECLINE;
760 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_LOAD_ORDER, "Skeleton (sample) Application",
762 .unload = unload_module,
763 .reload = reload_module,
764 .load_pri = AST_MODPRI_DEFAULT,