首先說一下什么是API挺庞,就是Freeswitch的一個接口命令谁尸,我們下面就來實現(xiàn)一個類似于HelloWorld的API.
申明API的宏如下
// cmd為參數(shù)列表
// 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)
申明完函數(shù)需要在Load中加載良蛮,調(diào)用宏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; \
}
上代碼
定義功能函數(shù)
#define SYNTAX_HELLOAPI "<something>"
// 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;
}
加載函數(shù)
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抽碌,是不是在異常的情況下不應(yīng)該返回SUCCESS啊决瞳?我們可以試一下货徙。 將無參數(shù)時改為返回FALSE
SWITCH_STANDARD_API(helloapi_function) {
if (zstr(cmd)) {
stream->write_function(stream, "parameter missing.\n");
return SWITCH_STATUS_FALSE; // <=change here!!
}
運行一下看看
FS連這個命令都不認識了。所以這個返回值是表示API是否接受皮胡,而不是是否成功的意思破婆。