Core JavaScript API

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.

What you get and what you return

Page Object Use it to
JavaScript API Understand the input variables, the expected output per connector function type, and how executions concatenate
Entity entity, gateway Read data stream values, timestamps and source fields of the device
Inner Collections collection Collect data points and set fields from inside the script
Operation Steps response Build operation steps and set result codes

Reaching back into the platform

Page Object Use it to
Operation operation Read and activate the device’s pending operations
Provision provision Retrieve and create entities through the provisioning API
Concatenated Connector Functions cf Chain RESPONSE and COLLECTION executions together

Helpers

Page Object Use it to
Utils utils AT commands, date handling, context, encryption and HTTP helpers
Cryptography Encrypt and decrypt with AES, hash with HMAC

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.

Subsections of Core JavaScript API

JavaScript API

Connector functions JS API guide

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.

Here there is an example of entity or gateway:

entity = {
    "provision.administration.channel": {
        "_value": {
            "_current": {
                "value": "battery_channel",
                "date": "2017-12-01T08:52:37.563Z",
                "at": "2017-12-01T08:52:37.563Z"
            }
        }
    },
    "provision.administration.identifier": {
        "_value": {
            "_current": {
                "value": "device_battery_id",
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.57Z",
                "at": "2017-12-01T08:52:37.57Z"
            }
        }
    },
    "provision.administration.organization": {
        "_value": {
            "_current": {
                "value": "battery_organization",
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.566Z",
                "at": "2017-12-01T08:52:37.566Z"
            }
        }
    },
    "provision.administration.plan": {
        "_value": {
            "_current": {
                "value": "FLOW_RATE_100",
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.565Z",
                "at": "2017-12-01T08:52:37.565Z"
            }
        }
    },
    "provision.administration.serviceGroup": {
        "_value": {
            "_current": {
                "value": "emptyServiceGroup",
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.561Z",
                "at": "2017-12-01T08:52:37.561Z"
            }
        }
    },
    "provision.device.communicationModules[].identifier": [
        {
            "_index": {
                "path": "provision.device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "provType": "MONITORING",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": "commsMod_battery_id",
                    "provType": "MONITORING",
                    "date": "2017-12-01T08:52:37.577Z",
                    "at": "2017-12-01T08:52:37.577Z"
                }
            }
        }
    ],
    "provision.device.communicationModules[].subscription.address": [
        {
            "_index": {
                "path": "provision.device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "provType": "MONITORING",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": {
                        "type": "IPV4",
                        "value": "99.1.1.71",
                        "apn": "myapnprov.es"
                    },
                    "provType": "REFERENCE",
                    "date": "2017-12-01T08:52:37.624Z",
                    "at": "2017-12-01T08:52:37.624Z"
                }
            }
        }
    ],
    "provision.device.communicationModules[].subscription.identifier": [
        {
            "_index": {
                "path": "provision.device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "provType": "MONITORING",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": "subscription_battery_id",
                    "provType": "MONITORING",
                    "date": "2017-12-01T08:52:37.626Z",
                    "at": "2017-12-01T08:52:37.626Z"
                }
            }
        }
    ],
    "provision.device.identifier": {
        "_value": {
            "_current": {
                "value": "device_battery_id",
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.636Z",
                "at": "2017-12-01T08:52:37.636Z"
            }
        }
    },
    "provision.device.location": {
        "_value": {
            "_current": {
                "value": {
                    "position": {
                        "type": "Point",
                        "coordinates": [
                            -3.7028,
                            40.41675
                        ]
                    },
                    "postal": "28013"
                },
                "provType": "MONITORING",
                "date": "2017-12-01T08:52:37.64Z",
                "at": "2017-12-01T08:52:37.64Z"
            }
        }
    },
    "resourceType": {
        "_value": {
            "_current": {
                "value": "entity.device",
                "provType": "IDENTIFIER",
                "date": "2017-12-01T08:52:37.643Z",
                "at": "2017-12-01T08:52:37.643Z"
            }
        }
    },
    "device.communicationModules[].identifier": [
        {
            "_index": {
                "path": "device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": "commsMod_battery_id",
                    "date": "2017-12-01T08:52:37.577Z",
                    "at": "2017-12-01T08:52:37.577Z"
                }
            }
        }
    ],
    "device.communicationModules[].subscription.address": [
        {
            "_index": {
                "path": "device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": {
                        "type": "IPV4",
                        "value": "99.1.1.71",
                        "apn": "myapn.es"
                    },
                    "date": "2017-12-01T08:52:37.624Z",
                    "at": "2017-12-01T08:52:37.624Z",
                    "source": "DEVICE_OPENGATE_HTTP",
                    "sourceInfo": "IoT Data Message Received"
                }
            }
        }
    ],
    "device.communicationModules[].subscription.identifier": [
        {
            "_index": {
                "path": "device.communicationModules[].identifier",
                "value": {
                    "_current": {
                        "value": "commsMod_battery_id",
                        "date": "2017-12-01T08:52:37.577Z",
                        "at": "2017-12-01T08:52:37.577Z"
                    }
                }
            },
            "_value": {
                "_current": {
                    "value": "subscription_battery_id",
                    "date": "2017-12-01T08:52:37.626Z",
                    "at": "2017-12-01T08:52:37.626Z",
                    "source": "DEVICE_OPENGATE_HTTP",
                    "sourceInfo": "IoT Data Message Received"
                }
            }
        }
    ],
    "device.identifier": {
        "_value": {
            "_current": {
                "value": "device_battery_id",
                "date": "2017-12-01T08:52:37.636Z",
                "at": "2017-12-01T08:52:37.636Z",
                "source": "DEVICE_OPENGATE_HTTP",
                "sourceInfo": "IoT Data Message Received"
            }
        }
    },
    "device.temperature.value": {
        "_value": {
            "_current": {
                "value": 25.3,
                "date": "2017-12-01T08:52:37.64Z",
                "at": "2017-12-01T08:52:37.64Z",
                "source": "DEVICE_OPENGATE_HTTP",
                "sourceInfo": "IoT Data Message Received"
            }
        }
    }
}

