首先说一下什么是API,就是Freeswitch的一个接口命令,我们下面就来实现一个类似于HelloWorld的API.
申明API的宏如下
// cmd为参数列表
// sessin为当前callleg的session
// stream为当前输出流。如果想在Freeswitch控制台中输出什么,可以往这个流里写
#define SWITCH_STANDARD_API(name) \
static switch_status_t name (_In_opt_z_ const char *cmd, _In_opt_ switch_core_session_t *session, _In_ switch_stream_handle_t *stream)
申明完函数需要在Load中加载,调用宏SWITCH_ADD_API
#define SWITCH_ADD_API(api_int, int_name, descript, funcptr, syntax_string) \
for (;;) { \
api_int = (switch_api_interface_t *)switch_loadable_module_create_interface(*module_interface, SWITCH_API_INTERFACE); \
api_int->interface_name = int_name; \
api_int->desc = descript; \
api_int->function = funcptr; \
api_int->syntax = syntax_string; \
break; \
}
上代码
定义功能函数
#define SYNTAX_HELLOAPI ""
// Actually it explais as followings:
// static switch_status_t helloapi_function (_In_opt_z_ const char *cmd, _In_opt_ switch_core_session_t *session, _In_ switch_stream_handle_t *stream)
SWITCH_STANDARD_API(helloapi_function) {
if (zstr(cmd)) {
stream->write_function(stream, "parameter missing.\n");
return SWITCH_STATUS_SUCCESS;
}
switch_memory_pool_t *pool;
switch_core_new_memory_pool(&pool);
char *mycmd = switch_core_strdup(pool, cmd);
char *argv[1] = {0};
int argc = switch_split(mycmd, ' ', argv);
switch_log_printf(SWITCH_CHANNEL_LOG, SWITCH_LOG_DEBUG, "cmd:%s, args count: %d\n", mycmd, argc);
if (argc < 1) {
stream->write_function(stream, "parameter number is invalid.\n");
return SWITCH_STATUS_SUCCESS;
}
stream->write_function(stream, "HelloApi. you said.\n", argv[0]);
return SWITCH_STATUS_SUCCESS;
}
加载函数
SWITCH_MODULE_LOAD_FUNCTION(mod_eric_load) {
// init module interface
*module_interface = switch_loadable_module_create_module_interface(pool, modname);
switch_api_interface_t *api_interface;
SWITCH_ADD_API(api_interface, "hello", "say something", helloapi_function, SYNTAX_HELLOAPI);
return SWITCH_STATUS_SUCCESS;
}
打包加载
看到有新的API Function ‘hello’添加了吧
我们来试一下
注意到我们的API中所有的返回都是SWITCH_STATUS_SUCCESS,是不是在异常的情况下不应该返回SUCCESS啊?我们可以试一下。 将无参数时改为返回FALSE
SWITCH_STANDARD_API(helloapi_function) {
if (zstr(cmd)) {
stream->write_function(stream, "parameter missing.\n");
return SWITCH_STATUS_FALSE; // <=change here!!
}
运行一下看看
FS连这个命令都不认识了。所以这个返回值是表示API是否接受,而不是是否成功的意思。