Javascript Engine
(→Methods) |
|||
(23 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
Javascript static Engine object.<br> | Javascript static Engine object.<br> | ||
This object is frozen. | This object is frozen. | ||
+ | |||
== Methods == | == Methods == | ||
− | * '''output([value1 [, value2 [, ...]]])''' | + | * '''output([value1[,value2[, ...]]])''' |
Output data to console / log.<br> | Output data to console / log.<br> | ||
Concatenate parameters. Put a space between them.<br> | Concatenate parameters. Put a space between them.<br> | ||
Line 12: | Line 13: | ||
// Output: "1 1 test" | // Output: "1 1 test" | ||
− | * '''debug([level, ][value1 [, value2 [, ...]]])''' | + | |
+ | * '''debug([level,][value1[,value2[, ...]]])''' | ||
Put a debug message in console / log.<br> | Put a debug message in console / log.<br> | ||
Concatenate values. Put a space between them.<br> | Concatenate values. Put a space between them.<br> | ||
Does nothing if the resulting string is empty.<br> | Does nothing if the resulting string is empty.<br> | ||
− | Debug level is handled if the first parameter is an integer value. Defaults to Engine.DebugNote otherwise.<br> | + | Debug level is handled if the first parameter is an integer value and function is called with at least 2 parameters. Defaults to Engine.DebugNote otherwise.<br> |
// The following calls will produce the same debug message: | // The following calls will produce the same debug message: | ||
Engine.debug(Engine.DebugNote,"test","out"); | Engine.debug(Engine.DebugNote,"test","out"); | ||
Line 22: | Line 24: | ||
Engine.debug("test" + " out"); | Engine.debug("test" + " out"); | ||
− | * '''alarm([info, ]level, value1 [, value2 [, ...]])''' | + | |
+ | * '''alarm([info,]level,value1[,value2[, ...]])''' | ||
Put a debug message. Emits an alarm if a callback is installed.<br> | Put a debug message. Emits an alarm if a callback is installed.<br> | ||
Concatenate values. Put a space between them.<br> | Concatenate values. Put a space between them.<br> | ||
Line 36: | Line 39: | ||
Engine.alarm("myscript",Engine.DebugWarn,""); | Engine.alarm("myscript",Engine.DebugWarn,""); | ||
+ | |||
+ | * '''trace(traceId,...)''' | ||
+ | * '''traceDebug(traceId,...)''' | ||
+ | * '''traceAlarm(traceId,...)''' | ||
+ | Put a debug message in console / log adding some extra string.<br> | ||
+ | Parameters:<br/> | ||
+ | '''traceId''' Id to trace.<br/> | ||
+ | All other parameters are the same as in ''debug()'' and ''alarm()'' functions.<br/> | ||
+ | ''trace()'' and ''traceDebug()'' behave like ''debug()'' function. ''trace()'' does nothing if ''traceId'' is empty.<br/> | ||
+ | ''traceAlarm()'' behaves like ''alarm()'' function.<br/> | ||
+ | When ''traceId'' is not empty a 'Trace:<traceId>' is added before debug contents.<br/> | ||
+ | |||
+ | Example: | ||
+ | var traceId = "some_id"; | ||
+ | Engine.traceDebug(traceId,Engine.DebugAll,"some string"); | ||
+ | // Same as | ||
+ | Engine.debug(Engine.DebugAll,"Trace:" + traceId,"some string"); | ||
+ | |||
+ | |||
* '''sleep(seconds)''' | * '''sleep(seconds)''' | ||
Sleep for a number of seconds.<br> | Sleep for a number of seconds.<br> | ||
+ | |||
* '''usleep(microseconds)''' | * '''usleep(microseconds)''' | ||
Sleep for a number of microseconds.<br> | Sleep for a number of microseconds.<br> | ||
+ | |||
* '''yield()''' | * '''yield()''' | ||
Give up the currently running timeslice. Note that on some platforms it also sleeps for the operating system's scheduler resolution.<br> | Give up the currently running timeslice. Note that on some platforms it also sleeps for the operating system's scheduler resolution.<br> | ||
+ | |||
* '''idle()''' | * '''idle()''' | ||
Line 49: | Line 74: | ||
On most operating systems this is a 5 msec sleep.<br> | On most operating systems this is a 5 msec sleep.<br> | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
* '''dump_r([what])''' | * '''dump_r([what])''' | ||
Line 66: | Line 84: | ||
Return:<br> | Return:<br> | ||
'''dump_r''' returns the string containing dumped data.<br> | '''dump_r''' returns the string containing dumped data.<br> | ||
+ | |||
* '''dump_var_r(what[,flags])''' | * '''dump_var_r(what[,flags])''' | ||
Line 88: | Line 107: | ||
Return:<br> | Return:<br> | ||
'''dump_var_r''' returns the string containing dumped data.<br> | '''dump_var_r''' returns the string containing dumped data.<br> | ||
+ | |||
* '''dump_root_r([flags])''' | * '''dump_root_r([flags])''' | ||
* '''print_root_r([flags])''' | * '''print_root_r([flags])''' | ||
− | Same as dump_var_r / print_var_r. ''' | + | Same as dump_var_r / print_var_r. '''what''' is the script context |
+ | |||
* '''dump_t(table[,hdrpMap[,params]])''' | * '''dump_t(table[,hdrpMap[,params]])''' | ||
Line 104: | Line 125: | ||
'''table''': Table to dump<br> | '''table''': Table to dump<br> | ||
'''hdrMap''': Header name mapping. Object with prop[header name in table]=value[new header display name]. Fields will be re-arranged as found in header mapping. New header display name may be empty if the list is only used to re-arrange fields<br> | '''hdrMap''': Header name mapping. Object with prop[header name in table]=value[new header display name]. Fields will be re-arranged as found in header mapping. New header display name may be empty if the list is only used to re-arrange fields<br> | ||
− | '''params''': Dump | + | '''params''': Dump parameters |
− | * '''force_empty''': Boolean (default: false). Dump | + | * '''force_empty''': Boolean (default: false). Dump titles/values separator if empty contents (no rows). Ignored if there are no header names |
* '''all_headers''': Boolean (default: false). Add the rest of the headers not found in 'hdrMap'. Ignored if 'hdrpMap' is not given | * '''all_headers''': Boolean (default: false). Add the rest of the headers not found in 'hdrMap'. Ignored if 'hdrpMap' is not given | ||
+ | * '''optimize_output''': Boolean (default: true). Optimize dumping. Do not add spaces at row end | ||
+ | * '''dump_empty_row''': Boolean (default: true). Dump rows with empty contents. This parameter is ignored (empty rows will be dumped) if ''optimize_output'' is disabled | ||
+ | * '''column_align_title_<COL_NAME>''': Keyword. Align title for specified column. Values: left,center,right. Default: left | ||
+ | * '''column_align_data_<COL_NAME>''': Keyword. Align data (row) for specified column. Values: left,center,right. Default: left | ||
+ | * '''column_width_fixed_<COL_NAME>''': Integer. Fixed column length. Title and column data will be adjusted (cut off or extended) to specified width. This parameter is ignored if 0 | ||
+ | * '''column_width_min_<COL_NAME>''': Integer. Minimum column length. Title and column data with length less than this value will be extended of to specified width by adding spaces. This parameter is ignored if 0 or fixed length is given | ||
+ | * '''column_width_max_<COL_NAME>''': Integer. Maximum column length. Title and column data with length greater than this value will be cut off to specified width. This parameter is ignored if 0 or fixed/minimum length is given | ||
Return:<br> | Return:<br> | ||
− | '''dump_t''' returns the string containing dumped data.<br> | + | '''dump_t''' returns the string containing dumped data.<br> |
+ | |||
+ | |||
+ | '''NOTE''': Empty columns (no title or values) will be ignored.<br/> | ||
+ | |||
a = [{name1:"val11", name2:"val12"}, {name1:"val21", name3:"val23"}]; | a = [{name1:"val11", name2:"val12"}, {name1:"val21", name3:"val23"}]; | ||
a2 = [["name1","name2","name3"], ["val11","val12" ],["val21",undefined,"val23"]]; | a2 = [["name1","name2","name3"], ["val11","val12" ],["val21",undefined,"val23"]]; | ||
Line 120: | Line 152: | ||
// val11 val12 | // val11 val12 | ||
// val21 val23 | // val21 val23 | ||
+ | |||
* '''debugName([name])''' | * '''debugName([name])''' | ||
Line 126: | Line 159: | ||
Parameters:<br> | Parameters:<br> | ||
'''name''': Debug name to set<br> | '''name''': Debug name to set<br> | ||
+ | |||
* '''debugLevel([level])''' | * '''debugLevel([level])''' | ||
Line 132: | Line 166: | ||
Parameters:<br> | Parameters:<br> | ||
'''level''': Debug level to set. Ignored if not an integer value<br> | '''level''': Debug level to set. Ignored if not an integer value<br> | ||
+ | |||
* '''debugEnabled([on])''' | * '''debugEnabled([on])''' | ||
Line 137: | Line 172: | ||
Retrieve the debug enabled flag if no parameter is given.<br> | Retrieve the debug enabled flag if no parameter is given.<br> | ||
Parameters:<br> | Parameters:<br> | ||
− | '''on''': | + | '''on''': True to enable debug output, false to disable it<br> |
+ | |||
* '''debugAt(level)''' | * '''debugAt(level)''' | ||
− | Check if the current debug level is greater or equal to requested level.<br> | + | Check if the current debug level of the module/script is greater or equal to requested level.<br> |
Parameters:<br> | Parameters:<br> | ||
'''level''': Integer value to check<br> | '''level''': Integer value to check<br> | ||
Return:<br> | Return:<br> | ||
− | + | True if the current debug level greater than or equal to '''level''', false otherwise.<br> | |
+ | |||
* '''setDebug(command)''' | * '''setDebug(command)''' | ||
Line 155: | Line 192: | ||
All other values are ignored.<br> | All other values are ignored.<br> | ||
− | |||
− | |||
− | |||
− | |||
* '''runParams([param])''' | * '''runParams([param])''' | ||
Line 167: | Line 200: | ||
Object with fields set to engine parameters or string with requested parameter value.<br> | Object with fields set to engine parameters or string with requested parameter value.<br> | ||
− | * '''configFile(name [,user])''' | + | |
+ | * '''configFile(name[,user])''' | ||
Retrieve the full path of a configuration file. Add the '.conf' extension to name.<br> | Retrieve the full path of a configuration file. Add the '.conf' extension to name.<br> | ||
Parameters:<br> | Parameters:<br> | ||
'''name''': Configuration file name<br> | '''name''': Configuration file name<br> | ||
− | '''user''': Optional. Set it to | + | '''user''': Optional. Set it to true to build the path from user settings<br> |
Return:<br> | Return:<br> | ||
Path to requested file.<br> | Path to requested file.<br> | ||
− | * '''setInterval(callback, milliseconds)''' | + | |
− | * '''setTimeout(callback, milliseconds)''' | + | * '''setInterval(callback, milliseconds[,callback_args...])''' |
+ | * '''setTimeout(callback, milliseconds[,callback_args...])''' | ||
Install a timer event. Request 'callback' function call on given interval.<br> | Install a timer event. Request 'callback' function call on given interval.<br> | ||
'''setInterval''': Repeat function call on requested interval.<br> | '''setInterval''': Repeat function call on requested interval.<br> | ||
Line 183: | Line 218: | ||
'''callback''': Function to call<br> | '''callback''': Function to call<br> | ||
'''milliseconds''': Timer interval in milliseconds<br> | '''milliseconds''': Timer interval in milliseconds<br> | ||
+ | '''callback_args''': Optional arguments to be passed to callback function<br> | ||
Return:<br> | Return:<br> | ||
Timer id.<br> | Timer id.<br> | ||
+ | |||
* '''clearInterval(id)''' | * '''clearInterval(id)''' | ||
Line 192: | Line 229: | ||
'''id''': Timer id to remove<br> | '''id''': Timer id to remove<br> | ||
Return:<br> | Return:<br> | ||
− | + | True on success, false if not found.<br> | |
− | * '''loadLibrary(name [,name1 ...])''' | + | |
− | * '''loadObject(name [,name1 ...])''' | + | * '''setEvent(callback,type[,params[,callback_args...])''' |
+ | Set an event to be signaled to script.<br/> | ||
+ | Parameters:<br> | ||
+ | '''callback''': Callback function<br> | ||
+ | '''type''': Event type (name or integer value)<br> | ||
+ | '''params''': Event setup parameters (object, optional)<br> | ||
+ | '''callback_args''': Optional arguments to be passed to callback function<br> | ||
+ | Return:<br> | ||
+ | Event numeric id, false on failure.<br> | ||
+ | |||
+ | Event type:<br/> | ||
+ | * ''reinit'' string or Engine.EventReInit property value. Setup a callback for javascript module initialize event.<br> | ||
+ | : May be used when a script wants to be notified on javascript module initialize (e.g. if it wants to detect the number of script instances when changed) | ||
+ | : Callback is called from internal processing thread before any timer event | ||
+ | : This event is available in static (loaded from config) and dynamic (loaded using ''javascript eval'' command) scripts | ||
+ | |||
+ | Event setup parameters:<br/> | ||
+ | * ''repeat''. Repeat event. Boolean (default: true) | ||
+ | |||
+ | |||
+ | * '''clearEvent(id)''' | ||
+ | Clear an event se using setEvent().<br/> | ||
+ | Parameters:<br> | ||
+ | '''id''': Event id<br> | ||
+ | Return:<br> | ||
+ | True on success, false on failure (not found).<br> | ||
+ | |||
+ | |||
+ | * '''loadLibrary(name[,name1 ...])''' | ||
+ | * '''loadObject(name[,name1 ...])''' | ||
Load an object (loadObject) or a set of objects (loadLibrary) into script context.<br> | Load an object (loadObject) or a set of objects (loadLibrary) into script context.<br> | ||
These methods can be used to load custom C++ objects exposed to javascript.<br> | These methods can be used to load custom C++ objects exposed to javascript.<br> | ||
Line 202: | Line 268: | ||
'''name''': Library of object name(s). Single name or comma separated list<br> | '''name''': Library of object name(s). Single name or comma separated list<br> | ||
Return:<br> | Return:<br> | ||
− | + | True on success, false on failure (library/object) not given or not found. <br> | |
// The following load objects defined in jsext module: | // The following load objects defined in jsext module: | ||
loadLibrary("jsext"); | loadLibrary("jsext"); | ||
Line 212: | Line 278: | ||
} | } | ||
− | * '''replaceParams(buf, params [,sqlEscape [,extraEsc]])''' | + | |
+ | * '''replaceParams(buf,params[,sqlEscape[,extraEsc]])''' | ||
Replace ${paramname} instances in 'buf' string from 'params' field values.<br> | Replace ${paramname} instances in 'buf' string from 'params' field values.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 226: | Line 293: | ||
// repl: "Test a=first empty= b=second" | // repl: "Test a=first empty= b=second" | ||
− | * '''atob''' | + | |
+ | * '''atob(b64_str)''' | ||
Decode Base64 data.<br> | Decode Base64 data.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 234: | Line 302: | ||
str = Engine.atob(b64_str) | str = Engine.atob(b64_str) | ||
− | * '''btoa''' | + | |
+ | * '''btoa(str[,line_len[,add_eol]])''' | ||
Encode string data to Base64.<br> | Encode string data to Base64.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 244: | Line 313: | ||
b64_str = Engine.btoa(str[,line_len[,add_eol]]) | b64_str = Engine.btoa(str[,line_len[,add_eol]]) | ||
− | * '''atoh''' | + | |
+ | * '''atoh(b64_str[,hex_sep[,hex_upcase]])''' | ||
Decode Base64 data.<br> | Decode Base64 data.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 254: | Line 324: | ||
hex_str = Engine.atoh(b64_str[,hex_sep[,hex_upcase]]) | hex_str = Engine.atoh(b64_str[,hex_sep[,hex_upcase]]) | ||
− | * '''htoa''' | + | |
+ | * '''htoa(hex_str[,line_len[,add_eol]])''' | ||
Encode hexified binary (string) data to Base64.<br> | Encode hexified binary (string) data to Base64.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 264: | Line 335: | ||
b64_str = Engine.htob(hex_str[,line_len[,add_eol]]) | b64_str = Engine.htob(hex_str[,line_len[,add_eol]]) | ||
− | * '''btoh''' | + | |
+ | * '''btoh(str[,hex_sep[,hex_upcase]])''' | ||
Convert binary (string) data to hexified string.<br> | Convert binary (string) data to hexified string.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 274: | Line 346: | ||
hex_str = Engine.btoh(str[,hex_sep[,hex_upcase]]) | hex_str = Engine.btoh(str[,hex_sep[,hex_upcase]]) | ||
− | * '''htob''' | + | |
+ | * '''htob(hex_str[,hex_sep])''' | ||
Unhexify binary (string) data.<br> | Unhexify binary (string) data.<br> | ||
Parameters:<br> | Parameters:<br> | ||
Line 282: | Line 355: | ||
The string, boolean ''false'' on failure (invalid input string). | The string, boolean ''false'' on failure (invalid input string). | ||
str = Engine.htob(hex_str[,hex_sep]) | str = Engine.htob(hex_str[,hex_sep]) | ||
+ | |||
+ | |||
+ | * '''hexByte(hex_str[,offset]''' | ||
+ | Convert at most 2 hexadecimal digits to integer value.<br/> | ||
+ | Parameters:<br/> | ||
+ | '''hex_str''': String<br/> | ||
+ | '''offset''': Optional, integer with offset in string to start from, negative to calculate offset from string end. Deault: 0<br/> | ||
+ | Return:<br/> | ||
+ | Success: Integer value in interval [0..255]<br/> | ||
+ | Failure: '''NaN'''. Reason: offset is past string length or at least one character is not a hexadecimal digit<br/> | ||
+ | |||
+ | |||
+ | * '''instanceIndex()''' | ||
+ | Retrieve the script instance index.<br/> | ||
+ | Return: calling script instance index. 0 (single instance) or greater than 0 if multiple instances are configured<br/> | ||
+ | |||
+ | See [[Javascript module]] configuration on how to configure multiple script instances.<br/> | ||
+ | |||
+ | |||
+ | * '''instanceCount()''' | ||
+ | Retrieve the number of configured script instance(s).<br/> | ||
+ | Return: calling script instance(s) count (at least 1)<br/> | ||
+ | |||
+ | See [[Javascript module]] configuration on how to configure multiple script instances.<br/> | ||
+ | |||
+ | |||
+ | * '''scriptType()''' | ||
+ | Return:<br/> | ||
+ | Calling script type numeric value. See Engine properties section.<br/> | ||
+ | |||
+ | Values:<br/> | ||
+ | '''Engine.ScriptTypeUnknown''' Unknown<br/> | ||
+ | '''Engine.ScriptTypeStatic''' Script was loaded from configuration<br/> | ||
+ | '''Engine.ScriptTypeDynamic''' Script was loaded using ''javascript load'' command<br/> | ||
+ | '''Engine.ScriptTypeMsgHandler''' Script is running a singleton message handler context<br/> | ||
+ | '''Engine.ScriptTypeEval''' Script is was loaded using ''javascript eval'' command<br/> | ||
+ | '''Engine.ScriptTypeRoute''' Script is running a singleton routing context (see the ''routing'' option of javascript config) <br/> | ||
+ | |||
+ | |||
+ | * '''scriptInfo()''' | ||
+ | Retrieve script info description.<br/> | ||
+ | Return: Object<br/> | ||
+ | |||
+ | Properties.<br/> | ||
+ | '''type''' Numeric. See scriptType() return value<br/> | ||
+ | '''type_name''' String. Associated script type name: static,dynamic,handler,eval,route. Empty for unknown type<br/> | ||
+ | |||
+ | |||
+ | * '''init([name])''' | ||
+ | Initialize all or specified plugin.<br/> | ||
+ | Parameters:<br/> | ||
+ | '''name''': Plugin name. Initialize engine and all plugins if this parameter is not given, empty or it value is '*' or 'all'<br/> | ||
+ | |||
+ | All plugins (engine) init: | ||
+ | # Reload main configuration file. Apply some global Yate parameters (maxworkers, addworkers, maxmsgrate, maxmsgage, maxqueued, maxevents, timejump) | ||
+ | # Dispatch an ''engine.init'' message | ||
+ | # Call initialize function for each installed plugins | ||
+ | # Return True | ||
+ | |||
+ | Plugin init: | ||
+ | # Dispatch an ''engine.init'' message with ''plugin'' parameter set to requested plugin name | ||
+ | # Call plugin's initialize function if is an installed one | ||
+ | # Return true if plugin is internal or ''engine.init'' message was handled, false otherwise | ||
+ | |||
+ | |||
+ | * '''restart([code[,gracefull]])''' | ||
+ | Stop and restart the engine and the entire program.<br> | ||
+ | Parameters:<br> | ||
+ | '''code''': Optional return code of the program. Defaults to 0<br> | ||
+ | '''gracefull''': Optional. Attempt to wait until no plugin is busy<br> | ||
+ | Return:<br> | ||
+ | True if restart was initiated, false if exiting or no supervisor or 'allow_abort' is disabled in javascript.conf.<br> | ||
+ | |||
+ | |||
+ | * '''started()''' | ||
+ | Check if engine is started at the time this method is called (engine.start message was sent).<br> | ||
+ | Return:<br> | ||
+ | True if engine was started (all modules were loaded and initialized), false if not.<br> | ||
+ | |||
+ | |||
+ | * '''exiting()''' | ||
+ | Return:<br> | ||
+ | True if engine (application) is exiting exiting (return code was set, Yate is executing stop procedures), false if not.<br> | ||
+ | |||
+ | |||
+ | * '''uptime([what[,msec]])''' | ||
+ | Retrieve application duration.<br/> | ||
+ | Parameters:<br> | ||
+ | '''what''': Duration to obtain. Default: Engine.WallTime<br> | ||
+ | '''msec''': Optional. Return duration in milliseconds. Default: false (return duration in seconds)<br> | ||
+ | Return: Requested duration.<br/> | ||
+ | |||
+ | Durations:<br/> | ||
+ | '''Engine.WallTime''': Duration from application start<br> | ||
+ | '''Engine.UserTime''': Time spent by application in user space<br> | ||
+ | '''Engine.KernelTime''': Time spent by application in kernel space<br> | ||
+ | |||
+ | |||
+ | * '''pluginLoaded(name)''' | ||
+ | Check if a specified plugin is loaded.<br/> | ||
+ | Parameters:<br/> | ||
+ | '''name''': Plugin name<br/> | ||
+ | Return: True if loaded, false otherwise.<br/> | ||
+ | |||
+ | Example: | ||
+ | if (Engine.pluginLoaded("sip")) { | ||
+ | // Do something related to sip module | ||
+ | } | ||
+ | |||
+ | |||
+ | * '''getCongestion()''' | ||
+ | Return: Yate congestion level (unsigned integer).<br/> | ||
+ | |||
+ | |||
+ | * '''setCongestion([reason])''' | ||
+ | Increase or decrease Yate congestion level.<br/> | ||
+ | Parameters:<br/> | ||
+ | '''reason''': Increase congestion level if given and not empty. Decrease congestion level otherwise<br/> | ||
+ | |||
+ | |||
+ | * '''accepting([value])''' | ||
+ | Set or retrieve Yate call accept global state.<br/> | ||
+ | Parameters:<br/> | ||
+ | '''value''': Set call accept state if this parameter is given<br/> | ||
+ | |||
+ | Set call accept (''value'' given) values: '''accept''', '''partial''', '''congestion''', '''reject'''. Do nothing if unknown.<br/> | ||
+ | Retrieve: return one of the above strings from current acept call state.<br/> | ||
+ | |||
+ | |||
+ | * '''lineNo()''' | ||
+ | Return: Line on script code where this function is called.<br/> | ||
+ | |||
+ | |||
+ | * '''fileName([fullPath])''' | ||
+ | Retrieve the name of script file this function is called from.<br/> | ||
+ | Parameters:<br> | ||
+ | '''fullPath''': Boolean, optional. True to return the full file path<br> | ||
+ | Return: File name of the calling script.<br/> | ||
+ | |||
+ | |||
+ | * '''fileNo([fullPath])''' | ||
+ | Retrieve the name of script file and line number this function is called from.<br/> | ||
+ | Parameters:<br> | ||
+ | '''fullPath''': Boolean, optional. True to return the full file path<br> | ||
+ | Return: File name and line number of the calling script (e.g. test.js:12)<br/> | ||
+ | |||
+ | |||
+ | * '''creationLine(obj,[fullPath])''' | ||
+ | Retrieve the name of script file and line number where an object was created.<br/> | ||
+ | Parameters:<br> | ||
+ | '''obj''': Object to check<br> | ||
+ | '''fullPath''': Boolean, optional. True to return the full file path<br> | ||
+ | Return: File name and line number where the given object was created. See fileNo() on format<br/> | ||
+ | |||
+ | Creation line: | ||
+ | var msg = new Message( // creationLine() returns this line | ||
+ | "call.route" | ||
+ | ); | ||
+ | var obj = { | ||
+ | a: 2 | ||
+ | }; // creationLine() returns this line | ||
+ | var arr = [ | ||
+ | "a" | ||
+ | ]; // creationLine() returns this line | ||
== Properties == | == Properties == | ||
Line 303: | Line 540: | ||
in some_script.js | in some_script.js | ||
Engine.name property value is "test" | Engine.name property value is "test" | ||
+ | |||
+ | * '''EventReInit''' | ||
+ | Value(s) to be passed to setEvent() function in ''type'' parameter.<br> | ||
+ | |||
+ | * '''ScriptTypeUnknown''', '''ScriptTypeStatic''', '''ScriptTypeDynamic''', '''ScriptTypeMsgHandler''', '''ScriptTypeEval''', '''ScriptTypeRoute''' | ||
+ | Values returned by scriptType() function.<br/> | ||
+ | |||
+ | * '''DumpPropOnly''', '''DumpFuncOnly''', '''DumpFunc''', '''DumpProp''', '''DumpRecursive''', '''DumpType''', '''DumpProto''', '''DumpPropObjType''' | ||
+ | Value(s) to be passed to dump_var_r(), print_var_r(), dump_root_r(), print_root_r() functions in ''flags'' parameter.<br> | ||
+ | |||
+ | * '''WallTime''', '''UserTime''', '''KernelTime''' | ||
+ | Values to be passed to uptime() function in ''what'' parameter.<br> | ||
+ | |||
+ | [[Category:Javascript]] |
Latest revision as of 10:35, 19 September 2024
Javascript static Engine object.
This object is frozen.
[edit] Methods
- output([value1[,value2[, ...]]])
Output data to console / log.
Concatenate parameters. Put a space between them.
Does nothing if the resulting string is empty.
Engine.output("1",1,"test"); Engine.output("1" + " " + 1 + " test"); // Output: "1 1 test"
- debug([level,][value1[,value2[, ...]]])
Put a debug message in console / log.
Concatenate values. Put a space between them.
Does nothing if the resulting string is empty.
Debug level is handled if the first parameter is an integer value and function is called with at least 2 parameters. Defaults to Engine.DebugNote otherwise.
// The following calls will produce the same debug message: Engine.debug(Engine.DebugNote,"test","out"); Engine.debug(8,"test out"); Engine.debug("test" + " out");
- alarm([info,]level,value1[,value2[, ...]])
Put a debug message. Emits an alarm if a callback is installed.
Concatenate values. Put a space between them.
Does nothing if the resulting string is empty.
Parameters:
info: Optional alarm extra information
level: Debug/Alarm level
Engine.alarm("myscript",Engine.DebugWarn,"Some warning"); // Run time error: Engine.alarm("some text"); Engine.alarm("myscript",Engine.DebugWarn); // No alarm, no debug message: Engine.alarm("myscript",Engine.DebugWarn,"");
- trace(traceId,...)
- traceDebug(traceId,...)
- traceAlarm(traceId,...)
Put a debug message in console / log adding some extra string.
Parameters:
traceId Id to trace.
All other parameters are the same as in debug() and alarm() functions.
trace() and traceDebug() behave like debug() function. trace() does nothing if traceId is empty.
traceAlarm() behaves like alarm() function.
When traceId is not empty a 'Trace:<traceId>' is added before debug contents.
Example:
var traceId = "some_id"; Engine.traceDebug(traceId,Engine.DebugAll,"some string"); // Same as Engine.debug(Engine.DebugAll,"Trace:" + traceId,"some string");
- sleep(seconds)
Sleep for a number of seconds.
- usleep(microseconds)
Sleep for a number of microseconds.
- yield()
Give up the currently running timeslice. Note that on some platforms it also sleeps for the operating system's scheduler resolution.
- idle()
Sleep for a system dependent period adequate for an idle thread.
On most operating systems this is a 5 msec sleep.
- dump_r([what])
- print_r([what])
Dump (recursive) current context or specified item methods and properties.
dump_r: Dump to string
print_r: Dump to output
Parameters:
what: Optional item (variable) to dump. Dump current context if missing
Return:
dump_r returns the string containing dumped data.
- dump_var_r(what[,flags])
- print_var_r(what[,flags])
Dump (recursive) specified item methods and/or properties.
dump_var_r: Dump to string
print_var_r: Dump to output
Parameters:
what: Variable to dump
flags: Configure dump contents
May be an ORed combination of the following values:
Engine.DumpProp: Dump object properties
Engine.DumpFunc: Dump object functions
Engine.DumpRecursive: Dump contained objects also
Engine.DumpType: Dump type (applies to functions also)
Engine.DumpProto: Dump object prototype
Engine.DumpPropObjType: Dump non basic type if the following conditions are met: Engine.DumpProp flag is set, Engine.DumpFunc is not set, Engine.DumpType is not set
Predefined combinations:
Engine.DumpPropOnly: Engine.DumpRecursive | Engine.DumpPropObjType | Engine.DumpProp
Engine.DumpFuncOnly: Engine.DumpRecursive | Engine.DumpProto | Engine.DumpFunc
Defaults to Engine.DumpPropOnly
Return:
dump_var_r returns the string containing dumped data.
- dump_root_r([flags])
- print_root_r([flags])
Same as dump_var_r / print_var_r. what is the script context
- dump_t(table[,hdrpMap[,params]])
- print_t(table[,hdrpMap[,params]])
Dump table to string or output.
The table may be an array of objects or an object containing arrays.
Array:
- Array of objects: each entry describe a new row. Object fields are column names.
- Array of arrays: Each entry describe a new row. First array contains column names.
Object: Each array field describe a column. Field name is the column name.
Parameters:
table: Table to dump
hdrMap: Header name mapping. Object with prop[header name in table]=value[new header display name]. Fields will be re-arranged as found in header mapping. New header display name may be empty if the list is only used to re-arrange fields
params: Dump parameters
- force_empty: Boolean (default: false). Dump titles/values separator if empty contents (no rows). Ignored if there are no header names
- all_headers: Boolean (default: false). Add the rest of the headers not found in 'hdrMap'. Ignored if 'hdrpMap' is not given
- optimize_output: Boolean (default: true). Optimize dumping. Do not add spaces at row end
- dump_empty_row: Boolean (default: true). Dump rows with empty contents. This parameter is ignored (empty rows will be dumped) if optimize_output is disabled
- column_align_title_<COL_NAME>: Keyword. Align title for specified column. Values: left,center,right. Default: left
- column_align_data_<COL_NAME>: Keyword. Align data (row) for specified column. Values: left,center,right. Default: left
- column_width_fixed_<COL_NAME>: Integer. Fixed column length. Title and column data will be adjusted (cut off or extended) to specified width. This parameter is ignored if 0
- column_width_min_<COL_NAME>: Integer. Minimum column length. Title and column data with length less than this value will be extended of to specified width by adding spaces. This parameter is ignored if 0 or fixed length is given
- column_width_max_<COL_NAME>: Integer. Maximum column length. Title and column data with length greater than this value will be cut off to specified width. This parameter is ignored if 0 or fixed/minimum length is given
Return:
dump_t returns the string containing dumped data.
NOTE: Empty columns (no title or values) will be ignored.
a = [{name1:"val11", name2:"val12"}, {name1:"val21", name3:"val23"}]; a2 = [["name1","name2","name3"], ["val11","val12" ],["val21",undefined,"val23"]]; o = {name1:["val11","val21"], name2:["val12"], name3:[null,"val23"]}; Engine.print_t(a); Engine.print_t(a2); Engine.print_t(o); // Same output: // name1 name2 name3 // ----- ----- ----- // val11 val12 // val21 val23
- debugName([name])
Set the debug name.
Retrieve debug name if no parameter is given.
Parameters:
name: Debug name to set
- debugLevel([level])
Set the debug level.
Retrieve the debug level if no parameter is given.
Parameters:
level: Debug level to set. Ignored if not an integer value
- debugEnabled([on])
Toggle (set) the debug enabled flag.
Retrieve the debug enabled flag if no parameter is given.
Parameters:
on: True to enable debug output, false to disable it
- debugAt(level)
Check if the current debug level of the module/script is greater or equal to requested level.
Parameters:
level: Integer value to check
Return:
True if the current debug level greater than or equal to level, false otherwise.
- setDebug(command)
Set debug according to command values.
Handled commands:
- level <level_value>: Set debug level to requested level value
- reset: Reset debug level to javascript module debug level
- engine: Reset debug level and debug enabled flag to yate engine settings
- boolean: Set debug enabled flag
All other values are ignored.
- runParams([param])
Retrieve engine list of parameters specific to this run or a specified one.
Parameters:
param: Optional name of parameter to retrieve
Return:
Object with fields set to engine parameters or string with requested parameter value.
- configFile(name[,user])
Retrieve the full path of a configuration file. Add the '.conf' extension to name.
Parameters:
name: Configuration file name
user: Optional. Set it to true to build the path from user settings
Return:
Path to requested file.
- setInterval(callback, milliseconds[,callback_args...])
- setTimeout(callback, milliseconds[,callback_args...])
Install a timer event. Request 'callback' function call on given interval.
setInterval: Repeat function call on requested interval.
setTimeout: Remove timer after first call.
Parameters:
callback: Function to call
milliseconds: Timer interval in milliseconds
callback_args: Optional arguments to be passed to callback function
Return:
Timer id.
- clearInterval(id)
- clearTimeout(id)
Remove requested timer.
Parameters:
id: Timer id to remove
Return:
True on success, false if not found.
- setEvent(callback,type[,params[,callback_args...])
Set an event to be signaled to script.
Parameters:
callback: Callback function
type: Event type (name or integer value)
params: Event setup parameters (object, optional)
callback_args: Optional arguments to be passed to callback function
Return:
Event numeric id, false on failure.
Event type:
- reinit string or Engine.EventReInit property value. Setup a callback for javascript module initialize event.
- May be used when a script wants to be notified on javascript module initialize (e.g. if it wants to detect the number of script instances when changed)
- Callback is called from internal processing thread before any timer event
- This event is available in static (loaded from config) and dynamic (loaded using javascript eval command) scripts
Event setup parameters:
- repeat. Repeat event. Boolean (default: true)
- clearEvent(id)
Clear an event se using setEvent().
Parameters:
id: Event id
Return:
True on success, false on failure (not found).
- loadLibrary(name[,name1 ...])
- loadObject(name[,name1 ...])
Load an object (loadObject) or a set of objects (loadLibrary) into script context.
These methods can be used to load custom C++ objects exposed to javascript.
An example of such module can be found in modules/test/jsext.cpp.
Parameters:
name: Library of object name(s). Single name or comma separated list
Return:
True on success, false on failure (library/object) not given or not found.
// The following load objects defined in jsext module: loadLibrary("jsext"); loadObject("ExtObj"); // Unsafe to check return value: ok = loadLibrary("lib1","lib2","lib3"); if (!ok) { // Unsafe: the list may be partially loaded. e.g. lib1 and lib3 loaded but not lib2 }
- replaceParams(buf,params[,sqlEscape[,extraEsc]])
Replace ${paramname} instances in 'buf' string from 'params' field values.
Parameters:
buf: String containing the replacements
params: Object whose fields are used to replace
sqlEscape: Optional. True to apply SQL escaping to parameter values
extraEsc: Character to escape other than the SQL default ones
Return:
String with replacements done. 'buf' if 'params' is an invalid object.
params = {a:"first", b:"second", c:"not found"}; s = "Test a=${a} empty=${missing} b=${b}"; repl = Engine.replaceParams(s,params); // repl: "Test a=first empty= b=second"
- atob(b64_str)
Decode Base64 data.
Parameters:
b64_str: Mandatory, Base64 encoded data
Return:
Decoded data, boolean false on failure (invalid Base64 data)
str = Engine.atob(b64_str)
- btoa(str[,line_len[,add_eol]])
Encode string data to Base64.
Parameters:
str: Mandatory, data to encode
line_len: Optional line length (split encoded data, add end of line after each line_len chars)
add_eol: Optional, add an extra end of line after encoded data
Return:
Base64 encoded data
b64_str = Engine.btoa(str[,line_len[,add_eol]])
- atoh(b64_str[,hex_sep[,hex_upcase]])
Decode Base64 data.
Parameters:
b64_str: Mandatory, Base64 encoded data
hex_sep: Optional separator to use between octets. Set it to 'undefined' if not used and hex_upcase is given
hex_upcase: Optional, use upper case characters in hexa
Return:
Hexified string, boolean false on failure (invalid Base64 data)
hex_str = Engine.atoh(b64_str[,hex_sep[,hex_upcase]])
- htoa(hex_str[,line_len[,add_eol]])
Encode hexified binary (string) data to Base64.
Parameters:
hex_str: Mandatory, data to encode
line_len: Optional line length (split encoded data, add end of line after each line_len chars)
add_eol: Optional, add an extra end of line after encoded data
Return:
The string, boolean false on failure (invalid input string).
b64_str = Engine.htob(hex_str[,line_len[,add_eol]])
- btoh(str[,hex_sep[,hex_upcase]])
Convert binary (string) data to hexified string.
Parameters:
str: Mandatory, data to hexify
hex_sep: Optional separator to use between octets. Set it to 'undefined' if not used and hex_upcase is given
hex_upcase: Optional, use upper case characters in hexa
Return:
Hexified string
hex_str = Engine.btoh(str[,hex_sep[,hex_upcase]])
- htob(hex_str[,hex_sep])
Unhexify binary (string) data.
Parameters:
hex_str: Mandatory, data to unhexify
hex_sep: Optional separator between octets. Set it to 'undefined' if missing or unknown (autodetect)
Return:
The string, boolean false on failure (invalid input string).
str = Engine.htob(hex_str[,hex_sep])
- hexByte(hex_str[,offset]
Convert at most 2 hexadecimal digits to integer value.
Parameters:
hex_str: String
offset: Optional, integer with offset in string to start from, negative to calculate offset from string end. Deault: 0
Return:
Success: Integer value in interval [0..255]
Failure: NaN. Reason: offset is past string length or at least one character is not a hexadecimal digit
- instanceIndex()
Retrieve the script instance index.
Return: calling script instance index. 0 (single instance) or greater than 0 if multiple instances are configured
See Javascript module configuration on how to configure multiple script instances.
- instanceCount()
Retrieve the number of configured script instance(s).
Return: calling script instance(s) count (at least 1)
See Javascript module configuration on how to configure multiple script instances.
- scriptType()
Return:
Calling script type numeric value. See Engine properties section.
Values:
Engine.ScriptTypeUnknown Unknown
Engine.ScriptTypeStatic Script was loaded from configuration
Engine.ScriptTypeDynamic Script was loaded using javascript load command
Engine.ScriptTypeMsgHandler Script is running a singleton message handler context
Engine.ScriptTypeEval Script is was loaded using javascript eval command
Engine.ScriptTypeRoute Script is running a singleton routing context (see the routing option of javascript config)
- scriptInfo()
Retrieve script info description.
Return: Object
Properties.
type Numeric. See scriptType() return value
type_name String. Associated script type name: static,dynamic,handler,eval,route. Empty for unknown type
- init([name])
Initialize all or specified plugin.
Parameters:
name: Plugin name. Initialize engine and all plugins if this parameter is not given, empty or it value is '*' or 'all'
All plugins (engine) init:
- Reload main configuration file. Apply some global Yate parameters (maxworkers, addworkers, maxmsgrate, maxmsgage, maxqueued, maxevents, timejump)
- Dispatch an engine.init message
- Call initialize function for each installed plugins
- Return True
Plugin init:
- Dispatch an engine.init message with plugin parameter set to requested plugin name
- Call plugin's initialize function if is an installed one
- Return true if plugin is internal or engine.init message was handled, false otherwise
- restart([code[,gracefull]])
Stop and restart the engine and the entire program.
Parameters:
code: Optional return code of the program. Defaults to 0
gracefull: Optional. Attempt to wait until no plugin is busy
Return:
True if restart was initiated, false if exiting or no supervisor or 'allow_abort' is disabled in javascript.conf.
- started()
Check if engine is started at the time this method is called (engine.start message was sent).
Return:
True if engine was started (all modules were loaded and initialized), false if not.
- exiting()
Return:
True if engine (application) is exiting exiting (return code was set, Yate is executing stop procedures), false if not.
- uptime([what[,msec]])
Retrieve application duration.
Parameters:
what: Duration to obtain. Default: Engine.WallTime
msec: Optional. Return duration in milliseconds. Default: false (return duration in seconds)
Return: Requested duration.
Durations:
Engine.WallTime: Duration from application start
Engine.UserTime: Time spent by application in user space
Engine.KernelTime: Time spent by application in kernel space
- pluginLoaded(name)
Check if a specified plugin is loaded.
Parameters:
name: Plugin name
Return: True if loaded, false otherwise.
Example:
if (Engine.pluginLoaded("sip")) { // Do something related to sip module }
- getCongestion()
Return: Yate congestion level (unsigned integer).
- setCongestion([reason])
Increase or decrease Yate congestion level.
Parameters:
reason: Increase congestion level if given and not empty. Decrease congestion level otherwise
- accepting([value])
Set or retrieve Yate call accept global state.
Parameters:
value: Set call accept state if this parameter is given
Set call accept (value given) values: accept, partial, congestion, reject. Do nothing if unknown.
Retrieve: return one of the above strings from current acept call state.
- lineNo()
Return: Line on script code where this function is called.
- fileName([fullPath])
Retrieve the name of script file this function is called from.
Parameters:
fullPath: Boolean, optional. True to return the full file path
Return: File name of the calling script.
- fileNo([fullPath])
Retrieve the name of script file and line number this function is called from.
Parameters:
fullPath: Boolean, optional. True to return the full file path
Return: File name and line number of the calling script (e.g. test.js:12)
- creationLine(obj,[fullPath])
Retrieve the name of script file and line number where an object was created.
Parameters:
obj: Object to check
fullPath: Boolean, optional. True to return the full file path
Return: File name and line number where the given object was created. See fileNo() on format
Creation line:
var msg = new Message( // creationLine() returns this line "call.route" ); var obj = { a: 2 }; // creationLine() returns this line var arr = [ "a" ]; // creationLine() returns this line
[edit] Properties
- DebugFail, DebugTest, DebugGoOn, DebugConf, DebugStub, DebugWarn, DebugMild, DebugCall, DebugNote, DebugInfo, DebugAll
Debug levels to be used when calling Engine.debug() or Engine.alarm().
NOTE:: Debug level is clamped to interval [DebugTest .. DebugAll] unless 'allow_abort' is enabled in javascript.conf (in this case the debug level is clamped to interval [DebugFail .. DebugAll].
- shared
Provides access to Shared object.
- name
Script name. It may not be available.
This is the name assigned to the script.
This property is missing when running javascript eval command.
Example:
javascript.conf: [scripts] test=some_script.js in some_script.js Engine.name property value is "test"
- EventReInit
Value(s) to be passed to setEvent() function in type parameter.
- ScriptTypeUnknown, ScriptTypeStatic, ScriptTypeDynamic, ScriptTypeMsgHandler, ScriptTypeEval, ScriptTypeRoute
Values returned by scriptType() function.
- DumpPropOnly, DumpFuncOnly, DumpFunc, DumpProp, DumpRecursive, DumpType, DumpProto, DumpPropObjType
Value(s) to be passed to dump_var_r(), print_var_r(), dump_root_r(), print_root_r() functions in flags parameter.
- WallTime, UserTime, KernelTime
Values to be passed to uptime() function in what parameter.