contextParams some examples:

REQUEST Connector function:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "sessionIp": "127.0.0.1"
}

COLLECTION or RESPONSE Connector function for MQTT connector:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "topic": "some/topic"
}

COLLECTION or RESPONSE Connector function for HTTP Rest endpoints:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "path": "context/path",
  "uri": "http://http_url/device_id/context/path",
  "remoteIp": "remote_device_ip"
}

COLLECTION or RESPONSE Connector function for Websocket connection:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "path": "context/path",
  "uri": "ws://ws_url/device/context/path"
}

COLLECTION or RESPONSE Connector function for SNMP connector:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "uri": "snmp://oid"
}

COLLECTION Connector function for DLMS connection:

{
  "apiKey": "97c9ceae-c4ee-49ea-ad50-e499bb55ac63",
  "obisCode": "0.1.2.3.3.5"
}

Connector function script output

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.

Param Type
operationObj Object

Example of use:

var operationParameters = cf.operationParameters(operationObj);

cf.operationTimestamp(operationObj)

Extract from operationObj timestamp field. This function could be used in REQUEST CFs, when the payload is Operation Request json.

Kind: global function
Returns: number - Returns timestamp field. If operationObj is not correct Request object, null will be returned.

Param Type
operationObj Object

cf.operationName(operationObj) String

Extract from operationObj name field. This function could be used in REQUEST CFs, when the payload is Operation Request json.

Kind: global function
Returns: String - Returns name field. If operationObj is not correct Request object, null will be returned.

Param Type
operationObj Object

cf.operationId(operationObj) String

Extract from operationObj id field. This function could be used in REQUEST CFs, when the payload is Operation Request json.

Kind: global function
Returns: String - Returns id field. If operationObj is not correct Request object, null will be returned.

Param Type
operationObj Object

cf.operationDeviceId(operationObj) String

Extract from operationObj deviceId field. This function could be used in REQUEST CFs, when the payload is Operation Request json.

Kind: global function
Returns: String - Returns deviceId field. If operationObj is not correct Request object, null will be returned.

Param Type
operationObj Object

JS API - Deprecated functions

responseCF(responseData, responseFunctionCriteria)

Used in Request connector functions to define a concatenated Response action.

Kind: global function

Param Type Description
responseData * data to be used as payload in Response Connector Function.
responseFunctionCriteria String the criteria to be used to search response connector function.

collectCF(collectionData, collectionFunctionCriteria)

Used in Request or Response connector functions to define a concatenated Collection action.

Kind: global function

