Difference between revisions of "JavaScript Callback Functions API"
m (Hsyco moved page Javascript callback api to JavaScript Callback Functions API) |
|||
(49 intermediate revisions by 5 users not shown) | |||
Line 1: | Line 1: | ||
− | + | [[Category:JavaScript]] | |
− | |||
== System Functions == | == System Functions == | ||
=== DaylightEvent === | === DaylightEvent === | ||
− | + | <source lang="java">DaylightEvent(day)</source> | |
Called at sunrise and sunset, according to the latitude and longitude values set in hsyco.ini, and the optional SunriseOffsetMinutes and SunsetOffsetMinutes parameters. | Called at sunrise and sunset, according to the latitude and longitude values set in hsyco.ini, and the optional SunriseOffsetMinutes and SunsetOffsetMinutes parameters. | ||
Line 12: | Line 11: | ||
'''Parameters:''' | '''Parameters:''' | ||
* day: boolean - true at sunrise, false at sunset. | * day: boolean - true at sunrise, false at sunset. | ||
− | |||
=== haActiveEvent === | === haActiveEvent === | ||
− | + | <source lang="java">haActiveEvent(active)</source> | |
Triggered by the change of state of an HSYCO server in a master/slave high availability configuration. | Triggered by the change of state of an HSYCO server in a master/slave high availability configuration. | ||
Line 23: | Line 21: | ||
'''Parameters:''' | '''Parameters:''' | ||
* active: boolean - true if the server is active, false if not active. | * active: boolean - true if the server is active, false if not active. | ||
− | |||
=== PowerEvent === | === PowerEvent === | ||
− | + | <source lang="java">PowerEvent(power)</source> | |
Triggered by a change of the current power load level, as set using the powerSet() Java API or the POWER action. | Triggered by a change of the current power load level, as set using the powerSet() Java API or the POWER action. | ||
Line 45: | Line 42: | ||
=== programTimerEvent === | === programTimerEvent === | ||
− | + | <source lang="java">programTimerEvent(name)</source> | |
Called when a program timer is activated. | Called when a program timer is activated. | ||
− | Program timers are set using programTimerSet(), programTimerReset(), programTimerRepeat(), or using the corresponding actions in EVENTS. | + | Program timers are set using [[Java_Command_and_Utility_Methods_API#programTimerSet|programTimerSet()]], [[Java_Command_and_Utility_Methods_API#programTimerReset|programTimerReset()]], [[Java_Command_and_Utility_Methods_API#programTimerRepeat|programTimerRepeat()]], or using the corresponding actions in EVENTS. |
Line 57: | Line 54: | ||
=== SchedulerEvent === | === SchedulerEvent === | ||
− | + | <source lang="java">SchedulerEvent(groupname, schedulename)</source> | |
This callback blocking function allows to call user methods at configurable intervals. | This callback blocking function allows to call user methods at configurable intervals. | ||
− | + | Schedules are defined using a group name and a schedule name. | |
Schedules under the same group run in the same thread and are executed sequentially, based on their interval in milliseconds. Schedules in different groups run in parallel. | Schedules under the same group run in the same thread and are executed sequentially, based on their interval in milliseconds. Schedules in different groups run in parallel. | ||
Line 69: | Line 66: | ||
* groupname: string - the scheduler’s group name | * groupname: string - the scheduler’s group name | ||
* schedulename: string - the scheduler’s name. | * schedulename: string - the scheduler’s name. | ||
− | |||
=== StartupEvent === | === StartupEvent === | ||
− | + | <source lang="java">StartupEvent()</source> | |
Called only once when HSYCO starts, after the initialization and HTTP server start-up, but before the execution of the different field interface threads. It is not executed in a thread, it is therefore a blocking method, that must complete its execution before all other HSYCO services can be started. | Called only once when HSYCO starts, after the initialization and HTTP server start-up, but before the execution of the different field interface threads. It is not executed in a thread, it is therefore a blocking method, that must complete its execution before all other HSYCO services can be started. | ||
− | |||
=== SunPositionEvent === | === SunPositionEvent === | ||
− | + | <source lang="java">SunPositionEvent(azimuth, elevation)</source> | |
Called when the Sun changes its height with respect to the horizon or its angle from true north. | Called when the Sun changes its height with respect to the horizon or its angle from true north. | ||
Line 92: | Line 87: | ||
=== TimeEvent === | === TimeEvent === | ||
− | + | <source lang="java">TimeEvent(time)</source> | |
Called every 60 seconds. | Called every 60 seconds. | ||
Line 107: | Line 102: | ||
=== varEvent === | === varEvent === | ||
− | + | <source lang="java">varEvent(name, value)</source> | |
Triggered by the change of value of a program variable. | Triggered by the change of value of a program variable. | ||
Line 120: | Line 115: | ||
=== CameraCommandEvent === | === CameraCommandEvent === | ||
− | + | <source lang="java">CameraCommandEvent(camerafunction, action, camera)</source> | |
Triggered by a camera control input from the Web interface. | Triggered by a camera control input from the Web interface. | ||
Line 129: | Line 124: | ||
'''Parameters:''' | '''Parameters:''' | ||
− | * | + | * camerafunction: string - see the table below |
* action: string - see the table below | * action: string - see the table below | ||
* camera: string - the camera name. | * camera: string - the camera name. | ||
Line 137: | Line 132: | ||
* numeric - if CameraCommandEvent() returns -1 or doesn't return a value, the standard PTZ command associated to the PTZ driver is skipped, otherwise it is executed normally. | * numeric - if CameraCommandEvent() returns -1 or doesn't return a value, the standard PTZ command associated to the PTZ driver is skipped, otherwise it is executed normally. | ||
− | {{tip|The JavaScript CameraCommandEvent | + | {{tip|The JavaScript CameraCommandEvent camerafunction is always called, but its return value is used only when the Java CameraCommandEvent callback is not defined or returned -1.}} |
+ | <div data-skipeditordoc> | ||
{{ui_camerapanel_ptz_table}} | {{ui_camerapanel_ptz_table}} | ||
− | + | </div> | |
=== CameraMotionEvent === | === CameraMotionEvent === | ||
− | + | <source lang="java">CameraMotionEvent(event, time)</source> | |
Called when HSYCO starts recording video from a camera. | Called when HSYCO starts recording video from a camera. | ||
Line 162: | Line 158: | ||
=== CameraViewEvent === | === CameraViewEvent === | ||
− | + | <source lang="java">CameraViewEvent(camera, active)</source> | |
CameraViewEvent() is called on changes of the live view status of cameras. | CameraViewEvent() is called on changes of the live view status of cameras. | ||
Line 180: | Line 176: | ||
=== DmxEvent === | === DmxEvent === | ||
− | + | <source lang="java">DmxEvent(channel, state)</source> | |
Called after changes to DMX-512 channels. | Called after changes to DMX-512 channels. | ||
Line 193: | Line 189: | ||
=== DmxFilter === | === DmxFilter === | ||
− | + | <source lang="java">DmxFilter(channel, state, reverse)</source> | |
This function allows to filter the value of the status of each channel on the DMX-512 buses, sending to the gateway different values from those set in HSYCO. | This function allows to filter the value of the status of each channel on the DMX-512 buses, sending to the gateway different values from those set in HSYCO. | ||
Line 220: | Line 216: | ||
=== DmxStartupEvent === | === DmxStartupEvent === | ||
− | + | <source lang="java">DmxStartupEvent(index)</source> | |
Called when starting the monitor threads for each DMX bus, once per bus at the start of the execution of HSYCO, and also after every restart of the monitor thread, for example after communication errors. | Called when starting the monitor threads for each DMX bus, once per bus at the start of the execution of HSYCO, and also after every restart of the monitor thread, for example after communication errors. | ||
Line 237: | Line 233: | ||
=== IREvent === | === IREvent === | ||
− | + | <source lang="java">IREvent(received, irtransid, event)</source> | |
This function is called when an IRTrans receives or sends an IR command from its local IR database. | This function is called when an IRTrans receives or sends an IR command from its local IR database. | ||
Line 254: | Line 250: | ||
=== IOEvent === | === IOEvent === | ||
− | + | <source lang="java">IOEvent(name, value)</source> | |
Triggered by the value change of any data point of an I/O server. | Triggered by the value change of any data point of an I/O server. | ||
Line 267: | Line 263: | ||
=== IOStartupEvent === | === IOStartupEvent === | ||
− | + | <source lang="java">IOStartupEvent(index)</source> | |
Triggered by the start of the communication thread of each I/O server - once for each server at the beginning of the execution of HSYCO, and also after every reboot of the communication thread, for example after communication errors. | Triggered by the start of the communication thread of each I/O server - once for each server at the beginning of the execution of HSYCO, and also after every reboot of the communication thread, for example after communication errors. | ||
Line 286: | Line 282: | ||
=== ModbusEvent === | === ModbusEvent === | ||
− | + | <source lang="java">ModbusEvent(name, addr, unitid, pdu)</source> | |
Called by the Modbus Server I/O Server on every Modbus request received from a Modbus client. | Called by the Modbus Server I/O Server on every Modbus request received from a Modbus client. | ||
Line 307: | Line 303: | ||
== Network Services == | == Network Services == | ||
+ | |||
+ | === httpCallEvent === | ||
+ | |||
+ | <source lang="java">httpCallEvent(address, secure, query)</source> | ||
+ | |||
+ | Called when the HSYCO HTTP server receives a GET request with the following path: | ||
+ | /x/httpcall?query | ||
+ | |||
+ | {{tip|The HTTP client's IP address must be in the trusted network range, or the httpcall request will be rejected, unless HTTPServerLowSecurityEnabled is true and the request is sent using HTTPS}} | ||
+ | |||
+ | This function shoud return a string, that will be sent as the text/plain answer to the HTTP client (with HTTP response code 200). | ||
+ | |||
+ | HSYCO will return a 404 Not Found response code if all of the following conditions are true: | ||
+ | * no HTTP event matches the query in EVENTS | ||
+ | * the httpCallEvent JavaScript callback is not defined in EVENTS, or doesn't return a value | ||
+ | * the httpCallEvent Java callback is not defined in user.java or in any plugins, or returns null. | ||
+ | |||
+ | If the httpCallEvent is defined both in JavaScript and Java, the Java version return value (unless null) will be used in the HTTP response. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * address: string - the IP address of the HTTP client | ||
+ | * secure: boolean - true if the request is sent to the HTTPS server, false if the request is sent to the HTTP server | ||
+ | * query: string - the string following the ? in the URL path. | ||
+ | |||
+ | |||
+ | '''Returns:''' | ||
+ | |||
+ | * string - the string to send as the text/plain answer to the HTTP client. | ||
+ | |||
+ | === httpRawEvent === | ||
+ | |||
+ | <source lang="java"> httpRawEvent(host, secure, version, httpmethod, gzip, contenttype, query, session, userid, indata)</source> | ||
+ | |||
+ | Called when the HSYCO HTTP server receives a GET or POST request with the following path: | ||
+ | /x/raw | ||
+ | |||
+ | {{tip|httpRawEvent is called only if the HTTP client's IP address is in the trusted network range and the HTTPServerLowSecurityEnabled option is true, or if the request has a valid user authentication cookie}} | ||
+ | |||
+ | The application code inside the httpRawEvent() function should return a complete HTTP response (both headers and body). | ||
+ | |||
+ | If multiple httpRawEvent() callbacks or functions are defined, only one should write the HTTP response. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * host: string - the IP address of the HTTP client | ||
+ | * secure: boolean - true if the request is sent to the HTTPS server, false if the request is sent to the HTTP server | ||
+ | * version: string - the HTTP version, as passed in the HTTP request header | ||
+ | * httpmethod: string - the HTTP request's method, "GET", "POST" or "HEAD" | ||
+ | * gzip: boolean - true if the client accepts compressed content (the Accept-Encoding header contains "gzip") | ||
+ | * contenttype: string - the HTTP request's content type (value of Content-Type header) | ||
+ | * query: string - the string following the ? in the URL path, or null if not present | ||
+ | * session: string - the authenticated session id, or null | ||
+ | * userid: string - the user id for requests having a valid authentication cookie, null otherwise | ||
+ | * indata: string - the POST data, or an empty string for GET or HEAD requests. | ||
+ | |||
+ | |||
+ | '''Returns:''' | ||
+ | |||
+ | * string - the application code should return the full HTTP response, including all headers. | ||
+ | |||
+ | |||
+ | '''Example:''' | ||
+ | |||
+ | function httpRawEvent(host, secure, version, httpmethod, gzip, contenttype, query, session, userid, indata) : { | ||
+ | messageLog("host: " + host); | ||
+ | messageLog("secure: " + secure); | ||
+ | messageLog("version: " + version); | ||
+ | messageLog("httpmethod: " + httpmethod); | ||
+ | messageLog("gzip: " + gzip); | ||
+ | messageLog("contenttype: " + contenttype); | ||
+ | messageLog("query: " + query); | ||
+ | messageLog("session: " + session); | ||
+ | messageLog("userid: " + userid); | ||
+ | messageLog("in: " + indata); | ||
+ | |||
+ | var outdata = httpmethod + " data echoed from host [" + host + "] : " + indata + "\r\n"; | ||
+ | var httpreply = version + " 200 OK\r\n"; | ||
+ | httpreply += "Server: HSYCO\r\n"; | ||
+ | httpreply += "Content-length: " + outdata.length + "\r\n"; | ||
+ | httpreply += "Content-type: text/plain\r\n"; | ||
+ | httpreply += "Cache-Control: no-store, no-cache\r\n\r\n"; | ||
+ | httpreply += outdata; | ||
+ | return httpreply; | ||
+ | } | ||
=== LocationEvent === | === LocationEvent === | ||
− | + | <source lang="java">LocationEvent(mac, ip, zoneId)</source> | |
− | Called, if the location service is active, when a variation in the | + | Called, if the location service is active, when a variation in the association of a client to the Wi-Fi Access Points is detected. |
Line 321: | Line 404: | ||
* zoneId: numeric - in case of association, it is the Access Point sequence number, according to the order defined in the LocationBases parameter in hsyco.ini; -1 if the client was de-associated from the Wi-Fi network. | * zoneId: numeric - in case of association, it is the Access Point sequence number, according to the order defined in the LocationBases parameter in hsyco.ini; -1 if the client was de-associated from the Wi-Fi network. | ||
+ | === LocationBeaconEvent === | ||
+ | <div style="color:#CC0000">'''{{Note|<center>WARNING! The Beacons functionality for iOS is experimental and subject to changes.</center>}}''' | ||
+ | </div> | ||
+ | <source lang="java">LocationBeaconEvent(session, address, userid, zone, distance, background)</source> | ||
+ | |||
+ | Called when the HSYCO App detects a change in the proximity of one of the configured beacons. See [[Beacons on HSYCO App for iOS]] for additional information. | ||
+ | |||
+ | There is no guarantee that the event would be fired. | ||
+ | |||
+ | Network delays or errors could cause delayed triggering of this event. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * session: string - session id string that uniquely identifies the client session | ||
+ | * address: string - the beacon's address | ||
+ | * userid: string - the user id | ||
+ | * zone: string - the beacon's zone | ||
+ | * distance: string - far, near, immediate or off | ||
+ | * background: boolean - true if the app called the server while in background mode (app closed) | ||
+ | |||
+ | === SysLogEvent === | ||
+ | |||
+ | <source lang="java"> SysLogEvent(address, log)</source> | ||
+ | |||
+ | Called when the HSYCO SYSLOG server receives a log message from a network client. | ||
+ | |||
+ | Note that this is a blocking call. The SYSLOG server will not process further messages until the last call has been processed. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * address: string - the IP address of the SYSLOG client | ||
+ | * log: string - SYSLOG log message. | ||
== PBX == | == PBX == | ||
Line 326: | Line 443: | ||
=== PBXCallEvent === | === PBXCallEvent === | ||
− | + | <source lang="java">PBXCallEvent(host, caller, called)</source> | |
Called when a call notification is sent to HSYCO by the PBX system. | Called when a call notification is sent to HSYCO by the PBX system. | ||
If the method returns true, the request is recorded on the log file with the [OK] status, with [ERROR] otherwise. | If the method returns true, the request is recorded on the log file with the [OK] status, with [ERROR] otherwise. | ||
+ | |||
+ | The PBX should generate HTTP requests to the HSYCO Web Server, using the following formats: | ||
+ | |||
+ | <nowiki>http://192.168.0.50/x/vcall/<from>/<to></nowiki> | ||
+ | |||
+ | or: | ||
+ | |||
+ | <nowiki>http://192.168.0.50/x/vcall?from=<from>&to=<to></nowiki> | ||
+ | |||
+ | For example, the HTTP request: | ||
+ | |||
+ | <nowiki>http://192.168.0.50/x/vcall?from=21&to=25</nowiki> | ||
+ | |||
+ | is interpreted as a call notification from internal number 21 to number 25. | ||
+ | |||
+ | {{tip|The HTTP client's IP address must be in the trusted network range, or the httpcall request will be rejected.}} | ||
Line 348: | Line 481: | ||
=== SlimPowerEvent === | === SlimPowerEvent === | ||
− | + | <source lang="java">SlimPowerEvent(index, power)</source> | |
Called when a Squeezebox player is turned on or off. | Called when a Squeezebox player is turned on or off. | ||
Line 360: | Line 493: | ||
=== SlimStatusEvent === | === SlimStatusEvent === | ||
− | + | <source lang="java">SlimStatusEvent()</source> | |
Called when a Squeezebox player changes its playback mode. | Called when a Squeezebox player changes its playback mode. | ||
Line 373: | Line 506: | ||
=== SlimVolumeEvent === | === SlimVolumeEvent === | ||
− | + | <source lang="java">SlimVolumeEvent(index, volume)</source> | |
Called when a Squeezebox player changes its volume level. | Called when a Squeezebox player changes its volume level. | ||
Line 388: | Line 521: | ||
=== UserTimerEvent === | === UserTimerEvent === | ||
− | + | <source lang="java">UserTimerEvent(name, active)</source> | |
Called when a user timer or scheduler’s rule should be activated, and before executing the associated action in EVENTS. | Called when a user timer or scheduler’s rule should be activated, and before executing the associated action in EVENTS. | ||
Line 421: | Line 554: | ||
=== pageEvent === | === pageEvent === | ||
− | + | <source lang="java">pageEvent(address, session, userid, project, page)</source> | |
Called when a Web client initially loads a project and when navigating between pages. | Called when a Web client initially loads a project and when navigating between pages. | ||
Line 437: | Line 570: | ||
* project: string - project’s id | * project: string - project’s id | ||
* page: string - the page id, with the #landscape or #portrait suffix if the page has distinct orientation versions in the project. | * page: string - the page id, with the #landscape or #portrait suffix if the page has distinct orientation versions in the project. | ||
+ | |||
+ | === loginEvent === | ||
+ | |||
+ | <source lang="java">loginEvent(address, session, userid)</source> | ||
+ | |||
+ | Called when a user authenticates with a valid PIN or PIN/PUK. | ||
+ | |||
+ | Note that, while the session string passed to the pageEvent callback contains the browser global session id followed by a web view id, the session string passed to loginEvent only contains the global session id. The global session id is the portion of session id that is common between multiple web views open concurrently on the same web browser. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * address: string - the client’s IP address string in textual presentation | ||
+ | * session: string - session id string that uniquely identifies the client session | ||
+ | * userid: string - the user id. | ||
+ | |||
+ | === logoutEvent === | ||
+ | |||
+ | <source lang="java">logoutEvent(address, session, userid, lock)</source> | ||
+ | |||
+ | Called when a user logs out or locks the user interface. | ||
+ | |||
+ | Note that, while the session string passed to the pageEvent callback contains the browser global session id followed by a web view id, the session string passed to logoutEvent only contains the global session id. The global session id is the portion of session id that is common between multiple web views open concurrently on the same web browser. | ||
+ | |||
+ | |||
+ | '''Parameters:''' | ||
+ | |||
+ | * address: string - the client’s IP address string in textual presentation | ||
+ | * session: string - session id string that uniquely identifies the client session | ||
+ | * userid: string - the user id | ||
+ | * lock: boolean - false when logging out; true when the user locks the user interface. | ||
=== uiClearEvent === | === uiClearEvent === | ||
− | + | <source lang="java">uiClearEvent(session)</source> | |
Called, following an explicit call of uiClear() or after the client session inactivity timeout expires, if the client session becomes active again (i.e. the client starts handshaking again with the server with the same session id). | Called, following an explicit call of uiClear() or after the client session inactivity timeout expires, if the client session becomes active again (i.e. the client starts handshaking again with the server with the same session id). | ||
Line 451: | Line 615: | ||
=== userCommand === | === userCommand === | ||
− | + | <source lang="java">userCommand(session, userid, name, param)</source> | |
− | Called by user clicks on buttons created in the Web interface with the | + | Called by user clicks on buttons created in the Web interface with the [[user|user objects]], by a USER action in EVENTS, or by the user() Java method and JavaScript function. |
+ | Also triggered by by the screensaver (see the '''[[Screensaver| Screensaver]]''' page for more details). | ||
This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”. | This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”. | ||
− | + | {{userCommand return values}} | |
+ | |||
+ | {{tip|As this callback may return data synchronously to the Web interface in response to a user command, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.}} | ||
Line 464: | Line 631: | ||
* session: string - a session id string that uniquely identifies the client session | * session: string - a session id string that uniquely identifies the client session | ||
* userid: string - the user id | * userid: string - the user id | ||
− | * name: string - the name field of the | + | * name: string - the name field of the [[user|user object]] |
− | * param: string - the param of the | + | * param: string - the param of the [[user|user object]] |
Line 476: | Line 643: | ||
=== userSubmit === | === userSubmit === | ||
− | + | <source lang="java">userSubmit(session, userid, name, fields)</source> | |
This function is similar to userCommand(session, userid, name, param). | This function is similar to userCommand(session, userid, name, param). | ||
− | When userSubmit() is defined, it will be called when a | + | When userSubmit() is defined, it will be called when a [[submit|submit button]] is pressed, while userCommand() will continue to be called on [[user|user buttons]]. |
userSubmit() provides a more convenient access to the values of multiple input fields in a form. | userSubmit() provides a more convenient access to the values of multiple input fields in a form. | ||
Line 486: | Line 653: | ||
This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”. | This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”. | ||
− | If you want to force the Web interface to show a specific page after the button is pressed (it would be like pressing a | + | If you want to force the Web interface to show a specific page after the button is pressed (it would be like pressing a [[link|link object]]), return a string starting with “page:” followed by the page name; in this case, userCommand() will be called when that popup or page is closed, with "/close" appended to param. |
+ | |||
+ | You can also use "page:back" or "page:forward" to move back and forth along the pages' navigation history. Use "page:close" to close a popup. | ||
+ | |||
+ | {{tip|As this callback may return data synchronously to the Web interface in response to a user command, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.}} | ||
Line 509: | Line 680: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
− | + | function userSubmit(session, user, name, values) : { | |
− | + | if (session.length > 0) { | |
− | + | messageLog(user + ', ' + name + '=' + values); | |
− | + | var keys = values.keySet().toArray(); | |
− | + | for (var i = 0; i < keys.length; i++) { | |
− | + | messageLog(user + ', ' + keys[i] + ' = ' + values.get(keys[i])); | |
− | + | } | |
− | + | return ""; | |
− | + | } | |
− | + | } | |
</syntaxhighlight> | </syntaxhighlight> | ||
Line 531: | Line 702: | ||
=== WebRootRequestEvent === | === WebRootRequestEvent === | ||
− | + | <source lang="java">WebRootRequestEvent(addr, secure, useragent)</source> | |
This method is called when the Web server receives a root URL request. It can return a string to redirect the browser to a valid URL, or null to prevent redirection. | This method is called when the Web server receives a root URL request. It can return a string to redirect the browser to a valid URL, or null to prevent redirection. | ||
+ | |||
+ | {{tip|As this callback returns data synchronously to the Web interface in response to the HTTP request, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.}} | ||
Line 553: | Line 726: | ||
<syntaxhighlight lang="javascript"> | <syntaxhighlight lang="javascript"> | ||
− | + | function WebRootRequestEvent(addr, secure, useragent) : { | |
− | + | return "hsycoserver/manager"; | |
− | + | } | |
</syntaxhighlight> | </syntaxhighlight> |
Latest revision as of 14:36, 13 October 2020
Contents
System Functions
DaylightEvent
DaylightEvent(day)
Called at sunrise and sunset, according to the latitude and longitude values set in hsyco.ini, and the optional SunriseOffsetMinutes and SunsetOffsetMinutes parameters.
Parameters:
- day: boolean - true at sunrise, false at sunset.
haActiveEvent
haActiveEvent(active)
Triggered by the change of state of an HSYCO server in a master/slave high availability configuration.
Parameters:
- active: boolean - true if the server is active, false if not active.
PowerEvent
PowerEvent(power)
Triggered by a change of the current power load level, as set using the powerSet() Java API or the POWER action.
Thanks to this function, you can alter the power value shown in the Web interface, for example to aggregate power readings acquired from other sensors.
Parameters:
- power: numeric - the power level, in Watts.
Returns:
- numeric - if PowerEvent() returns -1 or doesn't return a value, HSYCO status is updated with the detected power value, the value returned by PowerEvent() is otherwise used.
The JavaScript PowerEvent function is always called, but its return value is used only when the Java PowerEvent callback is not defined or returned -1.
programTimerEvent
programTimerEvent(name)
Called when a program timer is activated.
Program timers are set using programTimerSet(), programTimerReset(), programTimerRepeat(), or using the corresponding actions in EVENTS.
Parameters:
- name: string - program timer name.
SchedulerEvent
SchedulerEvent(groupname, schedulename)
This callback blocking function allows to call user methods at configurable intervals.
Schedules are defined using a group name and a schedule name.
Schedules under the same group run in the same thread and are executed sequentially, based on their interval in milliseconds. Schedules in different groups run in parallel.
Parameters:
- groupname: string - the scheduler’s group name
- schedulename: string - the scheduler’s name.
StartupEvent
StartupEvent()
Called only once when HSYCO starts, after the initialization and HTTP server start-up, but before the execution of the different field interface threads. It is not executed in a thread, it is therefore a blocking method, that must complete its execution before all other HSYCO services can be started.
SunPositionEvent
SunPositionEvent(azimuth, elevation)
Called when the Sun changes its height with respect to the horizon or its angle from true north.
Parameters:
- azimuth: numeric - the current Sun angle from true north, in decimal degrees
- elevation: numeric - the current Sun elevation in decimal degrees from the horizon. Elevation is negative at night.
TimeEvent
TimeEvent(time)
Called every 60 seconds.
HSYCO tries to synchronize the execution at the beginning of the minute, executing this method at seconds 0 of every minute.
However, the execution is not guaranteed. In case of heavy load HSYCO might not be able to execute the call with accurate timing. In extreme cases, it could occasionally skip some calls.
Parameters:
- time: numeric - the current time in milliseconds.
varEvent
varEvent(name, value)
Triggered by the change of value of a program variable.
Parameters:
- name: string - the variable name. Names are case-insensitive
- value: string - the value to be assigned to the program variable.
Cameras
CameraCommandEvent
CameraCommandEvent(camerafunction, action, camera)
Triggered by a camera control input from the Web interface.
It can be used to execute arbitrary actions when the user clicks on the active areas of the camera view, or to replace some or all of the standard PTZ commands with custom actions.
Parameters:
- camerafunction: string - see the table below
- action: string - see the table below
- camera: string - the camera name.
Returns:
- numeric - if CameraCommandEvent() returns -1 or doesn't return a value, the standard PTZ command associated to the PTZ driver is skipped, otherwise it is executed normally.
The JavaScript CameraCommandEvent camerafunction is always called, but its return value is used only when the Java CameraCommandEvent callback is not defined or returned -1.
|
CameraMotionEvent
CameraMotionEvent(event, time)
Called when HSYCO starts recording video from a camera.
Recording starts when a camera notifies a recording request with the recording HTTP API call (the zone=id portion is optional):
http://192.168.0.50/x/camerarec?camera=name&zone=id
Recording can also be triggered by the CameraRecTrigger() Java method or JavaScript function, or the CAMERAREC or CAMERARECFULL actions in EVENTS.
Parameters:
- event: string - the event identification string, either the camera name only or name:id if recording is triggered by a camerarec HTTP call with the optional zone=id parameter
- time: numeric - the current time in milliseconds.
CameraViewEvent
CameraViewEvent(camera, active)
CameraViewEvent() is called on changes of the live view status of cameras.
When at least one web client is showing the live feed from a camera, the camera is marked as active.
When no live feed request is received for a several consecutive seconds, the camera is marked as not active.
Parameters:
- camera: string - the camera name
- active: boolean - true if active, false if not.
DMX
DmxEvent
DmxEvent(channel, state)
Called after changes to DMX-512 channels.
Parameters:
- channel: numeric - DMX channel address, from 1 to 512 which might be preceded by the DMX gateway number, starting from 0
- state: numeric - the new channel value, from 0 to 255.
DmxFilter
DmxFilter(channel, state, reverse)
This function allows to filter the value of the status of each channel on the DMX-512 buses, sending to the gateway different values from those set in HSYCO.
This way, it is possible to apply chromatic corrections, or any on the fly translation of channels values.
This is a blocking function and is called when sending commands to the DMX gateway.
It is also called after reading current channels values from the gateway. In this case the conversion function should be symmetric and return a complementary value.
Parameters:
- channel: numeric - the DMX channel address, from 1 to 512 which might be preceded by the DMX gateway number, starting from 0
- state: numeric - the unfiltered value of the channel, from 0 to 255
- reverse: boolean - false if called when writing to the gateway; true if called when reading from the gateway.
Returns:
- numeric - the channel value that will be sent to the DMX gateway.
The JavaScript DmxFilter function is called only when the Java DmxFilter callback is not defined or returned the original value.
DmxStartupEvent
DmxStartupEvent(index)
Called when starting the monitor threads for each DMX bus, once per bus at the start of the execution of HSYCO, and also after every restart of the monitor thread, for example after communication errors.
It is safe, inside this function, to execute commands for the same DMX gateway.
This is a blocking function. The DMX driver will start after this function returns.
Parameters:
- Index: numeric - number of the DMX bus, starting from 0.
Infrared Control
IREvent
IREvent(received, irtransid, event)
This function is called when an IRTrans receives or sends an IR command from its local IR database.
IRTrans can only receive and decode infrared commands that have been previously stored in its internal FLASH memory database.
Parameters:
- received: boolean - true if the command has been received by the IRTrans, false if sent
- irtransid: numeric - IRTrans number, starting from 0 for the first device, based on the listing order of the IRTrans parameter in hsyco.ini
- event: string - the string of the command received or issued, formatted as: "remote_name,command".
I/O Servers
IOEvent
IOEvent(name, value)
Triggered by the value change of any data point of an I/O server.
Parameters:
- id: string - the server id and the name of the data point. According to the type of server, the format changes but it generally appears as server name, as declared the ioServers parameter in hsyco.ini, followed by a specific name representing the data point within the system
- value: string - the new value. For binary inputs or outputs, the returned values are “0” or “1”.
IOStartupEvent
IOStartupEvent(index)
Triggered by the start of the communication thread of each I/O server - once for each server at the beginning of the execution of HSYCO, and also after every reboot of the communication thread, for example after communication errors.
This is a blocking method. The I/O server driver will start after this function returns.
Parameters:
- index: numeric - the I/O server number, starting from 0, based on the listing order of the ioServers parameter in hsyco.ini.
Modbus
For detailed information about the Modbus protocol, and the response PDU formats, you should refer to the MODBUS Application Protocol Specification V1.1b documentation at: http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b.pdf
ModbusEvent
ModbusEvent(name, addr, unitid, pdu)
Called by the Modbus Server I/O Server on every Modbus request received from a Modbus client.
The returned byte array is used as the Modbus response PDU (function code and data).
Parameters:
- name: string - the name of the Modbus Server I/O server
- addr: string - IP address of the Modbus client
- unitid: numeric - the unit id set in the received Modbus request
- pdu: string - the request PDU data, in hexadecimal string format.
Returns:
- string - the response PDU data, in hexadecimal string format.
The JavaScript ModbusEvent function is called only when the Java ModbusEvent callback is not defined or returned a null value.
Network Services
httpCallEvent
httpCallEvent(address, secure, query)
Called when the HSYCO HTTP server receives a GET request with the following path:
/x/httpcall?query
The HTTP client's IP address must be in the trusted network range, or the httpcall request will be rejected, unless HTTPServerLowSecurityEnabled is true and the request is sent using HTTPS
This function shoud return a string, that will be sent as the text/plain answer to the HTTP client (with HTTP response code 200).
HSYCO will return a 404 Not Found response code if all of the following conditions are true:
- no HTTP event matches the query in EVENTS
- the httpCallEvent JavaScript callback is not defined in EVENTS, or doesn't return a value
- the httpCallEvent Java callback is not defined in user.java or in any plugins, or returns null.
If the httpCallEvent is defined both in JavaScript and Java, the Java version return value (unless null) will be used in the HTTP response.
Parameters:
- address: string - the IP address of the HTTP client
- secure: boolean - true if the request is sent to the HTTPS server, false if the request is sent to the HTTP server
- query: string - the string following the ? in the URL path.
Returns:
- string - the string to send as the text/plain answer to the HTTP client.
httpRawEvent
httpRawEvent(host, secure, version, httpmethod, gzip, contenttype, query, session, userid, indata)
Called when the HSYCO HTTP server receives a GET or POST request with the following path:
/x/raw
httpRawEvent is called only if the HTTP client's IP address is in the trusted network range and the HTTPServerLowSecurityEnabled option is true, or if the request has a valid user authentication cookie
The application code inside the httpRawEvent() function should return a complete HTTP response (both headers and body).
If multiple httpRawEvent() callbacks or functions are defined, only one should write the HTTP response.
Parameters:
- host: string - the IP address of the HTTP client
- secure: boolean - true if the request is sent to the HTTPS server, false if the request is sent to the HTTP server
- version: string - the HTTP version, as passed in the HTTP request header
- httpmethod: string - the HTTP request's method, "GET", "POST" or "HEAD"
- gzip: boolean - true if the client accepts compressed content (the Accept-Encoding header contains "gzip")
- contenttype: string - the HTTP request's content type (value of Content-Type header)
- query: string - the string following the ? in the URL path, or null if not present
- session: string - the authenticated session id, or null
- userid: string - the user id for requests having a valid authentication cookie, null otherwise
- indata: string - the POST data, or an empty string for GET or HEAD requests.
Returns:
- string - the application code should return the full HTTP response, including all headers.
Example:
function httpRawEvent(host, secure, version, httpmethod, gzip, contenttype, query, session, userid, indata) : { messageLog("host: " + host); messageLog("secure: " + secure); messageLog("version: " + version); messageLog("httpmethod: " + httpmethod); messageLog("gzip: " + gzip); messageLog("contenttype: " + contenttype); messageLog("query: " + query); messageLog("session: " + session); messageLog("userid: " + userid); messageLog("in: " + indata); var outdata = httpmethod + " data echoed from host [" + host + "] : " + indata + "\r\n"; var httpreply = version + " 200 OK\r\n"; httpreply += "Server: HSYCO\r\n"; httpreply += "Content-length: " + outdata.length + "\r\n"; httpreply += "Content-type: text/plain\r\n"; httpreply += "Cache-Control: no-store, no-cache\r\n\r\n"; httpreply += outdata; return httpreply; }
LocationEvent
LocationEvent(mac, ip, zoneId)
Called, if the location service is active, when a variation in the association of a client to the Wi-Fi Access Points is detected.
Parameters:
- mac: string - the MAC address of the client
- ip: string - the IP address of the client, if available, or null (the IP address could be null if the associated device is not connected to the HSYCO Web interface)
- zoneId: numeric - in case of association, it is the Access Point sequence number, according to the order defined in the LocationBases parameter in hsyco.ini; -1 if the client was de-associated from the Wi-Fi network.
LocationBeaconEvent
LocationBeaconEvent(session, address, userid, zone, distance, background)
Called when the HSYCO App detects a change in the proximity of one of the configured beacons. See Beacons on HSYCO App for iOS for additional information.
There is no guarantee that the event would be fired.
Network delays or errors could cause delayed triggering of this event.
Parameters:
- session: string - session id string that uniquely identifies the client session
- address: string - the beacon's address
- userid: string - the user id
- zone: string - the beacon's zone
- distance: string - far, near, immediate or off
- background: boolean - true if the app called the server while in background mode (app closed)
SysLogEvent
SysLogEvent(address, log)
Called when the HSYCO SYSLOG server receives a log message from a network client.
Note that this is a blocking call. The SYSLOG server will not process further messages until the last call has been processed.
Parameters:
- address: string - the IP address of the SYSLOG client
- log: string - SYSLOG log message.
PBX
PBXCallEvent
PBXCallEvent(host, caller, called)
Called when a call notification is sent to HSYCO by the PBX system.
If the method returns true, the request is recorded on the log file with the [OK] status, with [ERROR] otherwise.
The PBX should generate HTTP requests to the HSYCO Web Server, using the following formats:
http://192.168.0.50/x/vcall/<from>/<to>
or:
http://192.168.0.50/x/vcall?from=<from>&to=<to>
For example, the HTTP request:
http://192.168.0.50/x/vcall?from=21&to=25
is interpreted as a call notification from internal number 21 to number 25.
The HTTP client's IP address must be in the trusted network range, or the httpcall request will be rejected.
Parameters:
- host: string - the IP address of the PBX server
- caller: string - the caller number
- called: string - the called number.
Returns:
- boolean - return true to generate a log entry with [OK] status, false for [ERROR] status.
Squeezebox
SlimPowerEvent
SlimPowerEvent(index, power)
Called when a Squeezebox player is turned on or off.
Parameters:
- index: numeric - player number, starting from 0 for the first player, based on the listing order of the slimPlayers parameter in hsyco.ini
- power: numeric - 0: OFF, 1: ON.
SlimStatusEvent
SlimStatusEvent()
Called when a Squeezebox player changes its playback mode.
Parameters:
- index: numeric - player number, starting from 0 for the first player, based on the listing order of the slimPlayers parameter in hsyco.ini
- status: numeric - 0: OFF, 1: ON, 2: PAUSE, 3: PLAY, -1: UNKNOWN.
SlimVolumeEvent
SlimVolumeEvent(index, volume)
Called when a Squeezebox player changes its volume level.
Parameters:
- index: numeric - player number, starting from 0 for the first player, based on the listing order of the slimPlayers parameter in hsyco.ini
- volume: numeric - an integer number representing the volume change (not the absolute audio level) in a scale from 0 to 100; positive numbers correspond to a volume increase, negative numbers to a decrease.
Timers and Schedulers
UserTimerEvent
UserTimerEvent(name, active)
Called when a user timer or scheduler’s rule should be activated, and before executing the associated action in EVENTS.
It is also executed at the timer or scheduler’s rule deactivation.
This method must return a true value in order to make the timer or rule actually active and the associated actions executed.
Whenever the method returns false, the timer will not be activated, and the method will be called again once a minute for the scheduled duration of the timer.
In the same way, if the method returns false when the timer or rule is deactivated, the timer or rule will not be deactivated, extending the timer activation beyond the scheduled duration.
This is a blocking method.
Parameters:
- name: string - timer name or scheduler’s rule name
- active: boolean - true when activating and false when deactivating the timer or scheduler’s rule.
Returns:
- boolean - true to confirm the timer event, false to block the event.
The JavaScript UserTimerEvent function is alway called, but its return value is used only when the Java UserTimerEvent callback is not defined or returned true.
User Interface
pageEvent
pageEvent(address, session, userid, project, page)
Called when a Web client initially loads a project and when navigating between pages.
There is no guarantee that the event would be fired the exact moment the page is loaded.
Network delays or errors could cause delayed triggering of this event.
Parameters:
- address: string - the client’s IP address
- session: string - session id string that uniquely identifies the client session
- userid: string - the user id
- project: string - project’s id
- page: string - the page id, with the #landscape or #portrait suffix if the page has distinct orientation versions in the project.
loginEvent
loginEvent(address, session, userid)
Called when a user authenticates with a valid PIN or PIN/PUK.
Note that, while the session string passed to the pageEvent callback contains the browser global session id followed by a web view id, the session string passed to loginEvent only contains the global session id. The global session id is the portion of session id that is common between multiple web views open concurrently on the same web browser.
Parameters:
- address: string - the client’s IP address string in textual presentation
- session: string - session id string that uniquely identifies the client session
- userid: string - the user id.
logoutEvent
logoutEvent(address, session, userid, lock)
Called when a user logs out or locks the user interface.
Note that, while the session string passed to the pageEvent callback contains the browser global session id followed by a web view id, the session string passed to logoutEvent only contains the global session id. The global session id is the portion of session id that is common between multiple web views open concurrently on the same web browser.
Parameters:
- address: string - the client’s IP address string in textual presentation
- session: string - session id string that uniquely identifies the client session
- userid: string - the user id
- lock: boolean - false when logging out; true when the user locks the user interface.
uiClearEvent
uiClearEvent(session)
Called, following an explicit call of uiClear() or after the client session inactivity timeout expires, if the client session becomes active again (i.e. the client starts handshaking again with the server with the same session id).
Parameters:
- session: string - session id string that uniquely identifies the client session.
userCommand
userCommand(session, userid, name, param)
Called by user clicks on buttons created in the Web interface with the user objects, by a USER action in EVENTS, or by the user() Java method and JavaScript function. Also triggered by by the screensaver (see the Screensaver page for more details).
This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”.
If you want to navigate to a specific page when the button is pressed (it would be like pressing a Link object), return a string starting with "page:" followed by the page name; in this case, userCommand() will be called again when that popup or page is closed, with "/close" appended to param.
You can also use "page:back" or "page:forward" to move back and forth along the pages' navigation history. Use "page:close" to close a popup.
When the interface is loaded inside the HSYCO App (iOS or Android), you can send a specific command to the app by returning a string that starts with “app:“ followed by the command; the commands currently supported are “speech“, which enables the speech recognition, and “codescan“ which enables qr/bar code scanning.
Use "copy:<text>" to copy a text in the clipboard. In the HSYCO App you can also use "share:<text>" to open a popup with various options. This will behave like "copy" on browser.
As this callback may return data synchronously to the Web interface in response to a user command, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.
Parameters:
- session: string - a session id string that uniquely identifies the client session
- userid: string - the user id
- name: string - the name field of the user object
- param: string - the param of the user object
Returns:
- string - log or go to page, see text above. If this function doesn't return a value, an [ERROR] status is logged in the log file, while any other string causes the log of an [OK] status.
The JavaScript userCommand function is alway called, but its return value is used only when the Java userCommand callback is not defined or returned null or an empty string.
userSubmit
userSubmit(session, userid, name, fields)
This function is similar to userCommand(session, userid, name, param).
When userSubmit() is defined, it will be called when a submit button is pressed, while userCommand() will continue to be called on user buttons.
userSubmit() provides a more convenient access to the values of multiple input fields in a form.
This function can optionally return a string. Any returned string causes the log of an [OK] status. If you want to prevent logging, for example to avoid sensitive information to be written in the log file, you should return the string “!”.
If you want to force the Web interface to show a specific page after the button is pressed (it would be like pressing a link object), return a string starting with “page:” followed by the page name; in this case, userCommand() will be called when that popup or page is closed, with "/close" appended to param.
You can also use "page:back" or "page:forward" to move back and forth along the pages' navigation history. Use "page:close" to close a popup.
As this callback may return data synchronously to the Web interface in response to a user command, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.
Parameters:
- session: string - a session id string that uniquely identifies the client session
- userid: string - the user id
- name: string - the id of the (submit!id) object
- fields: array - the array of all input fields in the container where the (submit) object is located.
Returns:
- string - log or go to page, see text above. If this function doesn't return a value, an [ERROR] status is logged in the log file, while any other string causes the log of an [OK] status.
The JavaScript userSubmit function is alway called, but its return value is used only when the Java userCommand or userSubmit callback are not defined or returned null or an empty string.
Examples:
The following code shows how to retrieve all field names and values of a submitted form.
function userSubmit(session, user, name, values) : {
if (session.length > 0) {
messageLog(user + ', ' + name + '=' + values);
var keys = values.keySet().toArray();
for (var i = 0; i < keys.length; i++) {
messageLog(user + ', ' + keys[i] + ' = ' + values.get(keys[i]));
}
return "";
}
}
Create a project with a form and a few input fields in a container. Pressing the submit button should return something like this in the log file:
2014.01.31 13:54:32.034 - staff, submit1={keypad1=344, date1=20140131, input1=this is a text field} 2014.01.31 13:54:32.038 - staff, keypad1 = 344 2014.01.31 13:54:32.039 - staff, date1 = 20140131 2014.01.31 13:54:32.042 - staff, input1 = this is a text field 2014.01.31 13:54:32.043 - WEB USER COMMAND [submit1]: input1@this is a text field@date1@20140131@keypad1@344 [OK]
WebRootRequestEvent
WebRootRequestEvent(addr, secure, useragent)
This method is called when the Web server receives a root URL request. It can return a string to redirect the browser to a valid URL, or null to prevent redirection.
As this callback returns data synchronously to the Web interface in response to the HTTP request, its execution should be fast enough to avoid the timeout of the browser's request. To ensure a safe margin, it should complete in no more than one second.
Parameters:
- addr: string - the HTTP client’s address
- secure: boolean - true if this is an HTTPS request
- useragent: string - the Web browser’s user agent information.
Returns:
- string - optional return string containing a valid absolute or relative URL
Examples:
The following code redirects any root HTTP request received by the HSYCO server to the manager page.
function WebRootRequestEvent(addr, secure, useragent) : {
return "hsycoserver/manager";
}