Asterisk Expressions

本文介绍Asterisk拨号计划中的表达式语法及其应用,包括逻辑运算符、比较运算符等,并通过实例演示如何使用条件语句实现不同功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

asterisk 表达式应用:

cp from this link:

http://www.voip-info.org/wiki/view/Asterisk+Expressions

Asterisk Expressions

Asterisk dialplan expressions are special expressions that can be used in the dialplan of Asterisk.

Syntax

   $[expr1 operator expr2]

 

The high-level view of variable evaluations in Asterisk:

Since most user input will come via config files to Asterisk, some filtering and substitutions are done
as the config files are read.

Next, as the dialplan is executed, the ${ ... } variables and functions are evaluated and substituted.

And lastly, the contents of $[ .. ] expressions are evaluated and substituted.


Parameter Quoting:

  exten => s,5,BackGround,blabla

The parameter (blabla) can be quoted ("blabla"). In this case, a comma does not terminate the field. However, the double quotes will be passed down to the Background command, in this example.

Also, characters special to variable substitution, expression evaluation, etc (see below), can be quoted. For example, to literally use a $ on the string "$1231", quote it with a preceding /. Special characters that must be quoted to be used, are [ ] $ " /. (to write / itself, use //).

These double quotes and escapes are evaluated at the level of the asterisk config file parser.

Double quotes can also be used inside expressions, as discussed below.

Spaces Inside Variable

UPDATE: with the latest Asterisk Beta (1.2.0_2) there is the following notice:

Dialplan Expressions:

  • The dialplan expression parser (which handles $[ ... ] constructs) has gone through a major upgrade, but has one incompatible change: spaces are no longer required around expression operators, including string comparisons. However, you can now use quoting to keep strings together for comparison. For more details, please read the doc/README.variables file, and check over your dialplan for possible problems.

If the variable being evaluated contains spaces, there can be problems.

For these cases, double quotes around text that may contain spaces will force the surrounded text to be evaluated as a single token. The double quotes will be counted as part of that lexical token.

As an example:

 exten => s,6,GotoIf($[ "${CALLERIDNAME}" : "Privacy Manager" ]?callerid-liar|s|1:s|7)

The variable CALLERIDNAME could evaluate to "DELOREAN MOTORS" (with a space) but the above will evaluate to:

 "DELOREAN MOTORS" : "Privacy Manager"

and will evaluate to 0.

The above without double quotes would have evaluated to:

  DELOREAN MOTORS : Privacy Manager

and will result in syntax errors, because token DELOREAN is immediately followed by token MOTORS and the expression parser will not know how to evaluate this expression.

Null Strings

Testing to see if a string is null can be done in one of three different ways:

  exten => _XX.,1,GotoIf($["${calledid}" != ""]?3)

  exten => _XX.,1,GotoIf($[foo${calledid} != foo]?3)

  exten => _XX.,1,GotoIf($[${LEN(${calledid})} > 0]?3)

The second example above is the way suggested by the WIKI. It will work as long as there are no spaces in the evaluated value.

The first way should work in all cases, and indeed, might now be the safest way to handle this situation.

The third way seems the most logical. Anyone care to comment. Besides the LEN() function, there is now also ISNULL. Keep in mind such function calls need to kept inside ${...}.

 

Logical operators

  • expr1 | expr2 (Logical OR)
    • If expr1 evaluates to a non-empty string or a non-zero value, returns this value ("true"). Otherwise returns the evaluation of expr2.
  • expr1 & expr2 (Logical AND)
  • !expr (Logical Unary Complement)
    • If both expressions evaluate to non-empty strings or non-zero values, then returns the value of expr1 ("true"). Otherwise returns zero ("false").
    • Not available in versions of Asterisk < 1.1
    • Note that if a space is inserted between the '!' and the expression, an error will occur.

 

Comparison operators

  • expr1 = expr2
  • expr1 != expr2
  • expr1 < expr2
  • expr1 > expr2
  • expr1 <= expr2
  • expr1 >= expr2
    • If both arguments are integers, returns the result of an integer comparison. Otherwise returns the result of string comparison using the locale-specific collation sequence. In either case, the result of a comparison is 1 if the specified relation is true, or 0 if the relation is false.