Param Type Description
collectionData * data to be used as payload in Collection Connector Function.
collectionFunctionCriteria String the criteria to be used to search collection connector function.

publishOnTopic(payload, topic, deviceId)

Publish specified payload for specified topic and device.

Kind: global function

Param Type Description
payload * Data to be published. It will be converted to string.
topic String topic uri.
deviceId String device id.

ogCollection(datastreams, device, version)

Creates OG collection main object.

Kind: global function
Returns: Object - Json with Opengate Data Collection object.

Param Type Description
datastreams Array Array of datastreams objects. If not specified empty array will be set.
device String String with deviceId. If not defined null will be set.
version String String with version. If not specified, “1.0.0” value will be used.

ogCollectionDs(datastreamId, feed, datapoints)

Creates OG collection datastream object.

Kind: global function
Returns: Object - Json with Opengate Data Collection Datastream object.

Param Type Description
datastreamId String String with datastreamid. If not provided null will be set.
feed String String with feed name. If not provided null will be set.
datapoints Array Array of datapoints objects. If not provided empty array will be set.

ogCollectionDp(value, at, source, sourceInfo)

Creates OG collection datapoint object.

Kind: global function

Param Type Description
value * collected value. If not provided null will be set.
at number Number with collection timestamp. 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.

addOgCollectionDp(datapoint, ogCollection, datastreamId, feed)

Adds datapoint to specified datastream in the collection object, if datastream does not exist, it creates the datastream.

Kind: global function

Param Type Description
datapoint Object Datapoint object to be added.
ogCollection Object Opengate collection object with current collection data.
datastreamId String Datastream object identifier in collection object. If not exist, it will be created.
feed String feed name, only used if the datastream must be created.

ogResponse(id, name, deviceId, resultCode, resultDescription, steps, timestamp, trustedBoot, version)

Creates OG response object

Kind: global function
Returns: Object - OG response object

Param Type Description
id String operation request id. If not provided null will be set.
name String launched operation name. If not provided null will be set.
deviceId String operation request device id. If not provided null will be set.
resultCode String operation result code. If not provided null will be set.
resultDescription String operation result description. If not provided null will be set.
steps Array If not defined, empty array will be defined.
timestamp String Operation response timestamp. If not provided current timestamp will be set.
trustedBoot String Trusted boot value. If not provided null will be set.
version String If not specified “8.0” will be set.

ogStep(name, result, description, stepResponseList)

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.

encryptString(originalValue, datastreamConfiguration, organizationName)

Encrypt an original string with the configuration established by the datastream of the organization

Kind: global function
Returns: The originalValue encrypted

Param Type Description
originalValue string The value to encrypt.
datastreamConfiguration string The datastream of provision type, of the datamodel that define this value. This datastream has the configuration of encryption.
organizationName string The organization name to which the datamodel belongs.

decryptString(encryptedValue, datastreamConfiguration, organizationName)

Decrypt an encrypted string with the configuration established by the datastream of the organization

Kind: global function
Returns: The encryptedValue decrypted

Param Type Description
encryptedValue string The encrypted value to decrypt.
datastreamConfiguration string The datastream of provision type, of the datamodel that define this value. This datastream has the configuration of encryption.
organizationName string The organization name to which the datamodel belongs.

getAddressTypeFromAddress(address)

Calculates the address type from a given address

Kind: global function
Returns: The address type

Param Type Description
address string The address which the type will be calculated for.

Entity JavaScript API

Connector functions entity JS API guide

This API allows users to extract data from entity object.

Entity Object Methods

The following methods also work with the gateway object since it has the same structure as entity.

entity._value (datastream, index)

Extract from entity specified datastream “value” field value using parameters

Returns: * - Specified datastream “value” field. It can be complex object. null if datastream does not exist.

Param Type Description
datastream string The datastream name.
index any Element index of datastream array.

Example of use:

var value = entity._value('provision.device.identifier');

entity._at (datastream, index)

Extract from entity specified datastream “at” field value using parameters

Returns: Specified datastream “at” field. It can be complex object. null if datastream does not exist.

Param Type Description
datastream string The datastream name.
index any Element index of datastream array.

Example of use:

var at = entity._at('provision.device.identifier');

entity._date (datastream, index)

Extract from entity specified datastream date field value using parameters

Returns: Specified datastream “date” field. It can be complex object. null if datastream does not exist.

