概述

freeswitch 作为开源VOIP软交换,对经过fs的每一通电话都要有足够的控制。

在一通电话呼叫中,通话时长是一个重要的数据,客户在实际使用过程中,会有各种针对呼叫时长的场景需求。

本篇文档讨论fs如何设置最大呼叫时长,并从源代码的角度解析fs的实现原理。

 

环境

centos:CentOS  release 7.0 (Final)或以上版本

freeswitch:v1.8.7

GCC:4.8.5

 

定时挂机

freeswitch提供了APP接口“sched_hangup”,帮助使用者实现定时挂机功能,以达到设置最大呼叫时长的需求。

使用方法很简单,根据fs的官方文档,调用格式如下。

//在拨号计划中的调用格式
<action application="sched_hangup" data="[+]<time>[ <hangup_cause>]"/>
//作为API接口的调用格式
sched_hangup [+]<time> <uuid>[ <hangup_cause>]"
//实例,C++代码
//设置最大通话时长,默认55秒
ptmp = switch_core_get_variable("max_duration");
max_duration = (ptmp? ptmp: "+55");
if (SWITCH_STATUS_SUCCESS != switch_core_session_execute_application(session, "sched_hangup", max_duration))
{
switch_log_printf(SWITCH_CHANNEL_SESSION_LOG(session), SWITCH_LOG_WARNING,
                "sched_hangup failed, max_duration = %s\n", max_duration);
}
 
//实例,拨号计划
<action application="sched_hangup" data="+55 allotted_timeout"/>
<action application="sched_hangup" data="+55"/>
<action application="sched_hangup" data="55"/>
 
上面的拨号计划实例中,三种调用方式的参数不同,但是实际测试结果是一样的。
这一点和官方接口文档有差异。
Time in seconds.
 
If used with + then the call will be hung up after that number of seconds.
 
If used without + then the given value is considered the number of seconds since the epoch, 1970-01-01 00:00:00 UTC

 

接口描述中,“sched_hangup +55”和“sched_hangup 55”的结果应该是有区别的。

下面从源代码里找找看有什么地方做了特殊处理。

 

源代码

sched_hangup接口代码在mod_dptools模块,逻辑很简单,处理参数,调用“switch_ivr_schedule_hangup”接口。

处理参数的过程中,对于参数1中“+”号的处理,代码如下
int sec = atol(argv[0] + 1);

if (*argv[0] == '+') {

when = switch_epoch_time_now(NULL) + sec;

} else {

       when = atol(argv[0]);

}

//处理之后,when的值为”now+55”和“55”

 

switch_ivr_schedule_hangup接口代码在“switch_ivr_async.c”中,接口中直接调用“switch_scheduler_add_task”创建了一个定时任务,定时任务的逻辑就是对指定的呼叫挂机。

 

上面的逻辑中,都没有涉及执行时间的特殊处理,只剩下“switch_scheduler_add_task”创建任务接口,该接口在之前的文章“freeswitch的任务引擎实现分析”中有详细介绍。

//switch_scheduler_add_task,任务执行时间的特殊处理,小于now则+now
if (task_runtime < now) {
       container->task.repeat
= (uint32_t)task_runtime;
       task_runtime
+= now;
}

这样处理之后,上面“sched_hangup”调用中“+55”和“55”俩种参数的结果就统一了。

 

总结

freeswitch的功能接口部分有很多实用的功能和代码流程,适合有fs深度定制需求的开发参考。

最后放一张简图,便于理解。定时任务的数据结构和处理实际上要比这个复杂。

 

FreeSWITCH内置的负载均衡器 switch freeset_FreeSWITCH内置的负载均衡器

 

 

 

空空如常

求真得真