Arithmetic operators

  • expr1 + expr2
  • expr1 - expr2
  • - expr (unary negation operator)
    • Returns the results of addition or subtraction of integer-valued arguments.
    • Not available in versions of Asterisk < 1.1
  • expr1 * expr2
  • expr1 / expr2
  • expr1 % expr2
    • Return the results of multiplication, integer division, or remainder of integer-valued arguments.

Asterisk 1.6 Arithmetic

In 1.6 and above, we upgraded the $[] expressions to handle floating point numbers. Because of this, folks counting on integer behavior would be disrupted. To make the same results possible, some rounding and integer truncation functions have been added to the core of the Expr2 parser. Indeed, dialplan functions can be called from $.. expressions without the ${...} operators. The only trouble might be in the fact that the arguments to these functions must be specified with a comma. If you try to call the MATH function, for example, and try to say 3 + MATH(7*8), the expression parser will evaluate 7*8 for you into 56, and the MATH function will most likely complain that its input doesn't make any sense. We also provide access to most of the floating point functions in the C library. (but not all of them).

While we don't expect someone to want to do Fourier analysis in the dialplan, we don't want to preclude it, either.

Here is a list of the 'builtin' functions in Expr2. All other dialplan functions are available by simply calling them (read-only). In other words, you don't need to surround function calls in $... expressions with ${...}. Don't jump to conclusions, though! - you still need to wrap variable names in curly braces!

  • COS(x) x is in radians. Results vary from -1 to 1.
  • SIN(x) x is in radians. Results vary from -1 to 1.
  • TAN(x) x is in radians.
  • ACOS(x) x should be a value between -1 and 1.
  • ASIN(x) x should be a value between -1 and 1.
  • ATAN(x) returns the arc tangent in radians; between -PI/2 and PI/2.
  • ATAN2(x,y) returns a result resembling y/x, except that the signs of both args are used to determine the quadrant of the result. Its result is in radians, between -PI and PI.
  • POW(x,y) returns the value of x raised to the power of y.
  • SQRT(x) returns the square root of x.
  • FLOOR(x) rounds x down to the nearest integer.
  • CEIL(x) rounds x up to the nearest integer.
  • ROUND(x) rounds x to the nearest integer, but round halfway cases away from zero.
  • RINT(x) rounds x to the nearest integer, rounding halfway cases to the nearest even integer.
  • TRUNC(x) rounds x to the nearest integer not larger in absolute value.
  • REMAINDER(x,y) computes the remainder of dividing x by y. The return value is x - n*y, where n is the value x/y, rounded to the nearest integer. If this quotient is 1/2, it is rounded to the nearest even number.
  • EXP(x) returns e to the x power.
  • EXP2(x) returns 2 to the x power.
  • LOG(x) returns the natural logarithm of x.
  • LOG2(x) returns the base 2 log of x.
  • LOG10(x) returns the base 10 log of x.

 

Regular expressions

  • expr1 : regexp
    • The ':' operator matches expr1 against regexp, which must be a regular expression. The regular expression is anchored to the beginning of the string with an implicit '^'.
    • If the match succeeds and regexp contains at least one regular expression subexpression '/(.../)', the string corresponding to '/1' is returned; otherwise the result returned is the number of characters matched. If the match fails and regexp contains a regular expression subexpression, the null string is returned; otherwise 0.
  • expr1 =~ expr2
    • Exactly the same as the ':' operator, except that the match is not anchored to the beginning of the string. Pardon any similarity to seemingly similar operators in other programming languages!
    • The ":" and "=~" operators share the same precedence.
    • Not available in versions of Asterisk < 1.1


THE DOCUMENTATION ABOVE FOR REGULAR EXPRESSIONS IS WOEFULLY INADEQUATE. The problem seems to be that the regular expression syntax conflicts with Asterisk expression syntax. As a result, one must backslash escape anything which looks like it might be an expression operator. Also, contrary to what is suggested above, it does not seem to be necessary to backslash escape the parentheses.

Here is one example that works:

exten => stripcidtext,n,Set(regx="([0-9]+)") ; Note the quotes -- and note that parentheses are REQUIRED if you want to return the matched string 
exten => stripcidtext,n,Set(cid2=$["${cid}" : ${regx}]) ; Returns numeric beginning to string

So if ${cid} contains 123foo then ${cid2} will contain just 123.