Param Type Description
datastream string The datastream name.
index any Element index of datastream array.

Example of use:

var date = entity._date('provision.device.identifier');

entity._source (datastream, index)

Extract from entity specified datastream “source” field value using parameters

Returns: Specified datastream “source” field. It can be complex object. null if datastream does not exist.

Param Type Description
datastream string The datastream name.
index any Element index of datastream array.

Example of use:

var source = entity._source('provision.device.identifier');

entity._sourceInfo(datastream, index)

Extract from entity specified datastream “sourceInfo” field value using parameters

Returns: Specified datastream “sourceInfo” field. It can be complex object. null if datastream does not exist.

Param Type Description
datastream string The datastream name.
index any Element index of datastream array.

Example of use:

var sourceInfo = entity._sourceInfo('provision.device.identifier');

Inner Collections API

Connector functions JS API guide for inner collections

This file provides methods to collect data inside a connector function script execution. These methods belong to collection global object.

JS API

collection.addDatapoint(datastreamId, value, at, source, sourceInfo)

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:

var now = 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:

var dpValue = 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.

JS API

response.addStep(name, result, description, stepResponseList)

Builds a step result object and adds it to the steps list in the response global object.

Kind: global function
Returns: Void

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 Step result description. If not provided null will be set.
stepResponseList string StepResponse objects array. If not provided, empty array will be assigned.

Example of use:

response.addStep('FACTORY_RESET', 'SUCCESSFUL', 'direct step from CF');

response.sendSteps()

Sends a step response message to the OpenGate’s operation messages flow using the steps list in the response object, after that this list is cleaned.

Kind: global function
Returns: Void

Example of use:

response.sendSteps();

response.successful(statusDescription)

This method sets the SUCCESSFUL statusCode with the provided description.

Kind: global function
Returns: Void

Param Type Description
statusDescription string Descriptive text for result.

Example of use:

response.successful("CF finished correctly");

response will contain the following data:

{
    "operation": {
        "response": {
            //...
            "resultCode": "SUCCESSFUL",
            "resultDescription": "CF finished correctly",
            //...
        }
    }
}

response.errorProcessing(statusDescription)

This method sets the ERROR_PROCESSING statusCode with the provided description.

Kind: global function
Returns: Void

Param Type Description
statusDescription string Descriptive text for result.

Example of use:

response.errorProcessing("Error executing CF");

response will contain the following data:

{
    "operation": {
        "response": {
            //...
            "resultCode": "ERROR_PROCESSING",
            "resultDescription": "Error executing CF",
            //...
        }
    }
}

response.errorInParam(statusDescription)

This method sets the ERROR_IN_PARAM statusCode with the provided description.

Kind: global function
Returns: Void

Param Type Description
statusDescription string Descriptive text for result.

Example of use:

response.errorInParam("Incorrect param from CF");

response will contain the following data:

{
    "operation": {
        "response": {
            //...
            "resultCode": "ERROR_IN_PARAM",
            "resultDescription": "Incorrect param from CF",
            //...
        }
    }
}

response.notSupported(statusDescription)

This method sets the NOT_SUPPORTED statusCode with the provided description.

Kind: global function
Returns: Void

Param Type Description
statusDescription string Descriptive text for result.

Example of use:

response.notSupported("Not supported from CF");

response will contain the following data:

{
    "operation": {
        "response": {
            //...
            "resultCode": "NOT_SUPPORTED",
            "resultDescription": "Not supported from CF",
            //...
        }
    }
}

response.errorTimeout(statusDescription)

This method sets the ERROR_TIMEOUT statusCode with the provided description.

Kind: global function
Returns: Void

Param Type Description
statusDescription string Descriptive text for result.

Example of use:

response.errorTimeout("Timeout error from CF");

response will contain the following data:

{
    "operation": {
        "response": {
            //...
            "resultCode": "ERROR_TIMEOUT",
            "resultDescription": "Timeout error from CF",
            //...
        }
    }
}

response.unknownResult(statusDescription)

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:

var opResult = 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:

var opResult = operation.getNotFinished();

operation.getByCustomCondition(customCondition)

Read and return the selected device operations that match a custom filter condition

Param Type Description
customCondition Object Filter condition to apply (e.g., { 'eq': { 'operationStatus': 'IN_PROGRESS' } })

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:

