These objects are available to every connector function, whatever protocol the device speaks. Start
with the JavaScript API — it explains what your script receives and what it must
produce — and come back here for the object you need.
One more global is always there and is documented outside this section, because rules use the very same
object: logger, for writing TRACE, DEBUG, INFO, WARN and ERROR traces. It is the way to see
what a running function is doing — see Debugging, which covers both the
logger API and the
WebSocket service that streams the traces live.
Reserved names
Because these helpers are injected as globals, their names are reserved. Do not declare variables called
cf, collection, response, snmp, utils, dlms, dlms_gas, provision or operation in your
script.
In this javascript code, it is possible to use some defined functions to define the connector function. We will explain
them below.
Input parameters
The main script will have access to the following main vars:
entity: json with flattened operation target device entity representation.
gateway: json with flattened gateway entity representation. It can be null.
response: json with default response data (device identifier, request id (if known)…)
collection: json with default collection data (device identifier if known)
payload: it can be of different types: json object, binary content or flat text. It can contain different types of information: request or response information, collected data….
contextParams: json object with execution context information. It can have some of this params:
apiKey: device or user apikey.
remoteIp: remote host when HTTP Rest Resource is invoked.
uri: opened Websocket complete uri or invoked HTTP Rest Resource complete uri.
path: opened Websocket relative path or invoked HTTP Rest Resource relative path. This is the path used as south criteria to filter CFs.
topic: MQTT Topic where the message arrived.
sessionIp: device session IP
Protocol clients and APIs: clients such as mqtt, ssh, snmp, dlms, dlms_gas, provision, and operation will be available for being used.
Depending on the type of CF, the script must have different outputs (regardless of whether other calls are
concatenated).
REQUEST CF
No output is mandatory, so return null; can be used, or no return statement defined at all. In this case the operation will not be finished until the response event is processed.
Although the return statement is not mandatory, it is possible to return the response object. If returned, it will be processed and the operation can be finalized directly.
RESPONSE CF
In this case, OpenGate Standard Response object must be returned. If nothing or null is returned, then no operation
update will be done.
response object functions can be used to complete full data.
COLLECTION CF
In this case, OpenGate Standard Iot Data Collection object must be returned. If nothing or null is returned, then no
collection will be done.
collection object functions can be used to complete full data.
Connector function execution concatenation
In some cases, it is possible to invoke the execution of other CFs once the current CF execution is finished.
These are allowed cases:
From REQUEST CF:
Invoke RESPONSE CF
Invoke COLLECTION CF
Invoke RESPONSE CF and COLLECTION CF
From RESPONSE CF:
Invoke COLLECTION CF
Other invocations will be ignored (for example, invoke RESPONSE CF from COLLECTION CF).
There are two help functions for this:
cf.response
cf.collection
JS API
cf.operationParameters(operationObj)
Extract from operationObj parameters field. This function could be used in REQUEST CFs, when the payload is Operation Request json.
Kind: global function Returns: * - Returns parameters field. It can be a complex object. If operationObj is not a correct Request object, null will be returned.
Creates OG step object used in opengate response object.
Kind: global function Returns: OG step object
Param
Type
Description
name
String
step name. If not provided null will be set.
result
String
step result. If not provided null will be set.
description
String
description string. If not provided, null will be assigned.
stepResponseList
String
array of stepResponse objects. If not provided, empty array will be assigned.
ogStepResponse(name, value)
Creates OG step response object, used in step object.
Kind: global function Returns: OG step response object
Param
Type
Description
name
*
step name. If not provided null will be set.
value
Object
object with value. If not provided empty object will be assigned.
httpRequest(request, payload)
Executes specified request with specified payload.
Kind: global function Returns: Object - JSON with response. It will have two fields: ‘statusCode’ with http result code and ‘body’ with response body content.
Param
Type
Description
request
Object
Object with requests parameters: ‘method’, ‘uri’ and ‘headers’. - ‘method’: GET, POST, PUT, DELETE. - ‘uri’: request uri. - ‘headers’: json with http request headers.
payload
*
data to be sent. It can be null.
webSocketMsg(payload, deviceId)
Send message to opened websocket
Kind: global function
Param
Type
Description
payload
*
data to be published. It will be converted to string.
deviceId
String
Device identifier with the opened websocket
entityValue(entity, datastream, index)
Extract from entity specified datastream “value” field value.
Kind: global function Returns: * - Specified datastream “value” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entity
Object
entity Object with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
entitiesValue(entities, datastream, index)
Extract from the first entity of entities array specified datastream “value” field value.
Kind: global function Returns: * - Specified datastream “value” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entities
Array
Array of objects with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
entityAt(entity, datastream, index)
Extract from entity specified datastream “at” field value.
Kind: global function Returns: Specified datastream “at” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entity
Object
entity Object with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
entityDate(entity, datastream, index)
Extract from entity specified datastream “date” field value.
Kind: global function Returns: Specified datastream “date” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entity
Object
entity Object with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
entitySource(entity, datastream, index)
Extract from entity specified datastream “source” field value.
Kind: global function Returns: Specified datastream “source” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entity
Object
entity Object with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
entitySourceInfo(entity, datastream, index)
Extract from entity specified datastream “sourceInfo” field value.
Kind: global function Returns: Specified datastream “sourceInfo” field. It can be complex object. null if datastream does not exist.
Param
Type
Description
entity
Object
entity Object with flattened entity.
datastream
String
Datastream name, for example: ‘provision.device.identifier’.
index
number
Array Index. If provided datastream is an array (i.e. comm module), element index must be specified.
log(…msg)
Creates Info level logging messages. It concatenates msg parameters in the final string to be logged.
Kind: global function
Param
Type
Description
…msg
any
The function takes as parameters a list of elements to be concatenated to generate the string message to be printed.
Builds a datapoint object and adds it to the specified datastream in the datastreams list in the collection global object.
Kind: global function Returns: Void
Param
Type
Description
datastreamId
string
Datastream identifier by which the datapoint will be identified.
value
any
Collected value. If not provided null will be set.
at
number
Number with collection timestamp in seconds. If not provided null will be set.
source
string
String with source name. If not provided null will be set.
sourceInfo
string
String with source description. If not provided null will be set.
Example of use:
varnow= Date.now() /1000;
collection.addDatapoint('device.name', 'collected name from cf', now,'mySource','mySourceInfo');
collection.setFeed(datastreamId, feed)
Sets the feed name to a specific datastream in the datastreams list in the collection global object.
Kind: global function Returns: Void
Param
Type
Description
datastreamId
string
Datastream identifier by which the datapoint will be identified.
feed
string
The feed name to set to the specified datastream.
Example of use:
collection.setFeed('device.name', 'myFeed');
collection.send()
Sends a collection message to the OpenGate’s collection messages flow using the datastreams list in the collection global object, after that this list is cleaned.
Kind: global function Returns: Void
Example of use:
collection.send();
collection.getValue(datastream, dpIndex)
Searches for a datapoint value for the specified datastreamId. It is possible to specify the datapoint index inside the datastream. If not found, a null value will be returned.
Kind: global function Returns: *
Param
Type
Description
datastream
string
Datastream identifier which value must be returned
dpIndex
number
Datapoint index. If not defined first datapoint will be returned
Example of use:
vardpValue=collection.getValue('device.name');
// dpValue will be 'collected name from cf'
Operation Steps API
Connector functions JS API guide for the response object and immediate operation steps notification
This API provides methods on the response global object to build operation step results, notify them immediately, and set the operation result code.
This method sets the UNKNOWN_RESULT statusCode with the provided description.
Kind: global function Returns: Void
Param
Type
Description
statusDescription
string
Descriptive text for result.
Example of use:
response.unknownResult("Unknow result from CF");
response will contain the following data:
{
"operation": {
"response": {
//...
"resultCode": "UNKNOWN_RESULT",
"resultDescription": "Unknow result from CF",
//...
}
}
}
Operation JavaScript API
Connector functions - Active Operation JS API guide
This API allows users to read and activate operations from a connector function.
operation – Main Object
The operation object is the main object. It allows making requests to the Operations API.
To do the request, the object operation use the HTTP-Client API, you can use all attribute of this interface, for example, to add a certificate http.client.certificate=XXX
operation – Object Properties
Property
Type
Description
deviceId
string
Target device id of the operation pending
apiKey
string
Api-Key to use in the request to the Operations-API
host
string
Host to use in the request to the Operations-API
By default, the attributes will be set with the value of the context.
operation – Functions
operation.getAllPending()
Read and return the selected device operations pending (with status WAITING_FOR_CONNECTION) of the user to execute the CFx
This function does not require parameters.
The operation.getAllPending function returns an object, described as follows:
Property
Type
Attributes
Description
error
null or string
Message
Description of the exception error caught, or error sent by the request. It will be null when the request contains no errors
opResult
Object
statusCode, Object
Contains statusCode, and the result list object of the request, when it’s OK
Example of use with default values:
varopResult=operation.getAllPending();
operation.getNotFinished()
Read and return the selected device operations that are not finished
This function does not require parameters.
Function operation.getNotFinished return object, descript like:
Property
Type
Attributes
Description
error
null or string
Message
Description of the exception error caught, or error sent by the request. will be null, when the request no contains errors
opResult
Object
statusCode, Object
Contains statusCode, and the result list object of the request, when it’s OK
Example of use:
varopResult=operation.getNotFinished();
operation.getByCustomCondition(customCondition)
Read and return the selected device operations that match a custom filter condition
This API allows users to manage entity provisioning (creation and retrieval) from a connector function.
provision – Main Object
The provision global object provides properties and methods to interact with the Provisioning API.
provision – Object Properties
Property
Type
Default
Description
apiKey
string
If available, current connection’s apikey
API Key for the request.
host
string
Frontend’s default endpoint
Host for the Provisioning API.
identifier
string
null
Identifier of the entity to act upon.
organization
string
Device`s organization
Organization to which the entity belongs.
serviceGroup
string
"emptyServiceGroup"
Service Group for the entity.
defaultChannel
string
"defaultChannel"
Channel to which the entity belongs.
plan
string
null
Provisioning plan to apply.
extraDatastreams
Array
[]
Extra data as an array of objects like {datastreamId:value} pairs.
provision – Functions
provision.get(id)
Retrieves an existing entity from the database with specified identifier.
Kind: global function Returns: Object - If entity is found, entity data will be returned in result. If it is not found, result field will be null. If some error happened, it will be returned in error field.
Param
Type
Default
Description
id
string
this.identifier
(Optional) Entity identifier. If not defined identifier field will be used.
Example with provision.identifier:
provision.identifier="device_123";
constresp=provision.get();
if (!resp.error&&resp.result) {
logger.info("Entity identifier:", resp.result._value("provision.administration.identifier"));
}
Example with parameter:
constresp=provision.get("device_123");
if (!resp.error&&resp.result) {
logger.info("Entity identifier:", resp.result._value("provision.administration.identifier"));
}
Example with unexepected error:
constresp=provision.get("device_123");
if (resp.error) {
logger.error("Some error:", resp.error);
}
The object resp.result contains then same functions than entity object.
provision.create(fullBody)
Creates a new entity in the platform.
Kind: global function
Param
Type
Description
fullBody
Object
(Optional) Complete JSON body for the creation request. If not provided, it is generated from the object properties.
Returns: Object - An object containing either result (201 status) or error.
Sets a call for a RESPONSE connector function, if there is one that matches the south criteria indicated in responseFunctionCriteria, setting its input payload to the value of responsePayload.
Kind: global function Returns: Void
Param
Type
Description
responseFunctionCriteria
string
The south criteria that will be used to find a RESPONSE connector function.
responsePayload
any
It can be a String or a JSON object. In case it is null or not provided, the current connector function response object will be used instead. It is the in payload for the concatenated RESPONSE connector function.
Sets a call for a COLLECTION connector function, if there is one that matches the south criteria indicated in collectionFunctionCriteria, setting its input payload to the value of collectionPayload.
Kind: global function Returns: Void
Param
Type
Description
collectionFunctionCriteria
string
The south criteria that will be used to find a COLLECTION connector function.
collectionPayload
any
It can be a String or a JSON object. In case it is null or not provided, the current connector function response object will be used instead. It is the in payload for the concatenated COLLECTION connector function.
The address which the type will be calculated for.
Example of use:
varaddressType=utils.odm.getAddressTypeFromAddress("[IP_ADDRESS]");
//addressType will be: ipv4
varaddressType=utils.odm.getAddressTypeFromAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
//addressType will be: ipv6
Executes specified request with specified payload.
Kind: global function Returns: Object - JSON with response. It will have two fields: ‘statusCode’ with http result code and ‘body’ with response body content.
Param
Type
Description
request
Object
Object with requests parameters: ‘method’, ‘uri’ and ‘headers’. - ‘method’: GET, POST, PUT, DELETE. - ‘uri’: request uri. - ‘headers’: json with http request headers.
Connector functions JS API guide for crypto utility
This file provides methods for different crypto utilities using crypt global object.
Encrypt and decrypt messages with AES algorithms
The crypt.aes global object provides all the functions for encryption and decryption using the AES algorithm.
These JavaScript functions use the cipher algorithm identifier required by the Java method javax.crypto.Cipher.getInstance(algorithm), composed of {CipherName}/{cipherMode}/{CipherPadding}. Some examples are:
AES/CBC/NoPadding
AES/CBC/PKCS5Padding
AES/ECB/NoPadding
AES/ECB/PKCS5Padding
AES/GCM/NoPadding
Data hashing
The crypt.hmac global object provides functions for hashing data.
Encrypt the data using the selected AES algorithm with the provided shared key.
Kind: global function Returns: Uint8Array
Param
Type
Description
algorithm
string
algorithm identifier, as required in java javax.crypto.Cipher.getInstance(algorithm). For example: AES/CBC/PKCS5Padding
key
Uint8Array
key used to encrypt the data. In AES algorithms. The key size must match the selected algorithm. For example, AES algorithms support keys of 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256).
ivParam
Uint8Array
Initialization vector (IV) used in encryption. Only allowed or required depending on the selected algorithm.
Decrypt the data using the selected AES algorithm with the provided shared key.
Kind: global function Returns: Uint8Array
Param
Type
Description
algorithm
string
algorithm identifier, as required in java javax.crypto.Cipher.getInstance(algorithm). For example: AES/CBC/PKCS5Padding
key
Uint8Array
key used to decrypt the data. In AES algorithms. The key size must match the selected algorithm. For example, AES algorithms support keys of 16 bytes (AES-128), 24 bytes (AES-192), or 32 bytes (AES-256).
ivParam
Uint8Array
Initialization vector (IV) used in encryption. Only allowed or required depending on the selected algorithm.