However, if ${cid} contains foo123 then ${cid2} will be empty. Supposedly you could use =~ instead of : and the string matching would work anywhere, but I don't think that works correctly (at least, I could not get =~ to work).

Here is another example:

exten => s,n,Set(enum-protocol=$["${enum-record}" : "([a-zA-Z0-9]/+)/:"])

If enum-record contains "sip:18005558355@tf.voipmich.com", then this command will set enum-protocol to "sip".

Conditional operator

  • expr1 ? expr2 :: expr3
    • Traditional Conditional operator. If expr1 is a number that evaluates to 0 (false), expr3 is result of the this expression evaluation. Otherwise, expr2 is the result.
    • If expr1 is a string, and evaluates to an empty string, or the two characters (""), then expr3 is the result. Otherwise, expr2 is the result.
    • In Asterisk, all 3 exprs will be "evaluated"; if expr1 is "true", expr2 will be the result of the "evaluation" of this expression. expr3 will be the result otherwise.
    • This operator has the lowest precedence.
    • Not available in versions of Asterisk < 1.1
    • This operator is quite buggy. The IF function is recommended instead.


Parentheses are used for grouping in the usual manner.

Operator Precedence

  1. Parentheses: (, )
  2. Unary operators !, -
  3. Regular expression comparison: :, =~
  4. Multiplicative arithmetic operators: *, /, %
  5. Additive arithmetic operators: +, -
  6. Comparison operators: =, !=, <, >, <=, >=
  7. Logical operators: |, &
  8. Conditional operator: ? :

 

Conditionals

There are now several conditional applications-- an example is the conditional gotoIf :

exten => 1,2,GotoIf,condition?label1:label2

If condition is true go to label1, else go to label2. Labels are interpreted exactly as in the normal goto command.

"condition" is just a string. If the string is empty or "0", the condition is considered to be false, if it's anything else, the condition is true. This is designed to be used together with the expression syntax described above, eg :

exten => 1,2,GotoIf,$[${CALLERID} = 123456]2|1:3|1

Example

After the sequence:

exten => 1,1,SetVar(lala=$[1 + 2]);
exten => 1,2,SetVar(koko=$[2 * ${lala}]);

the value of ${koko} is "6".

See also

This next pages example is :

 

Asterisk cmd GotoIf

Synopsis

Conditional goto

Description

   GotoIf(condition?label1[:label2])
   GotoIf(condition?context1,extension1,priority1:context2,extension2,priority2)

Go to label1 if condition is true or to next step (or label2 if defined) if condition is false, or

   GotoIf(condition?[label1]:label2)

Go to next step (or label1 if defined) if condition is true or to label2 if condition is false.