var opResult = operation.getByCustomCondition({ 'eq': { 'operationStatus': 'IN_PROGRESS' } });
opResult – Object Functions

opResult is a JSON List Object returned by the operation.getAllPending function. You can use the following functions:

Function Return Description
activate null or string Activates the target operation. Returns null when the activation is OK, otherwise returns the error cause message
getRequest Object Builds and returns the request the device must send to respond to the operation

The object -opResult- contains all attributes and functions of the response (operation) object.

activate()

Activate the target operation selected with parameters of the context (Update to IN_PROGRESS the operation)

This function does not require parameters.

Example of use with default values:

var opResult = operation.getAllPending();
if (opResult.error) {
    return error;
}
opResult.forEach(op => op.activate());
getRequest()

Builds and returns the request the device must send to respond to the operation

This function does not require parameters.

reqRes – Object return the getRequest function

reqRes is a JSON Object returned by the getRequest function, described as follows:

Property Return Description
operation Object Main object to do the request

– Attributes of operation

Property Return Description
request Object Secondary main object to do the request

– Attributes of request

Property Return Description
name Object Operation name target of the request
id Object Operation identifier target of the request
parameters Object Parameters to use in the request
timestamp Object Operation time on do the request

By default, the attributes will be set with the value of the target operation.

Example getRequest object return:

{ 
    'operation': {
        'request': {
            'name': 'opName',
            'id': 'ce02792a-3a37-11f0-a48d-52540044ee01',
            'parameters': {},
            'timestamp': Date.now()
        }
    }
}

Example of use getRequest function:

var opResult = operation.getAllPending();
if (opResult.error) {
    return error;
}
opResult.forEach(op => {
        op.activate();
        http.client.body = op.getRequest();
        var httpResp = http.client.post();
        if (httpResp.statusCode != 201) {
            throw Error('Unexpected response:', httpResp);
        }
    }
);

Provision JavaScript API

Connector functions - Provision JS API guide

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";
const resp = provision.get();
if (!resp.error && resp.result) {
    logger.info("Entity identifier:", resp.result._value("provision.administration.identifier"));
}

Example with parameter:

const resp = provision.get("device_123");
if (!resp.error && resp.result) {
    logger.info("Entity identifier:", resp.result._value("provision.administration.identifier"));
}

Example with unexepected error:

const resp = 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.

Example using properties:

provision.identifier = "new_device_001";
provision.plan = "TEST_PLAN";
provision.extraDatastreams = [{ "provision.device.name": "cellName" }, { "provision.device.administrativeState": "ACTIVE" }, { "provision.device.specificType": "COMHUB" }, { "provision.tec": "NBIoT Cell" }];
const resp = provision.create();
if(!resp.error && resp.result == 201) {
    logger.info('Created');
} else {
    logger.error('Error creating entity:', resp.error);
}

Previous example will create with following body:

{
    "provision.administration.channel": {
        "_value": {
            "_current": {
                "value": "defaultChannel"
            }
        }
    },
    "provision.administration.identifier": {
        "_value": {
            "_current": {
                "value": "new_device_001"
            }
        }
    },
    "provision.administration.organization": {
        "_value": {
            "_current": {
                "value": "deviceOrg"
            }
        }
    },
    "provision.administration.serviceGroup": {
        "_value": {
            "_current": {
                "value": "emptyServiceGroup"
            }
        }
    },
    "provision.administration.plan": {
        "_value": {
            "_current": {
                "value": "TEST_PLAN"
            }
        }
    },
    "provision.device.name": {
        "_value": {
            "_current": {
                "value": "cellName"
            }
        }
    },
    "provision.device.administrativeState": {
        "_value": {
            "_current": {
                "value": "ACTIVE"
            }
        }
    },
    "provision.device.specificType": {
        "_value": {
            "_current": {
                "value": "COMHUB"
            }
        }
    },
    "provision.tec": {
        "_value": {
            "_current": {
                "value": "NBIoT Cell"
            }
        }
    }
}

If fullBody is provided, it will be used as the request body instead of building it from the object properties.

Example:

const body = {
    "provision.administration.channel": {
        "_value": {
            "_current": {
                "value": "defaultChannel"
            }
        }
    },
    "provision.administration.identifier": {
        "_value": {
            "_current": {
                "value": "new_device_001"
            }
        }
    },
    "provision.administration.organization": {
        "_value": {
            "_current": {
                "value": "deviceOrg"
            }
        }
    },
    "provision.administration.serviceGroup": {
        "_value": {
            "_current": {
                "value": "emptyServiceGroup"
            }
        }
    }
};
const resp = provision.create(body);
if(!resp.error && resp.result == 201) {
    logger.info('Created');
} else {
    logger.error('Error creating entity:', resp.error);
}

Concatenated Connector Functions API

Concatenated connector functions JS API guide

This file provides methods to build concatenated function executions. These methods belong to cf global object.

JS API

cf.response(responseFunctionCriteria, responsePayload)

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.

Example of use:

var resp = {
    'result': {
        'code': 'SUCCESSFUL',
        'description': 'Operation finished successful'
    },
    'data': {}
};

cf.response('snmps://1.0.1.4.5.123456.1.7', resp);

cf.collection(collectionFunctionCriteria, collectionPayload)

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.

Example of use:

var colMsg = {
    '1.0.1.4.5.123456.1.7.1': 'device name',
    '1.0.1.4.5.123456.1.7.2': 'device description',
};

cf.collection('snmps://1.0.1.4.5.123456.1.7', colMsg);

UTILS JavaScript API

Connector functions UTILS JS API guide

In this javascript code, there are helper operations available to help users who are building their own functions. We will explain them below.

JS UTILS API

These operations are grouped by their topic, at this time the available areas are:

  • AT commands
  • Endesa commands
  • ODM commands
  • Time commands

utils.atcmd.toDBm(value)

Translates the response got by the ‘AT+CSQ’ command, which is the GSM signal strength and a numerical value, to its corresponding dBm value.

Kind: global function
Returns: The translation to dBm value

Param Type Description
value number The GSM signal strength.

Example of use:

var dbVal = utils.atcmd.toDBm(1234);

utils.endesa.torscp(value)

Param Type Description
value string value to be converted

Example of use:

var val = utils.endesa.torscp("1234");

utils.endesa.toDbmPlusQuality(value)

Param Type Description
value string value to be converted

Example of use:

var val = utils.endesa.toDbmPlusQuality("1234");

utils.endesa.prepareMsisdn(msisdn)

If msisdn starts with “34”, then returns the value without “34”. Kind: global function
Returns: returns msisdn parameter without format

Param Type Description
msisdn string msisdn to be converted

Example of use:

var newMsisdn = utils.endesa.prepareMsisdn("341234567890");
//newMsisdn will be: 1234567890

utils.endesa.commandFrom(command)

Depending on the command value, specific translation will be returned.

Kind: global function
Returns: returns msisdn parameter without format

Param Type Description
command string command to be translated

Example of use:

var newCommand = utils.endesa.commandFrom("9600;8E1");
//newCommand will be: ATS37=9S13=1\r\n

utils.odm.addValueToContext(key,value)

Kind: global function

Param Type Description
key string key to be added to context
value string value to be added to context

Example of use:

utils.odm.addValueToContext("key", "value");

utils.odm.sleep(time)

Sleeps for specified time

Param Type Description
time number time to sleep in milliseconds

Example of use:

utils.odm.sleep(1000);

utils.odm.encryptString(originalValue, datastreamConfiguration, organizationName)

Encrypt an original string with the configuration established by the datastream of the organization

Kind: global function
Returns: The originalValue encrypted

Param Type Description
originalValue string The value to encrypt.
datastreamConfiguration string The datastream of provision type, of the datamodel that define this value. This datastream has the configuration of encryption.
organizationName string The organization name to which the datamodel belongs.

Example of use:

var encryptedValue = utils.odm.encryptString("originalValue", "datastreamConfiguration", "organizationName");

utils.odm.decryptString(encryptedValue, datastreamConfiguration, organizationName)

Decrypt an encrypted string with the configuration established by the datastream of the organization

Kind: global function
Returns: The encryptedValue decrypted

Param Type Description
encryptedValue string The encrypted value to decrypt.
datastreamConfiguration string The datastream of provision type, of the datamodel that define this value. This datastream has the configuration of encryption.
organizationName string The organization name to which the datamodel belongs.

Example of use:

var decryptedValue = utils.odm.decryptString("encryptedValue", "datastreamConfiguration", "organizationName");

utils.odm.getAddressTypeFromAddress(address)

Calculates the address type from a given address

Kind: global function
Returns: The address type