Either label1 or label2 may be omitted (in that case, we just don't take the particular branch), but not both.

condition is just a string. If the string is empty or "0", the condition is considered to be false. If it is anything else, the condition is true. This is designed to be used together with expression syntax.

Labels take the form '[[context,]extension,]priority', so they can be (a) a priority, (b) an extension and a priority, or (c) a context, an extension and a priority. This is the same syntax as for the Goto command.

Example 1

  exten => 206,1,GotoIf($["${CALLERID(num)}" = "303"]?dial1)
  exten => 206,n,GotoIf($["${CALLERID(num)}" != "304"]?moh:dial2)
  exten => 206,n(dial1),Dial(${SPHONE1},15,rt)
  exten => 206,n,Hangup()
  exten => 206,n(dial2),Dial(${PHONE2},15,rt)
  exten => 206,n,Hangup()
  exten => 206,n(moh),MusicOnHold(default)

20050427 - Note that ${CALLERID(num)} can contain spaces (e.g. "No CID available" from some Zap channels), and the example above has been corrected to cope with this situation - without the quotes around ${CALLERID(num)} it doesn't work!

Example 2

 ; Are the first three digits of the returned value of ${ENUM} are
 ;  either SIP or IAX?  If not,  we ignore and pass to normal
 ;  dialing path at priority 4.
 ;
 exten => _011X.,2,GotoIf($[$["${ENUM:0:3}" = "SIP"] | $["${ENUM:0:3}" = "IAX"]]?3:4)

 

Example 3

  ; This example checks for blank caller ID or 800 numbers.
  ; Callers from 800 numbers (usually telemarketers) or those 
  ; with no caller ID are asked to press 1 to speak with me.
  exten => s,1,NoOp(${CALLERID}) ; log callerID string
  ; check for callerID. If none,  make them hit 1.
  exten => s,n,GotoIf($["${CALLERID(num)}" = ""]?1000)
  ; If 800 number, make them hit 1.
  exten => s,n,GotoIf($["${CALLERID(num):0:3}" = "877"]?1000)
  exten => s,n,GotoIf($["${CALLERID(num):0:3}" = "800"]?1000)
  ; OK, we have valid caller ID and it's not an 800 number.
  ; Let's ring our phones now:
  exten => s,n,Dial(SIP/604&SIP/602,25,tr)
  exten => s,1000,Background(press1tospeaktome)

 

Example 4 with func_odbc

in func_odbc.conf:
 [ISLOCAL]
 dsn=foo
 read=SELECT COUNT(*) FROM localexchanges WHERE prefix='${ARG1:0:6}'

in extensions.conf:
 exten => _011-1-NXX-NXX-XXXX,1,GotoIf(${ODBC_ISLOCAL(${EXTEN:4})}?${EXTEN:4},1:${EXTEN:3},1)

Hints


It is worthwhile adding a test for null values, even though modern versions of Asterisk and/or Bison are known to work,
It seems that some still require a hack to test for null values:

For example, assume that the function CALLERID(num) returns an empty string

  GotoIf($[${CALLERID(num)} = 123456789]?3:2)


will cause an error. Instead, use either

  GotoIf($[foo${CALLERID(num)} = foo123456789]?3:2)


or

  GotoIf($["${CALLERID(num)}" = "123456789"]?3:2)


Note that if CALLERID(num) contains a space, the first alternative (foo${CALLERID(num)}) will fail with an error. The use of speech-marks ("") is therefore the recommended method.

Likewise you might want to add a leading 0 if you need to perform a numeric comparison:

  $[0${GROUP_COUNT(numcalls)} > 40]



Also, the use of spacing is very important if you're not using quoted values on both sides of the comparison. So, when testing characters 2 and 3 of ARG1 when ARG1 = "u6432" :


  ; will correctly evaluate to false (and carry on at step 3):
   exten => s,2,GotoIf($[${ARG1:1:2} = 61]?6100)
  ; will always evaluate true (and wrongly jump to step 6100):
   exten => s,2,GotoIf($[${ARG1:1:2}=61]?6100)    
  ; will complain about a mismatched number of characters in 
  ; the comparison (notice the space), thus: 
   exten => s,2,GotoIf($[${ARG1:1:2} =61]?6100) 

 

ast_yyerror: ast_yyerror(): syntax error: syntax error; Input: 64 =61
内容概要:本文档详细介绍了利用Google Earth Engine (GEE) 平台对指定区域(位于中国广东省某地)进行遥感影像处理的一系列操作。首先,定义了研究区边界,并选取了 Landsat 8 卫星2023年8月至10月期间的数据,通过去云处理、归一化等预处理步骤确保数据质量。接着,基于预处理后的影像计算了地表温度(LST)、归一化植被指数(NDVI)、湿度指数(WET)、建筑指数(NDBSI)四个关键指标,并进行了主成分分析(PCA),提取出最重要的信息成分。为了进一步优化结果,还应用了像素二元模型对主成分分析的第一主成分进行了条件规范化处理,生成了最终的环境状态评估指数(RSEI)。最后,利用JRC全球表面水体数据集对水体区域进行了掩膜处理,保证了非水体区域的有效性。所有处理均在GEE平台上完成,并提供了可视化展示及结果导出功能。 适合人群:具备地理信息系统基础知识,对遥感影像处理有一定了解的研究人员或技术人员。 使用场景及目标:① 对特定区域的生态环境状况进行定量评估;② 为城市规划、环境保护等领域提供科学依据;③ 掌握GEE平台下遥感影像处理流程和技术方法。 其他说明:本案例不仅展示了如何使用GEE平台进行遥感影像处理,还涵盖了多种常用遥感指标的计算方法,如LST、NDVI等,对于从事相关领域的科研工作者具有较高的参考价值。此外,文中涉及的代码可以直接在GEE代码编辑器中运行,便于读者实践操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值