Param Type Description
address string The address which the type will be calculated for.

Example of use:

var addressType = utils.odm.getAddressTypeFromAddress("[IP_ADDRESS]");
//addressType will be: ipv4

var addressType = utils.odm.getAddressTypeFromAddress("2001:0db8:85a3:0000:0000:8a2e:0370:7334");
//addressType will be: ipv6

utils.odm.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.

Example of use:

var value = utils.odm.entitiesValue(entities, "provision.device.identifier", 0);

utils.odm.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.

Example of use:

var response = utils.odm.httpRequest({method: "GET", uri: "http://example.com", headers: {}}, null);

utils.date.period.previousQuarter(referenceTimeMillis)

Calculates previous quarter from specified time in milliseconds.

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.previousQuarter(1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-11-01 12:00:00:000
    "final": 1698840899000, //2023-11-01 12:14:59:999
    "type": "previousQuarter" 
}

utils.date.period.previousDay(referenceTimeMillis)

Calculates previous day from specified time in milliseconds.

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.previousDay(1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-10-31 00:00:00:000
    "final": 1698840899000, //2023-10-31 23:59:59:999
    "type": "previousDay" 
}

utils.date.period.previousWeek(referenceTimeMillis)

Calculates previous week from specified time in milliseconds.

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.previousWeek(1698841200000);//2023-11-01 12:20:00 (Wednesday)

It will return:

{
    "initial": 1698840000000, //2023-10-23 00:00:00:000 (Monday)
    "final": 1698840899000, //2023-10-29 23:59:59:999 (Sunday)
    "type": "previousWeek" 
}

utils.date.period.previousMonth(referenceTimeMillis)

Calculates previous month from specified time in milliseconds.

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.previousMonth(1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-10-01 00:00:00:000
    "final": 1698840899000, //2023-10-31 23:59:59:999
    "type": "previousMonth" 
}

utils.date.period.customPeriodUtc(initialTimeStr, finalTimeStr)

Calculates specified period in utc times in milliseconds.

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.customPeriodUtc("2011-11-01T14:20:00.000+0100","2011-11-01T14:25:00.000+0100");

It will return:

{
    "initial": 1698844800000, //2011-11-01T13:20:00.000
    "final": 1698845100000, //2011-11-01T13:25:00.000
    "type": "custom" 
}

utils.date.period.lastMinutes(minutes, referenceTimeMillis)

Calculates a period of defined minutes until reference time. If referenceTimeMillis is not defined, current time will be used as reference

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
minutes number number of minutes of period
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.lastMinutes(15, 1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-11-01 12:05:00:000
    "final": 1698841200000, //2023-11-01 12:20:00:000
    "type": "lastMinutes" 
}

utils.date.period.lastHours(hours, referenceTimeMillis)

Calculates a period of defined hours until reference time. If referenceTimeMillis is not defined, current time will be used as reference

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
hours number number of hours of period
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.lastHours(24, 1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-10-31 12:20:00:000
    "final": 1698841200000, //2023-11-01 12:20:00:000
    "type": "lastHours" 
}

utils.date.period.lastDays(days, referenceTimeMillis)

Calculates a period of defined days until reference time. If referenceTimeMillis is not defined, current time will be used as reference

Kind: global function
Returns: return an object with initial and final times of defined period

Param Type Description
days number number of hours of period
referenceTimeMillis number reference time in milliseconds

Example of use:

var period = utils.date.period.lastDays(7, 1698841200000);//2023-11-01 12:20:00

It will return:

{
    "initial": 1698840000000, //2023-10-25 12:20:00:000
    "final": 1698841200000, //2023-11-01 12:20:00:000
    "type": "lastDays" 
}

utils.bytes.fromHexString(hexString)

Kind: global function
Returns: return an Uint8Array object equivalent to de hexadecimal String

Param Type Description
hexString string String in hexadecimal format

Example of use:

var bytes = utils.bytes.fromHexString("09 4A 48")

It will return:

[09, 74, 72]

utils.bytes.toHexString(array)

Kind: global function
Returns: return the hexadecimal string representation.

Param Type Description
array Array of bytes hexadecimal string representation

Example of use:

var hexStr = utils.bytes.toHexString([09, 74, 72])

It will return:

"094A48"

utils.bytes.fromText(str)

Kind: global function
Returns: return the Uint8Array representation of the string with UTF encoding.

Param Type Description
str string any text

Example of use:

var bytes = utils.bytes.fromText("Hello!")

It will return:

[72, 101, 108, 108, 111, 33]

utils.bytes.toText(bytes)

Kind: global function
Returns: return the string representation of array of bytes in UTF.

Param Type Description
bytes Array of bytes bytes representing a text in UTF

Example of use:

var text = utils.bytes.toText([72, 101, 108, 108, 111, 33])

It will return:

"Hello!"

Cryptography API

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.

AES JS API

crypt.aes.encrypt(algorithm, key, ivParameterSpec, 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.
data Uint8Array data to be encoded
var key128 = utils.bytes.fromText('012345678902345a'); /* 128 bits for AES-128 */
var ivParam = utils.bytes.fromText('0123456789023452');

var inputData = [104, 111, 108, 97, 32, 99, 97, 114, 97, 108, 99, 111, 108, 52, 53, 54];
var encriptedData = crypt.aes.encrypt("AES/CBC/NoPadding", key128, ivParam, inputData); 

log(encriptedData) // Expected output: [178,19,136,33,80,100,25,183,126,178,19,125,139,24,212,253]

crypt.aes.decrypt(algorithm, key, ivParameterSpec, data)

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.
data Uint8Array encoded data to be decrypted
var key128 = utils.bytes.fromText('012345678902345a'); /* 128 bits for AES-128 */
var ivParam = utils.bytes.fromText('0123456789023452');

var inputEncrypted = [178,19,136,33,80,100,25,183,126,178,19,125,139,24,212,253]
var data = crypt.aes.decrypt("AES/CBC/NoPadding", key128, ivParam, inputEncrypted);

log(data) // Expected output: [104, 111, 108, 97, 32, 99, 97, 114, 97, 108, 99, 111, 108, 52, 53, 54] 

HMAC JS API

Following functions apply some hashing function with specified key to specified data. In all cases, the result is a JSON with following structure:

Param Type Description
error string It will be null if hashing finishes correctly. If hashing fails, exception message will be indicated.
result Uint8Array Obtained hash. If the hash function is applied correctly, byte array with hashed data will be returned. If some error occurs, null will be returned

Correct hashing result:

{
 "error": null,
 "result": [-102, 54, -66, -103, -25, 112, 1, 118, -65, 122, -22, 27, 88, 106, -54, 122, -11, -109, -63, 99, -127, -23, -15, -43, 28, 109, -22, -65, 25, 45, -85, 9, 39, 44, 39, 75, -95, -47, -61, -103, 101, -80, -62, -35, -102, 74, -76, 45, 94, -7, -35, 8, -80, -80, -65, -103, 127, 104, 75, -65, -89, 111, -34, 109]
}

Result with some error

{
 "error": "Algorithm HmacSHA999 not available",
 "result": null
}

crypt.hmac.sha256(data, key)

Create a hash from provided string using sha256.

Kind: global function
Returns: Object

Param Type Description
data string Data to be hashed
key Uint8Array key to be used for hashing
var hashResult = crypt.hmac.sha256("Some data to be hashed", "hashingKey");
log(hashResult) 
/* Expected output: 
{
 "error": null,
 "result": [-56, -6, 82, -104, -74, -100, -103, 112, 80, -89, -61, 85, -63, 58, -102, -54, -68, 15, 70, 60, 44, 85, 110, -100, -108, -95, -48, -3, 8, -25, 33, -4]
}
*/

crypt.hmac.sha512(data, key)

Create a hash from provided string using sha512.

Kind: global function
Returns: Object

Param Type Description
data string Data to be hashed
key Uint8Array key to be used for hashing
var hashResult = crypt.hmac.sha512("Some data to be hashed", "hashingKey");
log(hashResult) ;
/* Expected output: 
{
 "error": null,
 "result": [-102, 54, -66, -103, -25, 112, 1, 118, -65, 122, -22, 27, 88, 106, -54, 122, -11, -109, -63, 99, -127, -23, -15, -43, 28, 109, -22, -65, 25, 45, -85, 9, 39, 44, 39, 75, -95, -47, -61, -103, 101, -80, -62, -35, -102, 74, -76, 45, 94, -7, -35, 8, -80, -80, -65, -103, 127, 104, 75, -65, -89, 111, -34, 109]
}
*/