Protocol APIs

You only need the page for the protocol your device actually speaks. Each of these injects one global object into your script, on top of the core API that is always there.

This is the reference, not the guide

These pages document which functions you can call. For how an integration over that protocol works — who opens the conversation, what the device must be, how to schedule the work — read Supported protocols, and then the page for your transport: HTTP, MQTT, WebSocket, CoAP, Meter and industrial protocols or Remote access.

Transports OpenGate already speaks

The device arrived over one of these, and the API lets you read the incoming message and shape the reply.

Protocol Object Gives you
HTTP http The received request, the response you return, and an HTTP client for outgoing calls
MQTT mqtt Publish messages to a topic
WebSocket Send a message down an already open connection
CoAP coap.server.response Set the status code, content format and body of the CoAP response. Integration: CoAP

Meter and industrial protocols

Here the connector function is the one that opens the conversation, usually to poll a meter.

Protocol Object Gives you
DLMS dlms Open a DLMS connection and run get, set and action requests
DLMS Gas dlms_gas Smart Gas meters across manufacturers, on top of DLMS
IEC102 Connect over IEC102 and execute ASDUs: login, time, load curves, profiles
SNMP snmp SNMP get and set against a device

Shell and network access

Protocol Object Gives you
SSH ssh Open a session, send commands, read the answer
Telnet The same over Telnet
ICMP Send a ping and process the result
ICMP Response payload The payload a RESPONSE function receives with the ping result

Subscriptions

Protocol Object Gives you
Kite kite Query and change a subscription’s status through the Kite connector

Subsections of Protocol APIs

HTTP JavaScript API

Connector functions HTTP JS API guide

This API allows users to execute HTTP related actions from a connector function.

HTTP Object

The http object is the main object of the HTTP client. It allows perform different actions such as do http request or define http response for Operation Response or Iot Collections requests through http protocol.

http object is divided in two objects:

  • server: Only for CFs called from http requests. Gives access to received request and allows to specify http response to be sent.
  • client: Configure and make http requests.

server Object Properties

Read only properties with received HTTP request and response object to define HTTP response to be sent.

Property Type Default Description
headers JSON Received http request headers
uri string Received http request uri (without host)
body * Received http request body (the same content as the payload property)
response JSON {} Object to be used to define http response to be sent when CF finishes

server.response Object Properties

Property Type Default Description
status integer 201 Response HTTP code
body * null Response body
headers JSON null Response HTTP headers

server.response Object Methods

server.response.send()

Creates HTTP Response with defined properties. The response will be sent once the CF is finished correctly.

Example:

http.server.response.status=200;
http.server.response.body={'msg': 'OK'};
http.server.response.send();
//continue CF execution
return collection;

In this case, after CF execution, the Http response to be generated will have 200 status code with specified body ({'msg': 'OK'}) and no specific headers.

client Object Properties

Property Type Default Description
method string null One of http methods: POST, GET, …
uri string null Request uri
headers JSON null Request headers in json format
body * null Response body
alias string null Used to set custom https context, alias to be used for keystore
certificate string null Used to set custom https context, certificate content
privateKey string null Used to set custom https context, private key content
redirectPolicy string null Overrides default redirection policy
clientVersion string null Overrides default client version configured
timeOut integer null Overrides default timeout configured. Defined in seconds

client Object Methods

Following methods return Http Request result JSON with these fields:

Field Description
statusCode Received response HTTP code
body Received response body
headers Received response headers

client.post()

Performs POST using defined configuration. Overrides defined method.

Example of use with default values:

http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
http.client.body = {'operation_name':'custom_operation_request'};
var httpResp = http.client.post();

client.put()

Performs PUT using defined configuration. Overrides defined method.

Example of use with default values:

http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
http.client.body = {'operation_name':'custom_operation_request'};
var httpResp = http.client.put();

client.get()

Performs GET using defined configuration. Overrides defined method.

Example of use with default values:

http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
var httpResp = http.client.get();

client.delete()

Performs DELETE using defined configuration. Overrides defined method.

Example of use with default values:

http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
var httpResp = http.client.delete();

client.patch()

Performs PATCH using defined configuration. Overrides defined method.

Example of use with default values:

http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
http.client.body = {'operation_name':'custom_operation_request'};
var httpResp = http.client.patch();

client.request()

Performs configured http request. method property must be defined.

Example of use with default values:

http.client.method = "GET";
http.client.uri = "https://remotehost/uri";
http.client.headers = {'X-Api-Key':'apikey'};
http.client.body = {'operation_name':'custom_operation_request'};
var httpResp = http.client.request();

MQTT JavaScript API

Connector functions MQTT JS API guide

This API allows users to execute operations in the MQTT client from a connector function.

MQTT Object

The mqtt object is the main object of the MQTT client. It allows publishing messages to an MQTT topic.

mqtt Object Properties

Property Type Default Description
device string entity id Target device id
topic string odm/request Topic uri where to publish the message

mqtt Object Methods

mqtt.publish(payload)

Publish a message on mqtt topic

Property Type Default Description
payload * Message to be sent. It can be string or a json object

Example of use with default values:

mqtt.publish({'operation_name':'custom_operation_request'});

Example of use with overriden values

mqtt.device='other_device';
mqtt.topic = 'destination/topic';
mqtt.publish('Message to be sent');

Websocket JavaScript API

Connector functions websocket JS API guide

This API allows users to send message to opened websocket.

Websocket Object Properties

Property Type Description
payload * Data to be published. It will be converted to string.
deviceId String Device identifier with the opened websocket

Websocket Object Methods

websocket.sendMsg()

Executes specified request using the properties of the websocket object

Returns: Object

Example of use:

websocket.payload = {someField:someValue};
websocket.deviceId = 'someDeviceId'
websocket.sendMsg();

CoAP API

Connector functions JS API guide for the CoAP protocol

This file provides methods and properties to specify a custom return code and a custom body in the CoAP response that is sent from the OpenGate platform to the device.

coap.server.response Object: Specifying a custom CoAP response to the device.

The coap.server.response global object provides all the necessary functionality to be able to specify both the state and the body of the CoAP response to return to the device.

coap.server.response Object Properties

Property Type Default Description
status number 204 The returned status, as a three digits number without dots
body Uint8Array [] The body of the returned CoAP response, as array of bytes
contentFormat number Indicates the representation format of the response body

coap.server.response Object Methods

coap.server.response.send()

The status, body and contentFormat are saved for inclusion in the CoAP response.

Example of use

// sending CHANGED status (2.04), and a number 1 as body (two bytes unsigned integer - little endian)
coap.server.response.status = 204; 
coap.server.response.body = new Uint8Array([01, 00]); 
coap.server.response.send();

DLMS JavaScript API

Connector functions DLMS JS API guide

This JavaScript code provides predefined functions to execute DLMS requests from the connector function. They are explained below.

Tip

For Smart Gas devices, there is a specialized extension of this API called DLMS Gas API which simplifies many common operations.

Types of south criteria for your DLMS connector function:

Description Format Example
Identification via OBIS code for notifications that contain a description element dlms://obis/<obis-code> dlms://obis/0.0.66.0.48.255
Identification via template ID for notifications containing only 1 or more octet-string values and taking first byte of each octet-string as template ID dlms://template/<template-id> dlms://template/48
Warning

The OBIS Code needs to be specified using only dots as separator, don’t use the complex form 0-0:66.0.48.255 or the Connector Function will not be called.

Input parameters in Collection Connector Function

The main script will have access to three main vars:

  • entity: json with flattened operation target device entity representation.
  • gateway: json with flattened gateway entity representation. It can be null.
  • payload: json that represents the DLMS message received from the device.
  • contextParams: json object with execution context information. It can have some of this params:
    • apiKey: device or user apikey.
    • remoteIp: remote host where DLMS message is invoked.
    • obisCode: OBIS code of the message arrived.
    • templateId: Template identifier of the message arrived.

ContextParams for COLLECTION Connector function for DLMS connection:

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

Here is a payload example:

payload = [
	{
	    "obisCode": "0.0.49.0.75.254",
	    "attrId": 2,
	    "classId": 1,
	    "type": "octet-string",
	    "value": [2, 3, 215, 0]
	},
	{
	    "obisCode": "0.0.49.0.77.254",
	    "attrId": 4,
	    "classId": 1,
	    "type": "unsigned",
	    "value": 1
	}
]

JS DLMS API

For REQUEST Connector Functions we will use the functions described below. You have an object, named dlms, with all the functions described. You must use dlms.<function>.

If you want to collect data after executing any of these function you can call collectCF and you can set various obis code in the URL provided as you can see in the next example:

collectCF(result.data, "dlms://obis/0.1.2.3.4.5");

dlms.connect()

Opens DLMS connection (default via TCP transport).

Kind: global function

The connection parameters need to be set before calling connect:

dlms.ip = "127.0.0.1"
dlms.connect()
Config name Type Default value Description
ip string null IP address of the device you want to connect to.
port number 4059 Port of the device you want to connect to.
connectionType string ("TCP", "UDP") "TCP" Protocol of the device you want to connect to.
cwport number 16 Client WPort.
swport number 1 Server WPort.
refMethod string ("LN", "SN") "LN" Server WPort.
securityLevel string ("MANUFACTURER", "HIGH", "LOW", "SHA1, "SHA256", "MD5", "GMAC", "ECDSA", "NONE") "NONE" Authentication mechanism to use in the connection.
password string null Password to use with the authentication mechanism.
timeout number 5000 Timeout of the connection.
security string (NONE, AUTHENTICATION, ENCRYPTION, AUTHENTICATION_ENCRYPTION) null Security used in every message. null value will be treated as NONE
securitySuite string (SUITE_0, SUITE_1, SUITE_2) null Authentication, encryption and key wrapping algorithm. null value will be treated as SUITE_0
authenticationKey byte[] as hexadecimal string null Key used for message authentication. The length of the key in bytes must match the securitySuite used
blockCipherKey byte[] as hexadecimal string null Key used for message encryption. The length of the key in bytes must match the securitySuite used
hesSystemTitle byte[] as hexadecimal string null Overrides default System Title to be sent in requests to client
ignoreSystemTitleInCiphering boolean false Whether the optional hesSystemTitle should be ignored (not sent) when sending ciphered messages
forceGetWithoutList boolean false Whether to force get() by default to request elements one by one instead of using a list when MULTIPLE_REFERENCES conformance is enabled
forceSetWithoutList boolean false Whether to force set() by default to request elements one by one instead of using a list when MULTIPLE_REFERENCES conformance is enabled
conformance string[] ("MULTIPLE_REFERENCES", "GENERAL_PROTECTION") [] Communication conformance values. For example, ‘MULTIPLE_REFERENCES’ specifies it is possible to send to device multiple obis in unique request
Warning

In case of security parameter is not NONE, next default values will be set:

  • blockCipherKey: 000102030405060708090A0B0C0D0E0F
  • authenticationKey: D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF

Add attributes

addAttr() is used both for get() and set() methods and has multiple signatures:

dlms.addAttr(classId, obisCode, attrId)

Applicable for normal gets.

Param Type Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
attrId number The attribute index of the object
// After connection has been established
dlms.addAttr(1, "1.2.3.4.5.6", 2)
var getResult = dlms.get() // More details on get() next

dlms.addAttr(classId, obisCode, attrId, type, value)

Applicable for normal sets.

Param Type Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
attrId number The attribute index of the object
type string The data type of the value to set
value see data types The data value to set
// After connection has been established
dlms.addAttr(1, "1.2.3.4.5.6", 2, "unsigned", 254)
var setResult = dlms.set() // More details on set next

dlms.addAttr(classId, obisCode, attrId, data)

Applicable for normal sets.

Param Type Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
attrId number The attribute index of the object
data object (with type and value) The data with both type and value to set

where:

data attribute Type Description
type string The data type of the value to set
value see data types The data value to set

This is an alternate way of using addAttr(classId, obisCode, attrId, type, value) with the data parameters in an object.

// After connection has been established
//dlms.addAttr(1, "1.2.3.4.5.6", 2, "unsigned", 254)
dlms.addAttr(1, "1.2.3.4.5.6", 2, {"type": "unsigned", "value": 254}) // This is similar to the previous addAttr (commented)
var setResult = dlms.set() // More details on set next

It’s helpful when used in combination with get().

// After connection has been established
dlms.addAttr(1, "1.2.3.4.5.6", 2)
var getResult = dlms.get() // More details on get next
dlms.addAttr(1, "1.2.3.4.5.255", 2, getResult[0]) // Set on object 1.2.3.4.5.255 the value (and data type) retrieved from object 1.2.3.4.5.6
var setResult = dlms.set() // More details on set next

dlms.addAttr(classId, obisCode, attrId, selectiveAccess)

Applicable for gets with selective access.

Param Type Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
attrId number The attribute index of the object
selectiveAccess object (with accessSelector and accessParameters) The selective access descriptor

where:

selectiveAccess attribute Type Description
accessSelector number The access selector
accessParameters object with type and value The access parameters

and

accessParameters attribute Type Description
type string The data type of access parameters
value see data types The data value of the access parameters
dlms.addAttr(1, "1.2.3.4.5.6", 2, {"accessSelector": 1, "accessParameters": {"type": "unsigned", "value": 254}})
Info

The proper access selector and parameters depend on the manufacturer and object type. Some may implement by range and by entry defined in the DLMS Blue Book - Parameters for selective access to the buffer attribute (section 4.3.6 in Blue Book 12).

// Example by range
dlms.addAttr(7, '7.0.99.99.3.255', 2, {
	accessSelector: 1,
	accessParameters: {
		type: 'structure',
		value: [{
			type: 'structure',
			value: [{
				type: 'long-unsigned',
				value: 1
			}, {
				type: 'octet-string',
				value: [0, 0, 1, 1, 0, 255]
			}, {
				type: 'integer',
				value: 2
			}, {
				type: 'long-unsigned',
				value: 0
			}]
		}, {
			type: 'double-long-unsigned',
			value: 1735884000
		}, {
			type: 'double-long-unsigned',
			value: 1736229600
		}, {
			type: 'array',
			value: []
		}]
	}
})

dlms.addAttr(attribute)

Generic signature applicable for all cases.

Attribute Type Mandatory Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
attrId number The attribute index of the object
type string only on set() The data type of the value to set
value see data types only on set() The data value to set
accessSelector number only on get() with selective access The access selector
accessParameters object with type and value only on get() with selective access The access parameters

where:

accessParameters attribute Type Description
type string The data type of access parameters
value see data types The data value of the access parameters
// For normal get
dlms.addAttr({classId: 1, obisCode: "1.2.3.4.5.6", attrId: 2})
// For normal set
dlms.addAttr({classId: 1, obisCode: "1.2.3.4.5.6", attrId: 2, type: "unsigned", value: 254})
// For get with selective access
dlms.addAttr({classId: 1, obisCode: "1.2.3.4.5.6", attrId: 2, accessSelector: 1, accessParameters: {type: "unsigned", value: 254}})
data types
Name Value type Compatible type in set Description Example
null-data null null
array Array of object Complex data, all elements must be of the same type [{"type":"unsigned","value":1},{"type":"unsigned","value":2}]
structure Array of object Complex data, different elements possible [{"type":"unsigned","value":1},{"type":"visible-string","value":"two"}]
boolean boolean true
bit-string Array of boolean string An ordered sequence of boolean values. In set() an string may be used instead of array of boolean as bit-string representation [true,false,true] ("101" as string representation in set())
double-long number Integer32 (-21474836482147483647) 0
double-long-unsigned number Unsigned32 (04294967295 0
octet-string Array of number string An ordered sequence of octets (8 bit bytes). May contain a dateTime value, see getDateTime() and getDate() [116,101,115,116] (or "test" in set())
visible-string string An ordered sequence of ASCII characters "test"
utf8-string string An ordered sequence of characters encoded as UTF-8 "test"
bcd number Binary Coded Decimal (099) 0
integer number Integer8 (-128127) 0
long number Integer16 (-3276832767) 0
unsigned number Unsigned8 (0255) 0
long-unsigned number Unsigned16 (065535) 0
compact-array Array of object Provides an alternative, compact encoding of complex data, all elements must be of the same type [{"type":"unsigned","value":1},{"type":"unsigned","value":2}]
long64 number Integer64 (-90071992547409919007199254740991) 1 0
long64-unsigned number Unsigned64 (09007199254740991) 1 0
enum number The elements of the enumeration type are defined in the Attribute description or Method description section of a COSEM IC specification (0255) 0
float32 number Floating point number in 4 bytes 0
float64 number Floating point number in 8 bytes 0
date-time object Object containing all fields in a dateTime object {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":26,"second":55,"hundredthsOfSecond":0,"deviation":-60,"status":0}
date object Object containing year, month, dayOfMonth and dayOfWeek fields in a dateTime object {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2}
time object Object containing hour, minute, second and hundredthsOfSecond fields in a dateTime object {"hour":16,"minute":1,"second":2,"hundredthsOfSecond":20}
Warning

JavaScript does not support the whole range of DLMS numbers, see footnotes.

dateTime objects

A dateTime object is used to specify all possible values for date-time, date and time DLMS types. It may define the following attributes:

Name Normal values Additional values
year 0..65534 65535 means unspecified
month 1..12 (jan-dec) 253 = daylight savings end, 254 daylight savings begin, 255 not specified
dayOfMonth 1..31 224..252 reserved, 253 2nd last day of month, 254 last day of month, 255 not specified
dayOfWeek 1..7 (mon-sun) 255 not specified
hour 0..23 255 not specified
minute 0..59 255 not specified
second 0..59 255 not specified
hundredthsOfSecond 0..99 255 not specified
deviation -720..720 (in minutes of local time to UTC) 32768 not specified
status 8 bit flags 255 not specified
Info

For more information see DLMS Blue Book - Date and time formats (section 4.1.6.1 in Blue Book 12)

To transform this object to a Date see getDate(). Keep in mind that sets of date-time, date, time and octet-string do not accept a Date object. To transform it to a dateTime object use getDateTime().

dlms.get(descriptive, forceWithoutList)

Executes a multi DLMS get attribute request with the previously specified payload (addAttr(classId, obisCode, attrId)).

Kind: global function
Returns: Array - Array of JSONs with responses. Each JSON will have six fields: result of the get operation, the requested classId, obisCode and attrId, type with the data type of the received value and the value received from the device. An optional error field may be returned for any error that happened during the get.

Param Type Mandatory Default Description
descriptive boolean true Descriptive mode returns complex data as Array of object containing type and value for each object, non descriptive mode flattens the returned array
forceWithoutList boolean false Whether to force the get to request elements one by one instead of using a list when MULTIPLE_REFERENCES conformance is enabled (if it’s not set the global forceGetWithoutList will be used)

Example for descriptive get:

// After connection has been established
dlms.addAttr(1, "0.0.0.0.0.0", 2) // Example for null-data
dlms.addAttr(1, "0.0.0.0.0.1", 2) // Example for array
dlms.addAttr(1, "0.0.0.0.0.2", 2) // Example for structure
dlms.addAttr(1, "0.0.0.0.0.3", 2) // Example for boolean
dlms.addAttr(1, "0.0.0.0.0.4", 2) // Example for bit-string
dlms.addAttr(1, "0.0.0.0.0.5", 2) // Example for double-long
// Rest on number examples are omitted because they are similar to double-long
dlms.addAttr(1, "0.0.0.0.0.6", 2) // Example for octet-string
dlms.addAttr(1, "0.0.0.0.0.7", 2) // Example for visible-string
// utf8-string example is omitted because it's similar to visible-string

var result = dlms.get() // Descriptive (true can also be passed)
log(result[0]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.0","attrId":2,"type":"null-data","value":null}]
log(result[1]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.1","attrId":2,"type":"array","value":[{"type":"long-unsigned","value":1},{"type":"long-unsigned","value":2},{"type":"long-unsigned","value":3}]}
log(result[2]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.2","attrId":2,"type":"structure","value":[{"type":"unsigned","value":1},{"type":"long-unsigned","value":2},{"type":"array","value":[{"type":"visible-string","value":"one"},{"type":"visible-string","value":"two"}]}]}
log(result[3]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.3","attrId":2,"type":"boolean","value":true}
log(result[4]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.4","attrId":2,"type":"bit-string","value":[true,false,true]}
log(result[5]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.5","attrId":2,"type":"double-long","value":1}
log(result[6]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.6","attrId":2,"type":"octet-string","value":[116,101,115,116]}
log(result[7]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.7","attrId":2,"type":"visible-string","value":"test"}

Example for non descriptive get

// After connection has been established
// Simple value types are returned exactly the same as descriptive mode, null-data is included to viasually see this
dlms.addAttr(1, "0.0.0.0.0.0", 2) // Example for null-data
// Simple value types are returned exactly the same as descriptive mode, null-data is included to viasually see this
dlms.addAttr(1, "0.0.0.0.0.1", 2) // Example for array
dlms.addAttr(1, "0.0.0.0.0.2", 2) // Example for structure

var result = dlms.get(false) // Non descriptive
log(result[0]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.0","attrId":2,"type":"null-data","value":null}]
log(result[1]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.1","attrId":2,"type":"array","value":[1,2,3]}
log(result[2]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.2","attrId":2,"type":"structure","value":[1,2,["one","two"]]}
Non descriptive get

Complex values returned in a non-descriptive get cannot be passed as value in a set.

get results
  • success
  • hardware-fault
  • temporary-failure
  • read-write-denied
  • object-undefined
  • object-class-inconsistent
  • object-unavailable
  • type-unmatched
  • scope-of-access-violated
  • data-block-unavailable
  • long-get-aborted
  • no-long-get-in-progress
  • long-set-aborted
  • no-long-set-in-progress
  • data-block-number-invalid
  • other-reason

dlms.set(descriptive)

Executes a multi DLMS set attribute request with the previously specified payload (addAttr(classId, obisCode, attrId, type, value)).

Kind: global function
Returns: Array - Array of JSONs with responses. Each JSON will have six fields: result of the set operation, the requested classId, obisCode and attrId, type with the data type of the received value and the value received from the device. An optional error field may be returned for any error that happened during the set.

Param Type Mandatory Default Description
descriptive boolean true Does not matter on set(). It’s included to have the same signature as get() and in case a device returns something in a set.
forceWithoutList boolean false Whether to force the set to request elements one by one instead of using a list when MULTIPLE_REFERENCES conformance is enabled (if it’s not set the global forceSetWithoutList will be used)
Info

Normally, a set request should always return a null-data as type and null as value.

Warning

A set request for complex data must always specify the value in a descriptive manner (as Array of Object containing both type and value for each and all elements and sub-elements in case of more nested complex elements).

// After connection has been established
dlms.addAttr(1, "0.0.0.0.0.0", 2, "null-data", null) // Example for null-data
dlms.addAttr(1, "0.0.0.0.0.1", 2, "array", [{"type":"long-unsigned","value":1},{"type":"long-unsigned","value":2},{"type":"long-unsigned","value":3}]) // Example for array
dlms.addAttr(1, "0.0.0.0.0.2", 2, "structure", [{"type":"unsigned","value":1},{"type":"long-unsigned","value":2},{"type":"array","value":[{"type":"visible-string","value":"one"},{"type":"visible-string","value":"two"}]}]) // Example for structure
dlms.addAttr(1, "0.0.0.0.0.3", 2, "boolean", false) // Example for boolean
dlms.addAttr(1, "0.0.0.0.0.4", 2, "bit-string", [true, false, true, false]) // Example for bit-string as boolean array (default type)
dlms.addAttr(1, "0.0.0.0.0.4", 2, "bit-string", "1010") // Example for bit-string as string with the bit-string representation (alternative set value type, a get will always return it as boolean array)
dlms.addAttr(1, "0.0.0.0.0.5", 2, "double-long", 1) // Example for double-long
// Rest on number examples are omitted because they are similar to double-long
dlms.addAttr(1, "0.0.0.0.0.6", 2, "octet-string", [116, 101, 115, 116]) // Example for octet-string as byte array (default type)
dlms.addAttr(1, "0.0.0.0.0.6", 2, "octet-string", "test") // Example for octet-string as string (alternative set value type, a get will always return it as byte array)
dlms.addAttr(1, "0.0.0.0.0.7", 2, "visible-string", "test") // Example for visible-string
// utf8-string example is omitted because it's similar to visible-string

var result = dlms.set() // Descriptive mode does not really matter, because return should always be null-data.
log(result[0]) // Expected output: {"result":"success","classId":1,"obisCode":"0.0.0.0.0.0","attrId":2,"type":"null-data","value":null}]
// All remaining results are similar, including returning null-data.
set results

They are the same as get results.

dlms.addMethod(classId, obisCode, methodId, type, value)

addMethod() is used for method() function.

Param Type Mandatory Description
classId Array The class ID of the object to access
obisCode string The name of the object to access
methodId string The method index in the object
type string when needed The data type of the value to pass to the method
value string when needed The data value to pass to the method

dlms.method(descriptive)

Executes a multi DLMS method (or action) request with the previously specified payload (addMethod(classId, obisCode, methodId, type, value)).

Kind: global function
Returns: Array - Array of JSONs with responses. Each JSON will have six fields: result of the method operation, the requested classId, obisCode and methodId, type with the data type of the received value and the value received from the device. An optional error field may be returned for any error that happened during the method (for example an error decoding the optional return parameters).

Param Type Mandatory Default Description
descriptive boolean true Descriptive mode returns complex data as Array of object containing type and value for each object, non descriptive mode flattens the returned array
Info

A method request may need and/or return whatever type and value it’s needed. Check Method description section of a COSEM IC specification.

// After connection has been established
dlms.addMethod(7, "1.0.99.1.0.255", 2) // Example for method needing null-data as parameter (default type and value)
dlms.addMethod(7, "1.0.99.1.0.254", 2, "unsigned", 0) // Example for method needing 0 (unsigned) as parameter

var result = dlms.method()
log(result[0]) // Expected output: {"result":"success","classId":1,"obisCode":"1.0.99.1.0.255","methodId":2,"type":"null-data","value":null}]
log(result[1]) // Expected output: {"result":"success","classId":1,"obisCode":"1.0.99.1.0.254","methodId":2,"type":"boolean","value":true}
action results
  • success
  • hardware-fault
  • temporary-failure
  • read-write-denied
  • object-undefined
  • object-class-inconsistent
  • object-unavailable
  • type-unmatched
  • scope-of-access-violated
  • data-block-unavailable
  • long-action-aborted
  • no-long-action-in-progress
  • other-reason

dlms.initializeNextFrameCounter(currentFrameCounter)

Sets the invocation counter of the ciphering to the next value of the received frame counter. This is used for devices that maintain two separate frame counters (one for transmit and one for receive). Usually the current Management Frame Counter - On-line is received in a CompactFrame notification and that value is the one that needs to be passed to this function for that device.

Kind: global function

Param Type Mandatory Description
currentFrameCounter number The current frame counter sent by the device.

dlms.getInvocationCounter()

Returns the current invocation counter of the ciphering.

Kind: global function Returns: number (integer).

dlms.disconnect()

Close the DLMS connection.

Kind: global function

dlms.getCompactData(typeDescription, value, descriptive, italianMode)

Extract the compact data serialized in a byte array according to the description given.

Kind: global function
Returns: Object - Object containing result and/or error. On success, result contains the parsed compact data (either in descriptive (with type in each value) or non-descriptive (direct values) format depending on the descriptive parameter). On error, the error will contain the error description and result may be null or contain a best-effort decoding of the compact data that may be incorrect.

Param Type Mandatory Default Description
typeDescription Object Object with the description of the data. The attributes of the object will be different according to the data expected’
value Array of number (or Object containing an octet-string type with its value) Array of bytes with the compact data (for example the DLMS notification data or element received)
descriptive boolean true Descriptive mode returns complex data as Array of object containing type and value for each object, non descriptive mode flattens the returned array
italianMode boolean false Determines if the compact data decoding of arrays must be in italian mode or not (explicitArrayLengthInContent)

Here is a description example:

var typeDescription = {"type": "structure", "items": [
		{"type": "long-unsigned"},
		{"type": "unsigned"},
		{"type": "array", "length": 1, "subtype": {"type": "long-unsigned"}},
		{"type": "array", "length": 1, "subtype": {"type": "double-long-unsigned"}},
		{"type": "structure", "items": [
			{"type": "unsigned"}, {"type": "long-unsigned"}
		]},
		{"type": "octet-string"}
	]
}
Info
  • Simple data types just need to define the type as seen in data types.
  • array type description must define a subtype, which is a typeDescription, and a length when not using italianMode. italianMode (or explicitArrayLengthInContent) does not need the length because it’s encoded in the received data.
  • structure type description must define an array of items, which are each a typeDescription.
  • compact-array is not supported inside a compact data.

Here is an example of the function result in descriptive and non descriptive modes:

var {result: data, error} = dlms.getCompactData(typeDescription, payload);
if (error) {
    log("Error: " + error);
} else {
    log(data) // Expected output: {"type":"structure","value":[{"type":"long-unsigned","value":1},{"type":"unsigned","value":2},{"type":"array","value":[{"type":"long-unsigned","value":3}]},{"type":"array","value":[{"type":"double-long-unsigned","value":4}]},{"type":"structure","value":[{"type":"unsigned","value":5},{"type":"long-unsigned","value":6}]},{"type":"octet-string","value":[83,112,97,114,101,32,79,98,106,101,99,116]}]}
}

var {result: data, error} = dlms.getCompactData(typeDescription, payload, false);
if (error) {
    log("Error: " + error);
} else {
    log(data) // Expected output: [1,2,[3],[4],[5,6],[83, 112, 97, 114, 101, 32, 79, 98, 106, 101, 99, 116]]
}

dlms.getDate(value) ⇒ Date

Extract the Date of a dateTime object or an octet-string. Some dateTime objects or octet-string may not contain a complete date and this method will return a date that may not be as accurate as you expect. You should check the dateTime object for unspecified value.

Kind: global function Returns: Date

Param Type Mandatory Default Description
value dateTime object or Array of number (or Object having type date-time, date, time or octet-string with its value) The best-effort Date possible
// compact-data containing all 

var dateTime = data[0]
log(dateTime) // Expected output: {"type":"date-time","value":{"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":26,"second":55,"hundredthsOfSecond":0,"deviation":-60,"status":0}}
log(dlms.getDate(dateTime).toISOString()) // Expected output: 2023-11-28T11:26:55.000Z
log(dlms.getDate(dateTime.value).toISOString()) // Expected output: 2023-11-28T11:26:55.000Z

var date = data[1]
log(date) // Expected output: {"type":"date","value":{"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2}}
log(dlms.getDate(date).toISOString()) // Expected output: 2023-11-28T00:00:00.000Z
log(dlms.getDate(date.value).toISOString()) // Expected output: 2023-11-28T00:00:00.000Z

var time = data[2]
log(time) // Expected output: {"type":"date","value":{"hour":16,"minute":1,"second":2,"hundredthsOfSecond":20}}
log(dlms.getDate(time).toISOString()) // Expected output: 0000-01-01T16:01:02.200Z
log(dlms.getDate(time.value).toISOString()) // Expected output: 0000-01-01T16:01:02.200Z

var octet = data[3]
log(octet) // Expected output: {"type":"octet-string","value":[7, 231, 11, 28, 2, 10, 26, 55, 0, -1, -60, 0]}
log(dlms.getDate(octet).toISOString()) // Expected output: 2023-11-28T11:26:55.000Z
log(dlms.getDate(octet.value).toISOString()) // Expected output: 2023-11-28T11:26:55.000Z

var undefinedDateTimeInOctet = data[4]
log(undefinedDateTimeInOctet) // Expected output: {"type":"octet-string","value":[-1, -1, -1, -1, -1, -1, -1, -1, -1, -128, 0, -1]}
log(dlms.getDate(undefinedDateTimeInOctet).toISOString()) // Expected output: 0000-01-01T00:00:00.000Z
log(dlms.getDate(undefinedDateTimeInOctet.value).toISOString()) // Expected output: 0000-01-01T00:00:00.000Z

log(dlms.getDate(dlms.unspecifiedDateTime()).toISOString()) // Expected output: 0000-01-01T00:00:00.000Z

dlms.getDateTime(value)

Extract the dateTime object of a Date or an octet-string. The resulting dateTime objects generated from a Date will use UTC time specifying a deviation of 0. If you need something else construct the dateTime object manually.

Kind: global function Returns: Object

Param Type Mandatory Default Description
value Date or Array of number (or Object having type of octet-string with its value) Value containing a dateTime compatible value
log(dlms.getDateTime(new Date('2023-11-28T10:24:00.000Z'))) // Expected output: {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":24,"second":0,"hundredthsOfSecond":0,"deviation":0,"status":0}
log(dlms.getDateTime(new Date('2023-11-28T10:24:00.299Z'))) // Expected output: {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":24,"second":0,"hundredthsOfSecond":29,"deviation":0,"status":0}
log(dlms.getDateTime(new Date('Tue Nov 28 2023 11:24:00 GMT+0100'))) // Expected output: {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":24,"second":0,"hundredthsOfSecond":0,"deviation":0,"status":0}

// compact-data containing all values

var octet = data[0]
log(octet) // Expected output: {"type":"octet-string","value":[7, 231, 11, 28, 2, 10, 26, 55, 0, -1, -60, 0]}
log(dlms.getDateTime(octet)) // Expected output: {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":26,"second":55,"hundredthsOfSecond":0,"deviation":-60,"status":0}
log(dlms.getDateTime(octet)) // Expected output: {"year":2023,"month":11,"dayOfMonth":28,"dayOfWeek":2,"hour":10,"minute":26,"second":55,"hundredthsOfSecond":0,"deviation":-60,"status":0}

var undefinedDateTimeInOctet = data[1]
log(undefinedDateTimeInOctet) // Expected output: {'type': 'octet-string', 'value': [-1, -1, -1, -1, -1, -1, -1, -1, -1, -128, 0, -1]}
log(dlms.getDateTime(undefinedDateTimeInOctet)) // Expected output: {"year":65535,"month":255,"dayOfMonth":255,"dayOfWeek":255,"hour":255,"minute":255,"second":255,"hundredthsOfSecond":255,"deviation":32768,"status":255}
log(dlms.getDateTime(undefinedDateTimeInOctet.value)) // Expected output: {"year":65535,"month":255,"dayOfMonth":255,"dayOfWeek":255,"hour":255,"minute":255,"second":255,"hundredthsOfSecond":255,"deviation":32768,"status":255}

dlms.undefinedDateTime()

Get dateTime object with all its fields set to not specified.

You can also use unspecifiedDateTime().

Kind: global function Returns: Object

dlms.addAttr(1, '0.0.0.0.0.0', 2, 'octet-string', dlms.undefinedDateTime())
log(dlms.getDate(dlms.undefinedDateTime()).toISOString()) // Expected output: 0000-01-01T00:00:00.000Z

dlms.unspecifiedDateTime()

Get dateTime object with all its fields set to not specified.

You can also use undefinedDateTime().

Kind: global function Returns: Object

dlms.addAttr(1, '0.0.0.0.0.0', 2, 'octet-string', dlms.unspecifiedDateTime())
log(dlms.getDate(dlms.unspecifiedDateTime()).toISOString()) // Expected output: 0000-01-01T00:00:00.000Z

DLMS Gas JavaScript API

Connector functions DLMS Gas JS API guide

The dlms_gas API provides a unified framework for managing Smart Gas meters from various manufacturers.

Manufacturer-based behavior

This API is designed to abstract behavior based on different manufacturers. Currently, the following behaviors have been specified:

  • pietro
  • watertech
  • honeywell
  • spark

There is a common or default behavior that serves as a basis for all manufacturers and that they overwrite when they need to. In addition, the API is designed to be extended and customized with new behaviors in the development of new CFs.

Connector Functions Implementation

Some use cases for how to implement a CF are explained below.

Standard connector function implementation with already defined behaviors

dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

In this case, the call to dlms_gas.init() will initialize the initial parameters based on the device information and the configuration specified in the organization’s default entity. For more details on the behavior of dlms_gas.init(), see the dlms_gas.config properties and dlms_gas.init() function.

Next, when executing dlms_gas.decode(), the received Compact Frame will be decoded based on the standard specification of the already known compact frames (47, 48, 49, 51, 97). For more details on the behavior of dlms_gas.decode(), see the dlms_gas.decode section.

The next step is to execute the actions corresponding to the session (OpenGate operations, information requests, time change…). For more details on the actions performed, see the dlms_gas.pendingActions section.

Finally, dlms_gas.collect() is invoked, which is responsible for collecting data from the three entities involved in gas device communications: meter, network cell, and organizational unit. For more details on the behavior of dlms_gas.collect(), see the dlms_gas.collect section.

Configuration initialization

The following examples show some cases of how to vary the initial configuration.

The first case shows how to initialize the session using a configuration entity different from the organization’s. In this case, it starts from the idea that the entity representing the organization contains a suffix.

const orgName = entity._value('provision.administration.organization') + '_dev';
dlms_gas.init(orgName);

Another option is to modify the configuration once initialized. In this example, we see how the maxClockSkewAllowedSec and italianMode parameters are overwritten. The dlms_gas.config parameters are explained in the dlms_gas.config section.

dlms_gas.init();
dlms_gas.config.maxClockSkewAllowedSec = 10;
dlms_gas.config.italianMode = false;

Finally, it may be necessary to overwrite the API key. This case is not recommended, but if necessary, it is done as follows:

dlms_gas.config.__initApiKey('different-api-key');

Configuration of actions to be performed in the session

Without changing the order of the actions to be performed, it is possible to force or avoid certain actions being performed.

The following example shows how to avoid attempting to change the meter’s time.

dlms_gas.actions.setClock = false;
dlms_gas.pendingActions();

It is also possible to force some of the actions to be performed even if the conditions for their normal behavior are not met. For example, the request for certain information is only made when a device connects for the first time to the platform in order to collect some of its initial configuration. However, it is possible to force this request every time it connects:

dlms_gas.actions.forceInitialData = true;
dlms_gas.pendingActions();

For all options, see the dlms_gas.actions section. Although initially with this configuration the order of the actions cannot be changed (see the dlms_gas.pendingActions section), it is possible to overwrite the order or even change the actions to be performed with more advanced programming that we will see later.

Customization of compact frames decoding

Currently, the following Compact Frames are considered: 47, 48, 49, 51, and 97.

Tip

CF 22 is also considered, but only as part of the FOTA process and it is not expected to be used as push notification compact frame.

The specification for decoding a CF is based on objects with the following specification:

{
  "template":{},
  "initAndCollect": function(data){}
}

The template property is a JSON following what is specified in the DLMS API documentation for the dlms.getCompactData function and the typeDescription parameter. The dlms_gas.decode function calls the getCompactData function with the specified template.

The initAndCollect method is responsible for loading the decoded values of the compact frame into the devCollection object. It is not mandatory to implement this method if it is not necessary to collect the decoded CF. This method can also be used to initialize other variables of interest for the session. For example, it is common to initialize the variables dlms_gas.recUnixTime, dlms_gas.recMetEventsCounter, and dlms_gas.recNonMetEventsCounter.

The dlms_gas.decode function internally uses the corresponding template specification object (see default properties) to decode the received template, but it is possible to pass a specific object as a parameter in which to specify a different specification.

In this example, we will see what the (made-up) decoding of a compact frame identified with number 32 could look like:

const customTemplate = {
  "template": {
        'attrId': 2, 'template': 32, 'type': 'structure',
        'items': [
          { 'type': 'unsigned' },
          { 'type': 'double-long-unsigned' },
          { 'type': 'long-unsigned' },
          { 'type': 'long-unsigned' },
        ]
      },
  "initAndCollect": function (data) { 
      logger.trace(`Collecting data from cf 32`);
      dlms_gas.recUnixTime = data[1];
      dlms_gas.recMetEventsCounter = data[2];
      dlms_gas.recNonMetEventsCounter = data[3];
      dlms_gas.devCollection.addDatapoint('mType', data[0], dlms_gas.recUnixTime);
      dlms_gas.devCollection.addDatapoint('metCount', dlms_gas.recMetEventsCounter, dlms_gas.recUnixTime);
      dlms_gas.devCollection.addDatapoint('nonMetCount', dlms_gas.recNonMetEventsCounter, dlms_gas.recUnixTime);
      dlms_gas.devCollection.addDatapoint('contSinLect', false, dlms_gas.now);
  }
};
const decodeResult = dlms_gas.decode(customTemplate);

Another possibility is simply to change the decoding behavior of an already specified compact frame (47, 48, 49, 51, 97). In this case, there are several options to carry this out.

The first one is to create a completely new specification using the original template and defining the initAndCollect function:

const custom48 = {
  "template": dlms_gas.default["48"].template,
  "initAndCollect": function (data) { 
      logger.trace(`Collecting data from cf 48 with custom behavior`);
      dlms_gas.devCollection.addDatapoint(...);
      dlms_gas.devCollection.addDatapoint(...);
      dlms_gas.devCollection.addDatapoint(...);
      dlms_gas.devCollection.addDatapoint(...);
      dlms_gas.devCollection.addDatapoint(...);
      ...
  }
};
const decodeResult = dlms_gas.decode(custom48);

Following this line, it is also possible to implement the initAndCollect method using the default behavior but extending or altering that behavior as much as possible. An example could be the following, where the default behavior is used but then additional actions are performed:

const custom48 = {
  "template": dlms_gas.default["48"].template,
  "initAndCollect": function (data) { 
      logger.trace(`Collecting data from cf 48 extending default behavior`);
      dlms_gas.default["48"].initAndCollect(data);
      // extra actions: for example, adjust received time.
      dlms_gas.recUnixTime = dlms_gas.recUnixTime - (60 * 60 * 1000);
  }
};
const decodeResult = dlms_gas.decode(custom48);

Fully customized behaviors

The dlms_gas API includes objects responsible for encapsulating the functions and properties of different behaviors:

  • dlms_gas.default: contains all the properties and functions used to perform all actions.
  • dlms_gas.pietro: overwrites the functions and properties necessary to support the behavior of Pietro-type meters.
  • dlms_gas.honeywell: overwrites the functions and properties necessary to support the behavior of Honeywell-type meters.
  • dlms_gas.watertech: overwrites the functions and properties necessary to support the behavior of Watertech-type meters.
  • dlms_gas.spark: overwrites the functions and properties necessary to support the behavior of Spark-type meters.

Each behavior is specified at initilization time according to device manufacturer. If the device manufacturer is unknown, the dlms_gas.default behavior will be used.

Info

Check dlms_gas.behavior object’s properties and functions to understand how internally works behaviors management.

A simple way to test different behaviors is to overwrite the dlms_gas.behavior property. In the following example, the behavior is forced to be honeywell regardless of the manufacturer:

dlms_gas.behavior = 'honeywell';
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

Once dlms_gas.behavior is specified as honeywell, the rest of the logic is executed with the Honeywell behavior.

Finally, it is possible to define or extend the complete behavior of the API. It may be that with the configurations or specifications seen so far, it is not possible to adapt to a particular case. In this case, it will be necessary to define a new behavior to be used in the rest of the connector function. This is done as follows:

const newBehavior = {/*actions and properties*/};
dlms_gas.customBehavior(newBehavior);
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collection();

When calling dlms_gas.customBehavior(newBehavior), the dlms_gas.behavior variable is initialized with the value 'custom' and the dlms_gas.custom object is initialized with the specified parameter. From here on, all other actions will be done based on what is specified in newBehavior. See dlms_gas.customBehavior for more information.

It is possible to specify “base” behavior for a custom one using the baseBehavior property. In this case, it will try to look for defined functions and properties in newBehavior and if not found, it will try to find them in baseBehavior. Finally if it is not found in baseBehavior it will try to find it in dlms_gas.default.

In next example, when looking for a function or property, it will follow next order to find it: newBehavior -> honeywell -> default.

const newBehavior = {
  "baseBehavior": "honeywell",
  /*actions and properties*/
};
dlms_gas.customBehavior(newBehavior);
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

Reviewing the decoding examples from the previous section, they could be incorporated using the concept of customBehavior.

The following example shows how to define a new compact frame specification, while maintaining the possibility for the connector function to support other compact frames because the decode method is not forced to use the specification passed as a parameter.

const newBehavior = {
  "32": {
    "template": {
        'attrId': 2, 'template': 32, 'type': 'structure',
        'items': [
          { 'type': 'unsigned' },
          { 'type': 'double-long-unsigned' },
          { 'type': 'long-unsigned' },
          { 'type': 'long-unsigned' },
        ]
      },
    "initAndCollect": function (data) { 
        logger.trace(`Collecting data from cf 32`);
        dlms_gas.recUnixTime = data[1];
        dlms_gas.recMetEventsCounter = data[2];
        dlms_gas.recNonMetEventsCounter = data[3];
        dlms_gas.devCollection.addDatapoint('mType', data[0], dlms_gas.recUnixTime);
        dlms_gas.devCollection.addDatapoint('metCount', dlms_gas.recMetEventsCounter, dlms_gas.recUnixTime);
        dlms_gas.devCollection.addDatapoint('nonMetCount', dlms_gas.recNonMetEventsCounter, dlms_gas.recUnixTime);
        dlms_gas.devCollection.addDatapoint('contSinLect', false, dlms_gas.now);
    }
  }
};
dlms_gas.customBehavior(newBehavior);
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

If you want to modify the behavior of initAndCollect of some known compact frame (47, 48, 49, 51, and 97), it is even simpler, as they internally have an overridable collection method, so you only need to define that method in the custom behavior.

const newBehavior = {
  "initAndCollectCf48": function (data) { 
    //custom behavior
  }     
};
dlms_gas.customBehavior(newBehavior);
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

The initAndCollect function of the predefined compact frames 47, 48, 49, 51, and 97 internally calls the corresponding initAndCollectCfxx method. Therefore, you only need to overwrite that method to alter its behavior.

The same concept applies to the dlms_gas.pendingActions and dlms_gas.collect functions. Internally, they call methods defined in default. Therefore, they can be easily modified. For example, the order in which actions are performed could be modified or even new actions could be added as in the following example, where the default actions are invoked first and then a custom action is invoked.

const newBehavior = {
    "pendingActions": function () {
      dlms_gas.default.pendingActions();
      dlms_gas.custom.customPendingAction();
    },
    "customPendingAction": function() {
        // custom action
    }
};
dlms_gas.customBehavior(newBehavior);
dlms_gas.init();
dlms_gas.decode();
dlms_gas.pendingActions();
dlms_gas.collect();

The previous example shows several important concepts:

  • The pendingActions function is overwritten for the new behavior, so when the main dlms_gas.pendingActions() method is invoked, the new custom function will be executed.
  • A new function customPendingAction is defined and will be executed when dlms_gas.pendingActions() is invoked.
  • To call to the default pendingActions function, it is done through the default object (dlms_gas.default.pendingActions();) since we want to execute all the default pending actions.
  • To invoke the new customPendingAction function, we do it through custom (dlms_gas.custom.customPendingAction();), which is the object containing the new behavior.

To learn about the existing functions and properties defined for the behaviors, see the specifications for each of them in the following sections.


dlms_gas api specification

The dlms_gas object is the main entry point for Smart Gas operations.

It has several properties used to keep session status. See dlm_gas properties section and it also has some main basic functions. See dlm_gas functions section.

Finally it has complex properties to specifiy Connector Functions behavior:

dlms_gas properties

Following properties represent session state.

Property Type Default Description
now number null Current session timestamp in milliseconds. It is calculated in init method.
now_seconds number null Current session timestamp in seconds. It is calculated in init method.
behaviorName string "default" Active behavior name. It is calculated from device manufacturer in init method.
devCollection Object null Main device collection object. It is initialized automatically with normal collection object in init method.
cellCollection Object null Cellular network collection object. It is initialized automatically in init method.
uoCollection Object null Organization collection object. It is initialized automatically in init method.
recUnixTime number null Initiailized from received push notification.
EOGDTime number null End of Gas Day Time. Initiailized from received push notification.
recMetEventsCounter number null Metrological events counter. Initiailized from received push notification.
recNonMetEventsCounter number null Non-metrological events counter. Initiailized from received push notification.
messagesCounter number 0 Count of messages in current session.
numBlockErrorSession number 0 Used to manage fota blocks transfer.
numBlockTransfSession number 0 Used to manage fota blocks transfer.
restoreDefaultSchedule boolean false Used to manage restoring the default schedule.
onlineMngFrmCntr number null Online management frame counter. It is initialized from received push notification if available, otherwise is initialized from meter previously collected data.
messagesPerECL number null Count of messages per ECL. It is initialized in init method from used behavior

dlms_gas functions

dlms_gas.init(confEntityName)

Initializes the DLMS Gas API context. It loads provisioned and collected data from meter entity and provisioned configuration data from configuratiion entity if it is found. By default it uses the meter’s organization name to find created configuration entity, if it was created with different name it must be passed as argument.

See dlms_gas.config for more information about configuration data.

Property Type Default Description
confEntityName string null Optional organization name.

Examples:

dlms_gas.init();
dlms_gas.init(entity._value("provision.administration.organiaztion)+"_dev");

dlms_gas.decode(customTemplate, descriptive)

Decodes received payload after identifying the template and collects data. Internally it calls to behavior specific decode method. See DLMS Manufacturer Behavior section below for full specification of that method.

Parameter Type Default Description
customTemplate Object null Template to force.
descriptive boolean false Enable descriptive format.

Example:

var res = dlms_gas.decode();

dlms_gas.pendingActions()

Executes the full session flow. Internally it calls to behavior specific pendingActions method. See DLMS Manufacturer Behavior section below for full specification of that method.

By default it executes the following actions:

  1. sync clock: check and sync device clock
  2. retrieve initial data: used to retrieve data that is expected only once on device onboarding like firmware, apn configuration, etc. This data will be asked if it is not collected already.
  3. retrieve push events configurations: like initial data retrieving but for push events configurations, it will be asked if it is not collected already.
  4. periodic actions: used to retrieve data that must be retrieved periodically like statistics.
  5. automatic actions: used to retrieve data depending on previously collected data and received data in push notification.
  6. opengate operations: used to execute operations requested from opengate.

Previous actions execution can be controlled by dlms_gas.actions object properties. If the action is not enabled, it will not be executed. If it is forced it will ignore previous checks like statistics age or if initial data was already collected.

Examples:

//standard behavior
dlms_gas.pendingActions();
//skip statistics and force push events configuration retrieval
dlms_gas.actions.retrieveStatistics = false;
dlms_gas.actions.retrievePushEventsConfigurations = true;
dlms_gas.actions.forcePushConf = true;
dlms_gas.pendingActions();

dlms_gas.collect()

Used at the end of the script to send collected data for meter entity, cell enity and organization entity. Internally it calls to specific behavior collect method.

Example:

dlms_gas.collect();
Warning

It must used at the end of the Connector function to ensure that data collected during the execution is raised to opengate.

dlms_gas.customBehavior(behavior)

Changes the default behavior to a custom one. Internall it set dlms_gas.behaviorName property to "custom" and dlms_gas.custom property with the behavior provided as argument.

See DLMS Manufacturer Behavior section below for full specification of this method.

Property Type Default Description
behavior Object {} The behavior to use. If empty, is like using default behavior.

Example:

const customBehavior = {/*behavior specification*/};
dlms_gas.customBehavior(customBehavior);

dlms_gas._exec(callType, dType, uType)

It executes specified standard dlms call (get, set, method). It will use the dType and uType for msRaw collection. It will return an object with the result from dlms standard function or with the error message. This method is just utility and is not intended to be used directly. Instead it must be used dlms_gas.get, dlms_gas.set, dlms_gas.method or dlms_gas.getByRange.

Internally this method will do several actions:

  • Call collectMsRaw before and after the dlms standard function call.
  • Increase dlms_gas.messagesCounter property before the dlms call.
  • Increase and collect onlineMngFrmCntr if the dlms call was successful.
  • At the end, cleans dlms.attrList and dlms.methodList arrays.
Property Type Default Description
callType string Type of call to execute.
dType number mtype for messages sent to device.
uType number mtype for messages received from device.

Returned object will contain an object with the following properties:

  • error: Error message if some error occurs.
  • result: Return result from dlms standard function call. The result depends on the dlms method called (get, set, method).

dlms_gas.get(dType, uType)

It wrapes dlms.get calls adding extra behavior. dType and uType will be used for msRaw collection. The dlms.get response will be flattened in order to store the values in a single object. See examples below.

Property Type Default Description
dType number mtype for messages sent to device.
uType number mtype for messages received from device.

Returned object will contain.

object with the following properties:

  • error: Error message if some error occurs.
  • [classid_obis_attrid]: Values for the requested attributes, if attribute request was successful.

Example:

dlms.addAttr(1, '0.0.94.39.58.255', 2);
dlms.addAttr(45, '0.1.25.4.0.255', 2);
dlms.addAttr(3, '0.0.96.6.6.255', 2);
const res = dlms_gas.get(-8, 4);

Some return examples:

{
  "1_0.94.39.58.255_2": ...returned value from dlms.get... ,
  "45_0.1.25.4.0.255_2": ...returned value from dlms.get... ,
  "3_0.96.6.6.255_2": ...returned value from dlms.get...
}

If some attribute request fails, the error will be added to the error property.

{
  "error": "...errors specification separated by ';'",
  "1_0.0.94.39.58.255_2": ...returned value from dlms.get...
}

If the dlms.get request fails, the error property will be set and no attribute values will be returned.

{
  "error": "... error message ..."
}

dlms_gas.set(dType, uType)

It wrapes dlms.set calls adding extra behavior. dType and uType will be used for msRaw collection. The dlms.set response will be flattened in order to store the values in a single object. See examples below.

Property Type Default Description
dType number mtype for messages sent to device.
uType number mtype for messages received from device.

Returned object will contain an object with the following properties:

  • error: Error message if some error occurs.
  • [classid_obis_attrid]: Results for the modified attributes.

Example:

dlms.addAttr(22, '0.0.15.0.1.255', 2, 'structure', [{ 'type': 'octet-string', 'value': [0, 0, 10, 0, 106, -1] }, { 'type': 'long-unsigned', 'value': vst }]);
dlms.addAttr(22, '0.0.15.0.1.255', 4, 'array', [{ 'type': 'structure', 'value': [{ 'type': 'octet-string', 'value': timeOctet }, { 'type': 'octet-string', 'value': dateOctet }] }]);
const dlmsResp = dlms_gas.set(-13, 6);

Some return examples:

{
  "22_0.0.15.0.1.255_2": "success",
  "22_0.0.15.0.1.255_4": "success"
}

If some attribute modification returns an error, the error will be added to the error property and the response will be “success” for the rest of the attributes.

{
  "error": "...errors specification...",
  "22_0.0.15.0.1.255_2": "error message",
  "22_0.0.15.0.1.255_4": "success"
}

If the dlms.set request fails, the error property will be set and no attribute values will be returned.

{
  "error": "... error message ..."
}

dlms_gas.method(dType, uType)

It wrapes dlms.method calls adding extra behavior. dType and uType will be used for msRaw collection. The dlms.method response will be flattened in order to store the values in a single object. See examples below.

Property Type Default Description
dType number mtype for messages sent to device.
uType number mtype for messages received from device.

Returned object will contain.

object with the following properties:

  • error: Error message if some error occurs.
  • [classid_obis_attrid]: Results for the modified attributes, if attribute modification was successful.

Example:

dlms.addMethod(3, '7.0.96.5.1.255', 1, 'integer', 0);
const dlmsResp = dlms_gas.method(-18, 18);

Some return examples:

{
  "3_7.0.96.5.1.255_1": "success"
}

If some method execution returns an error, the error will be added to the error property and the response will be “success” for the rest of the attributes.

{
  "error": "...errors specification...",
  "3_7.0.96.5.1.255_1": "error message"
}

If the dlms.method request fails, the error property will be set and no attribute values will be returned.

{
  "error": "... error message ..."
}

dlms_gas.getByRange(classId, obis, attrId, accessSelector, paramClassID, paramObis, paramAttrId, rangeType, rangeFrom, rangeTo, maxRangePerPage, dType, uType)

It retrieves values by range using dlms.get with selective access. It retrieves all the values within the range, even if the device returns values in multiple pages. In case of any page retrieval fails, the error will be added to the error property and the response will be “success” for the rest of the pages.

Property Type Default Description
classId number Class ID of the object.
obis string OBIS code.
attrId number Attribute ID.
accessSelector number Access selector (e.g., 1 for range).
paramClassID number Selector’s parameter Class ID.
paramObis string Selector’s parameter OBIS code.
paramAttrId number Selector’s parameter Attribute ID.
rangeType string Data type for range values (e.g., ‘double-long-unsigned’).
rangeFrom number Start of range.
rangeTo number End of range.
maxRangePerPage number Maximum range size. For event buffer ranges, the number of elements per page. For temporal ranges max period for page.
dType number mtype for messages sent to device.
uType number mtype for messages received from device.

It returns an object with the following properties:

  • result: Array of all values retrieved.
  • error: Error message if any error occurs.

Example:

const res = dlms_gas.getByRange(7, '0.0.99.1.0.255', 2, 1, 8, '0.0.1.0.0.255', 2, 'double-long-unsigned', lastIndex, currentIndex, 10, -8, 4);
Tip

There some objects to make easier the call to this method. Check the [Range retrieval configuration object section][#range-retrieval-configuration-object]

dlms_gas.config Object Properties

Following properties are loaded from device entity and from “configuration entity” when executing dlms_gas.init method. Some of them contain connected meter status and data and other contain configuration values from configuration entity.

Property Type Default Description
orgName string null Name of the organization that the meter belongs to.
confEntityName string null Name of the entity that contins configuration parameters. See dlms_gas.init method to see how it is initialized
systemTitle string null Meter System title.
cellPrefix string null Prefix for the cell identification. It can be defined in the configuration entity.
apiKey string null API Key for the platform. It must be defined in the configuration entity.
periodicDataAgeMillis number null Maximum age of periodic data in milliseconds. It can be calculated from data in configuration entity.
maxSecondsWithoutCom number null Maximum seconds without communication. It can be calculated from data in configuration entity.
cellPlanName string null Name of the cell plan. It can be defined in the configuration entity.
maxClockSkewAllowedSec number null Maximum difference in time for clock sync in seconds. It can be defined in the configuration entity.
maxClockCorrection number null Maximum clock correction allowed. In this case it is filled for specified behavior
numBlockError number null It contains meter’s FOTA process blocks number with transfer error.
numBlockTransf number null It contains meter’s FOTA process successufully transferred blocks number.
badSessionsCounter number null It contains meter’s FOTA process failed sessions counter
maxSessionsErrorsRate number null It contains FOTA process maximum block errors rate allowed in a session. It can be defined in the configuration entity.
maxBadSessions number null It contains FOTA process maximum bad sessions before FOTA abort. It can be defined in the configuration entity
manufacturer string null Meter manufacturer.
italianMode boolean false Enable Italian specific mode. Calculated from manufacturer.
deviceId string null Meter identifier.
cellId string null Cell identifier. It is filled from device collected cell identifier.
fotaBlockSize number null FOTA block size for current meter. It is filled from collected data.
fotaEnabled boolean false Indicates if the meter has FOTA enabled. It is filled from collected data.
fotaNumberOfBlocks number null FOTA total number of blocks for current meter. It is calculated and collected at the begining of FOTA process
lastEventCounter number null Counter for the last event. It is filled from meter’s previously collected data.
lastCommunication number null Timestamp for the last communication. It is filled from meter’s previous last notification.

Next table indicates which datastreams are used to init these properties:

Property Entity Datastream Default value
orgName Meter provision.administration.organization null
manufacturer Meter provision.device.model null
deviceId Meter provision.device.serialNumber null
systemTitle Meter provision.administration.identifier null
lastEventCounter Meter metCount null
cellId Meter NBcellID null
fotaBlockSize Meter fotaBlockSize null
fotaNumberOfBlocks Meter firmwareTotalBlock null
fotaEnabled Meter fotaEnabled null
numBlockError Meter numBlockError 0
numBlockTransf Meter numBlockTransf 0
badSessionsCounter Meter badSessionsCounter 0
lastCommunication Meter mType null
cellPrefix Configuration provision.ACR orgName_
periodicDataAgeMillis Configuration provision.periodicDataAgeDays 1296000000 (15 days in milliseconds)
maxSecondsWithoutCom Configuration provision.maxDaysWithoutCom 259200 (3 days in seconds)
maxClockSkewAllowedSec Configuration provision.maxClockSkewAllowedSec 120
maxSessionsErrorsRate Configuration provision.maxSessionsErrorsRate 0.2
maxBadSessions Configuration provision.maxBadSessions 3
cellPlanName Configuration provision.cellPlanName null
apiKey Configuration provision.administration.apiKey null
Warning

Datastream used to initialize periodicDataAgeMillis and maxSecondsWithoutCom contains time in days and they are converted to milliseconds and seconds respectively.

It is possible to override this values after init calling to dlms_gas.init():

dlms_gas.init();
dlms_gas.config.maxClockSkewAllowedSec = 60;

dlms_gas.config Object Functions

config.__initApiKey(apiKey)

Internal utility used to initialize the API key.

Parameter Type Description
apiKey string The API key to be forced into the session context.

If it is necessary to specify manually the apikey from Connector Function it must be called after dlms_gas.init call. Example:

dlms_gas.init();
dlms_gas.config.__initApiKey('your-api-key');

dlms_gas.behavior Object properties

Property Type Default Description
chain Set<string> null It contains the behavior chain used to resolve function or property call. It is initilized in dlms_gas.init

dlms_gas.behavior Object Functions

behavior.getName(manufacturer)

Calculates and returns behavior name from manufacturer parameter (Not case session). This method is called from dlms_gas.init function only if dlms_gas.behaviorName is null.

Parameter Type Default Description
manufacturer string null Meter provisioned manufacturer name.

Next table explains current behaviors:

Behavior name Manufacturer
pietro If manufacturer contains ‘pietro’
honeywell If manufacturer contains ‘honeywell’
spark If manufacturer contains ‘spark’
watertech If manufacturer contains ‘watertech’
default If manufacturer is null or contains none of the above

behavior.calculateChain(behaviorName, visited)

Internall utility to calculate recursively the behavior chain. It is called from dlms_gas.init and it will return a Set with all behaviors to be checked when a function or property is called. It will take into account that specified behavior exists, if not it will return default behavior as last element of the chain. Something similiar will happen if there is a circular baseBehavior reference.

Parameter Type Default Description
behaviorName string null The name of the behavior to calculate the chain for. If null, it uses dlms_gas.behaviorName
visited Set<string> new Set() A set of behavior names that have already been visited. Used to detect circular references

For example, if custom behavior is defined with pietro as baseBehavior:

const chain = dlms_gas.behavior.calculateChain('custom');
//it will return following chain: ['custom', 'pietro', 'default']

In case that custom behavior has invalid baseBehavior (it doesn’t exist), it will return following chain:

//having custom behavior with invalid baseBehavior, for example 'nonExistentBehavior'
const chain = dlms_gas.behavior.calculateChain('custom');
//it will return following chain: ['custom', 'default']

behavior.property(propertyName)

Returns property value from behavior chain in order to call it. It will return the property value if exists in any behavior in the chain, if not it will return null.

Warning

This method should be used when specifying a custom behavior to ensure that the value returned is the best match for the current behavior chain.

Parameter Type Default Description
propertyName string null The name of the property to retrieve

behavior.function(functionName)

Returns function from behavior chain in order to call it. It will return the function if exists in any behavior in the chain, if not it will empty function.

Warning

This method should be used when specifying a custom behavior to ensure that the function returned is the best match for the current behavior chain.

Parameter Type Default Description
functionName string null The name of the function to retrieve

Example of function calling using behavior management:

    const address = dlms_gas.behavior.function("encodeIpPort")(pConf.platform.ip, pConf.platform.port);
Warning

When overriding one function in custom behavior take care to not call itselsf using this method because it will throw exception due to infinite recursion

Example of bad use of function method and how to override correctly the function:

const cb = {
  "retrieveStatistics": function(data){
    dlms_gas.behavior.function('retrieveStatistics')(); //Bad practice: Infinite recursion
    dlms_gas.default.retrieveStatistics(); //the correct way to do it
    dlms_gas.honeywell.retrieveStatistics(); //the correct way to do it
    //... extra code ...
  }
}

dlms_gas.actions Object Properties

Control flags to enable or disable specific automated tasks.

Property Type Default Description
setClock boolean true Enable automated clock synchronization.
retrieveInitialData `boolean" true Enable FW and static config retrieval.
retrievePushEventsConfigurations boolean `true" Enable PUSH event config retrieval.
periodicActions boolean `true" Enable statistics and diagnostic retrieval.
automaticActions boolean `true" Enable logs and profile retrieval.
operations boolean `true" Enable pending operation execution.
forceInitialData boolean false Force retrieval of initial data.
forcePushConf boolean false Force retrieval of push configuration.
forceStatistics boolean false Force retrieval of statistics.

dlms_gas.default object Properties

Following properties are defined in dlms_gas.default and used when no manufacturer specific property is defined.

Property Type Value Description
47 Object Specification for Compact Frame 47. Includes template and initAndCollect. See decoding section.
48 Object Specification for Compact Frame 48. Includes template and initAndCollect. See decoding section.
49 Object Specification for Compact Frame 49. Includes template and initAndCollect. See decoding section.
51 Object Specification for Compact Frame 51. Includes template and initAndCollect. See decoding section.
97 Object Specification for Compact Frame 97. Includes template and initAndCollect. See decoding section.
22 Object Specification for Compact Frame 22. Used in FOTA process.
cwport number 1 Used to define dlms.cwport when initializing client
swport number 1 Used to define dlms.swport when initializing client
hesSystemTitle string 5341435341435341 Used to define dlms.hesSystemTitle when initializing client
conformance string ['MULTIPLE_REFERENCES', 'GENERAL_PROTECTION', 'SELECTIVE_ACCESS'] Used to define dlms.conformance when initializing client
forceGetWithoutList boolean false Used to define dlms.forceGetWithoutList when initializing client
forceSetWithoutList boolean false Used to define dlms.forceSetWithoutList when initializing client
ignoreSystemTitleInCiphering boolean true Used to define dlms.ignoreSystemTitleInCiphering when initializing client
onlineFramCounterRetryInc number 5 Used to synchronize meters counter with collected frame counter.
onlineFramCounterRetryMax number 3 Used to synchronize meters counter with collected frame counter.
maxClockCorrection number 900 Default maximum clock correction allowed.
messagesPerECL object { "0": 20, "1": 20, "2": 0 } To limit fota blocks depending on ECL value.
isItalianModeManufacturer boolean true Indicates if manufacturer follows Italian mode by default.
eclAttribute number 3 Attribute ID for ECL retrieval.
errorIfWrongFotaBlockMapSize boolean true Specify if fota operation must finish immediately with error if block map length retrieved in CF22 does not match with calculated number of blocks. If false, block map array will be resized to the calculated number of blocks.
statisticsRefDs string "MetBattRemUseTime" Data stream reference for statistics retrieval.
supportedOps Array List of supported operations and their priority for execution. see operations spec.

Range retrieval configuration object

To simplify metrological events, non-metrological events, daily profiles and hourly profiles retrieval customization following object is used to define range selection parameters. It is used internally when calling getByRange function.

Property Type Description
classId number Data to be retrieved class id.
obis string Data to be retrieved obis.
attrId number Data to be retrieved attribute id.
accessSelector number Data to be retrieved attribute id.
paramClassID number Range parameter specification classID.
paramObis string Range parameter specification obis.
paramAttrId number Range parameter specification attrId.
rangeType string Range parameter specification rangeType.
maxRangePerPage number Used to specify pagination

Next are default configurations for specified retrievals:

{
    "metEventsRangeSelection": {
      "classId": 7,
      "obis": '7.0.99.98.1.255',
      "attrId": 2,
      "accessSelector": 1,
      "paramClassID": 1,
      "paramObis": [0, 0, 96, 15, 1, -1],
      "paramAttrId": 2,
      "rangeType": "long-unsigned",
      "maxRangePerPage": 7
    },
    "nonMetEventsRangeSelection": {
      "classId": 7,
      "obis": '7.0.99.98.0.255',
      "attrId": 2,
      "accessSelector": 1,
      "paramClassID": 1,
      "paramObis": [0, 0, 96, 15, 2, -1],
      "paramAttrId": 2,
      "rangeType": "long-unsigned",
      "maxRangePerPage": 8
    },
    "dailyProfilesRangeSelection": {
      "classId": 7,
      "obis": '7.0.99.99.3.255',
      "attrId": 2,
      "accessSelector": 1,
      "paramClassID": 1,
      "paramObis": [0, 0, 1, 1, 0, -1],
      "paramAttrId": 2,
      "rangeType": "double-long-unsigned",
      "maxRangePerPage": 10 * 24 * 3600
    },
    "hourlyRangeSelection": {
      "classId": 7,
      "obis": '7.0.99.99.2.255',
      "attrId": 2,
      "accessSelector": 1,
      "paramClassID": 1,
      "paramObis": [0, 0, 1, 1, 0, -1],
      "paramAttrId": 2,
      "rangeType": "double-long-unsigned",
      "maxRangePerPage": 20 * 3600
    }
}

Operations specification

supportedOps is used to specify Opengate operations execution. This property is an array of objects that contains operation name and function to be called. Operations will be executed following the order they are defined in the array.

Property Type Description
name string Opengate operation name.
funcName string Function to be called when specified operation is executed.

Default value:

{
    "supportedOps":
      [{
        "name": "ValveManagement",
        "funcName": "valveManagement"
      }, {
        "name": "ResetDiagnostic",
        "funcName": "resetDiagnostic"
      }, {
        "name": "RequestNonMetroLogs",
        "funcName": "requestNonMetroLogs"
      }, {
        "name": "HourlyValues",
        "funcName": "hourlyValues"
      }, {
        "name": "CommsBatStatus",
        "funcName": "commsBatStatus"
      }, {
        "name": "APNConfig",
        "funcName": "apnConfig"
      }, {
        "name": "PushStrategy",
        "funcName": "pushStrategy"
      }, {
        "name": "FOTA",
        "funcName": "fota"
      }]
}

On one hand it is possible to specify custom array with custom functions. On the other hand it is possible just to override specified function (for example "valveManagement" function) just to customize specific operation behavior.

dlms_gas.default object Functions

default.apnConfig(op)

Apn configuration operation logic. Configures the SIM APN and PLMN code on the device and processes the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.automaticActions()

Orchestrates automatic data retrieval functions. These functions retrieve data from the device depending on last collected data and new received data. Following functions are called in order:

default.closeConnection()

Called at then end of pendingActions function. In this case (default behavior) it is empty.

default.collect()

Sends the gathered datapoints for the device, cell, and organizational unit. It takes into account if dls_gas.devCollection, dls_gas.cellCollection or dls_gas.uoCollection are defined and they have identifier field is defined.

Warning

In the case of cellCollection it will check if cell entity exists and create if necessary.

default.collectBillingPeriodSnapshotData(billingPeriodData)

Collects the billing period data snapshot. Receives an with the values of decoded billing period snapshot:

Parameter Type Description
billingPeriodData object Object containing the billing period data.

default.collectDiagnostic(diagnostic, at, source, sourceInfo)

Decodes a 16-bit diagnostic value into individual status flags that are collected with specified at, source and sourceInfo.

Parameter Type Description
diagnostic number Diagnostic value to be decoded.
at number Timestamp to be used for collection. If not defined current time will be used.
source string If defined it will be used as datapoint source.
sourceInfo object If defined it will be used as datapoint sourceInfo.

default.collectHourlyDiagnostics(diagnosticsArray, unixTime)

Collects an array of hourly diagnostics values with at time as reference.

Parameter Type Description
diagnosticsArray Array Array with hourly diagnostics values
at number Timestamp to be used as reference.

default.collectHourlyVolumes(incsArray, at)

Collects an array of hourly volume increments with at time as reference.

Parameter Type Description
incsArray Array Array with hourly volume increments
at number Timestamp to be used as reference.

default.collectMsRaw(mType, payload, payloadSize)

Internal utility to collect raw messages. It adds msRaw datapoint to device, cell and organizational unit collections. Datapoint is composed by provided arguments.

Parameter Type Description
mType number Message type.
payload string Raw hex payload.
payloadSize number Payload size in bytes.

Examples:

// For received compact frame
dlms_gas.manufacturer.function("collectMsRaw")(contextParams.templateId, utils.bytes.toHexString(payload.value), payload.value.length);
// For dlms request sent to device
dlms_gas.manufacturer.function("collectMsRaw")(-22);
// For dlms response received from device
dlms_gas.manufacturer.function("collectMsRaw")(22);

default.collectNetworkStatus(networkStatus, at)

Decodes an 8-bit network status integer value into individual flags and adds it to the device collection.

Parameter Type Description
networkStatus number Status to be decoded.
at number Timestamp to be used for collection. If not defined current time will be used.

default.collectTarifPlan(tariffPlann, at)

Transforms and collects received array of two numbers into an array of two bytes hexadecimal string.

Parameter Type Description
tariffPlann array Array of bytes representing the tariff plan.
at number Timestamp to be used for collection. If not defined current time will be used.

default.collectDailyLoadProfilesArray(loadProfiles, source, sourceInfo)

Collects from received daily profiles with specified source and sourceInfo. Each element of array must be an object with the following fields:

Parameter Type Description
loadProfiles Array Array of daily profiles to collect.
source string Optional source identifier.
sourceInfo object Optional source information.

Each element of the array is an array with 4 elements:

Element Index Type Description
0 number End of Gas day timestamp.
1 number End of Gas day cumulative diagnostic
2 number End of Gas day volume
3 number End of Gas day volume under alarm.

default.commsBatStatus(op)

Comms bat status retrieval operation logic. Retrieves battery status and communication statistics from the device and processes the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.configClient()

Initializes the dlms client parameters for sending requests to the device. This method is called from dlms_gas.init function.

default.createCellIfNecessary()

Automatically provisions a new NBIoT Cell entity in Opengate if it doesn’t exist. It uses NBcellID as entity name.

default.dateToDateOctet(date)

Converts a JavaScript Date object into DLMS octet-string format for date (5 bytes).

Parameter Type Description
date Date Date to convert.

Returns an object with following fields:

Field Type Description
result Array<number> DLMS octet-string format for date (5 bytes).
error string Error message.

Example:

const date = new Date("2026-04-23T05:30:00.000Z");
const dateOctet = dlms_gas.manufacturer.function("dateToDateOctet")(date);
// Example: dateOctet = { result: [ 7, 234, 4, 23, 4 ] }

default.dateToTimeOctet(date)

Converts a JavaScript Date object into DLMS octet-string format for time (4 bytes).

Parameter Type Description
date Date Date to convert.

Returns an object with following fields:

Field Type Description
result Array<number> DLMS octet-string format for time (4 bytes).
error string Error message.

Example:

const date = new Date("2026-04-23T05:30:00.000Z");
const dateOctet = dlms_gas.manufacturer.function("dateToTimeOctet")(date);
// Example: dateOctet = { result: [ 5, 30, 0, 0 ] }

default.decode(customTemplate, descriptive)

The main entry point for Compact Frame decoding. It identifies the correct template based on the templateId in the context (or it uses the provided customTemplate), performs the decoding, and triggers the collection logic.

If customTemplate is provided, it is used to decode the compact frame, otherwise predefined templates will be used.

For compact frame decoding see dlms api documentation .

Parameter Type Description
customTemplate object Template to be used for compact frame decoding.
descriptive boolean If true, the decoded values will be in a more descriptive format.

Returns an object with following fields:

Field Type Description
result object Decoded data.
error string Error message.
const decodedData = dlms_gas.manufacturer.function("decode")();
// Correct result: decodedData = { result: [22, 225, 37, 203, 0, 15, 225, 233, 128, 255, 123, 32, 241, 71, 57, 187, 177, 79, 2, 48] }
// some error case: decodedData = { error: "error description" }

default.decodeFw(fwBytes)

Decodes a 6-byte array into a descriptive firmware version string including version numbers, build commit (hex), and date.

Returned version will be something like this: Version:${major}.${minor}.${patch};Build:0x${commitField.toString(16).toUpperCase().padStart(4, "0")};Fecha:${year}-${String(month).padStart(2, "0")}-${String(day).padStart(2, "0")}

Parameter Type Description
fwBytes Array<number> Array of 6 bytes representing the firmware version.

Returns an object with following fields:

Field Type Description
result string Decoded firmware version string. It is returned with next template:
error string Error message.
const fwBytes = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06];
const fwVersion = dlms_gas.manufacturer.function("decodeFw")(fwBytes);
// Example: fwVersion = { result: "Version:1.2.3;Build:0x4506;Fecha:2026-04-23" }

default.doPushEventConfiguration(event, conf)

Internal function that executes the actual DLMS set operations to apply push event configurations.

Parameter Type Description
event number Event number (1, 2, 3, 4).
conf object Configuration for the event.

conf object has the following properties:

Property Type Description
cf number Compact frame to be configured
addressOctStr byte[] Ip:port string coded as byte array
randomTime number Random time to be used in communications
schedule Object[] Schedulation specification.

schedule is an array of four objects. Each object has the following properties:

Property Type Description
dateOctet byte[] Communication periodicity expression following DLMS standard.
timeOctet byte[] Communication time specification: [Hour, Minute, Second, Hundredths]

default.encodeIpPort(ip, port)

Encodes an IP address and port into a 22-byte octet-string for push configuration.

Parameter Type Description
ip string IP address to encode.
port number Port to encode.

Returns an byte array

Example:

const ip = "127.0.0.1";
const port = 8080;
const ipPort = dlms_gas.manufacturer.function("encodeIpPort")(ip, port);
// Example: ipPort = [ 49, 50, 55, 46, 48, 46, 48, 46, 49, 58, 56, 48, 56, 48];

default.eventScheduleArray(scheduleData)

Event DLMS schedule array generation logic. Generates the event schedule array for push events configuration. Adds the 4 events with corresponding periodicity and hour specification including disabled events.

Parameter Type Description
scheduleData Object Object with event’s day periodicty value and hour specification value from operation paraemeters.

Returns an array of objects with date and time octet. Example:

[
  {
    "dateOctet": "[-1, -1, -1, 3, -40]",
    "timeOctet": "[0, 5, 0, 0]"
  },
  {
    "dateOctet": "[-1, -1, -1, 3, -40]",
    "timeOctet": "[3, 5, 0, 0]"
  },
  {
    "dateOctet": "[-1, -1, -1, -1, -1]",
    "timeOctet": "[-1, -1, -1, -1]"
  },
  {
    "dateOctet": "[-1, -1, -1, -1, -1]",
    "timeOctet": "[-1, -1, -1, -1]"
  }
]

default.fota(op)

FOTA configuration operation logic. It manages specific scheduling, fota process initialization, blocks transfers by sessions and different process status management. It manage the operation status allong all the process.

Parameter Type Description
op Object Object returned by operation api.

default.fotaAdjustBlocks(imageTransferBlocksMap, expectedNumberOfBlocks)

Recalculates and returns blocks map according to the expectedNumberOfBlocks calculated at the FOTA operation beginig. If received array shorter than expected it is filled with false values. If it is larger, it is truncated to the expected number of blocks.

Parameter Type Description
imageTransferBlocksMap Array List of blocks retrieved in CF22
expectedNumberOfBlocks number Expected number of blocks calculated in FOTA process initialization.

Returns an array with the adjusted blocks status map.

default.fotaBlocksTransfer(op, blocksStatusMap)

Orchestrates the transmission of multiple firmware blocks in a single session, respecting the maximum messages allowed for the current ECL. It manages specially first and last block sent to update operation status. It also manages errors per session.

Parameter Type Description
op Object Object returned by operation api.

default.fotaBlockTransfer(blockIndex, bundleName, bundleVersion, deploymentName, deploymentVersion)

Executes the actual transmission of a single firmware block calling dlms.sendFotaPage method. It increase success and error counters.

Parameter Type Description
op Object Object returned by operation api.

default.fotaCalculateIdentifier(op)

Calculates the unique image identifier based on KDL, hashtag, and activation date. It adds at the beginning of the identifier follwing bytes 014D.

Parameter Type Description
op Object Object returned by operation api.

Returns an object with following properties:

Property Type Description
result Array<number> Array with the calculated image identifier.
error string Error message.

Example:

{
  "result": "[1, 77, 14, 50, 145, 16, 132, 16, 233, 67, 18, 99, 235, 189,...]"
}

default.fotaCheckAllowed(op)

Verifies if the device is correctly configured for FOTA (valid block size and FOTA enabled). It updates operation status according to the validation.

Parameter Type Description
op Object Object returned by operation api.

default.fotaCheckBadSessions()

Aborts the FOTA process if the number of consecutive bad sessions reaches the maximum allowed threshold and throws an error. It uses badSessionsCounter and maxBadSessions from dlms_gas.config.

default.fotaCheckSessionBlocksErrors()

Just checks session errors rate and updates bad sessions counter.

default.fotaContinueProcess(op)

Internal function used to continue FOTA operation from different sessions: it manage different process status, sends blocks and finalizes operation according to final status (including device default scheduling).

It updates operation status using op parameter.

Parameter Type Description
op Object Object returned by operation api.

default.fotaImgActivate(op)

Function intended to invoke image activation DLMS method, but actually is empty function in default behavior. It can be implemented in specific behaviors.

Parameter Type Description
op Object Object returned by operation api.

default.fotaImgVerify(op)

Function intended to invoke image verification DLMS method, but actually is empty function in default behavior. It can be implemented in specific behaviors.

Parameter Type Description
op Object Object returned by operation api.

default.fotaImgTransferInitiate(op)

Invokes image transfer process initiation DLMS method and calculates the total number of blocks based on the firmware size and configured block size. It updates operation status.

Parameter Type Description
op Object Object returned by operation api.

default.fotaRestoreDefaultSchedule(op)

Restores the default push strategy schedule after the FOTA process is finished or cancelled. It updates operation status.

Parameter Type Description
op Object Object returned by operation api.

default.fotaScheduleForFota(op)

Temporary updates the push strategy schedule to a more aggressive frequency (every hour) during the FOTA process to speed up block transmission. It updates operation status.

Parameter Type Description
op Object Object returned by operation api.

default.fotaStartProcess(op)

Internal function used to complete first steps of FOTA operation: device status validation, device special scheduling and fota process initialization in the meter.

It updates operation status using op parameter.

Parameter Type Description
op Object Object returned by operation api.

default.fotaStateFromCf22(op)

It retrieves CF22 and updates session data to continue with FOTA proess.

Parameter Type Description
op Object Object returned by operation api.

It returns an object with transfer status and transfered blocks map. Example:

{
  "transferStatus": 1,
  "blocksMap": "[true, true, false, false]"
}

default.fotaStatus0(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 0. Actually it calls fotaStatusUnknown function because this function is not supposed to be executed.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus1(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 1. Try to send pending blocks or call image verification function.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus2(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 2. In default behavior it does nothing.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus3(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 3. It just calls to fotaImgActivate function.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus4(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 4. It finishes the FOTA process with image verification error.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus5(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 5. In default behavior it does nothing.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus6(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 6. Asks to device for new firmware data, restores default scheduling and finlizes FOTA operation.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatus7(op, fotaState)

Executed when the devices Compact Frame 22 retrieve status 7. It finishes the FOTA process with image activation error.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaStatusUnknown(op, fotaState)

Executed when the devices Compact Frame 22 retrieve an unexpected status. In default behavior it just incresaes bad sessions counter.

Parameter Type Description
op Object Object returned by operation api.
fotaState object FOTA status object with returned by fotaStateFromCf22 function.

default.fotaUpdateLostSteps(fotaState, op)

Function that depending on fotaState (process status and blocks maps) updates operation lost steps.

Parameter Type Description
fotaState object FOTA status object with returned by fotaStateFromCf22 function.
op Object Object returned by operation api.

default.fotaUpdateSuccessBlocksFromDevice(imageTransferBlocksMap)

Updates the internal block transmission counter based on the blocks retrieved form CF 22.

Parameter Type Description
imageTransferBlocksMap Array Array with boolean values representing the status of each block.

default.getHourlyArrayWithAt(hourlyArray, refTime)

From an array with hourly data (volumes, diagnostics…) and with refTime as reference, build an array with the at time of each increment.

Parameter Type Description
hourlyArray Array Array with hourly data (volumes, diagnostics…)
refTime number Timestamp to be used as reference

Returns an array with following objects:

[
  {
    "value": "120",
    "at": "1783051200"
  },
  {
    "value": "125",
    "at": "1783054800"
  },
  {
    "value": "150",
    "at": "1783058400"
  },
  {
    "value": "200",
    "at": "1783062000"
  }
  ....
]

default.getPeriodictyOctet(period, time)

Returns the DLMS date octet-string representing the periodicity for push event schedulation. It takes into account both period and time.

Parameter Type Description
period string Name of periodicty. Check table below for supported values.
time string Time value. It is used just to check if it is null and then return Disabled octet

These are codification rules for periodicity:

Periodicty name Returned octet
Disabled [-1, -1, -1, -1, -1]
every1Day [-1, -1, -1, 1, -40]
every2Day [-1, -1, -1, 2, -40]
every3Day [-1, -1, -1, 3, -40]
endOfBilling [-1, -1, -1, -1, -36]
everyMonday [-1, -1, -1, -1, 1]
everyTuesday [-1, -1, -1, -1, 2]
everyWednesday [-1, -1, -1, -1, 3]
everyThursday [-1, -1, -1, -1, 4]
everyFriday [-1, -1, -1, -1, 5]
everySaturday [-1, -1, -1, -1, 6]
everySunday [-1, -1, -1, -1, 7]

If invalid periodicty is used, an exception will be thrown.

default.getTimeOctet(period, time)

Returns the DLMS time octet for push event schedulation. It takes into account both period and time.

Parameter Type Description
period string Name of periodicty. If it is null or Disabled, then “Disabled” time octet ([-1, -1, -1, -1]) will be returned
time string Time value. It is parsed into time octet. If it si null, then “Disabled” ([-1, -1, -1, -1]) octet will be returned

default.getStepByName(op, stepName, checkInCurrentResponse)

Search in passed operation object if the step is already completed. If checkInCurrentResponse is not specified, it will check only in steps completed in the operation. If checkInCurrentResponse is specified and it is true, it will check also in the steps added in current execution.

Parameter Type Description
op Object Object returned by operation api.
stepName string Name of the step to search.
checkInCurrentResponse boolean Whether to check in the current step response. Default value is false

default.hourlyValues(op)

Horly values retrieval operation logic. Retrieves hourly incremental volume values from the device by range and processes the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.initAndCollectCf47(data)

Function called from dlms_gas.decode after decoding 47 compact frame from received notification. Initialize parameters to be used later and collects received fields.

Parameter Type Description
data Object Object with decoded compact frame data return from dlms.getCompactData() method.

default.initAndCollectCf48(data)

Function called from dlms_gas.decode after decoding 48 compact frame from received notification. Initialize parameters to be used later and collects received fields.

Parameter Type Description
data Object Object with decoded compact frame data return from dlms.getCompactData() method.

default.initAndCollectCf49(data)

Function called from dlms_gas.decode after decoding 49 compact frame from received notification. Initialize parameters to be used later and collects received fields.

Parameter Type Description
data Object Object with decoded compact frame data return from dlms.getCompactData() method.

default.initAndCollectCf51(data)

Function called from dlms_gas.decode after decoding 51 compact frame from received notification. Initialize parameters to be used later and collects received fields.

Parameter Type Description
data Object Object with decoded compact frame data return from dlms.getCompactData() method.

default.initAndCollectCf97(data)

Function called from dlms_gas.decode() after decoding 97 compact frame from received notification. Initialize parameters to be used later and collects received fields.

Parameter Type Description
data Object Object with decoded compact frame data return from dlms.getCompactData() method.
Warning

In this case, because received compact frame does not contain onlineFrameCounter it will try to recovery from the device using previously collected frame counter to initilialize client. See default.restoreOnlineFrameCounter() function

default.operations()

Dispatches and executes active operations from the Opengate platform. Retrieves all alive operations for the device using Operations JS Api. It iterates through supportedOps and executes the process for any matching active operation.

default.pendingActions()

The main entry point for a standard communication session. It orchestrates the actions to be performed in a session. It uses dlms_gas.actions object to determine which actions to perform.

The order of actions are:

default.periodicActions()

Orchestrates periodic data retrieval functions. These functions retrieve data from the device periodically:

default.pushStrategy(op)

Push configuration operation logic. Configures the push communication strategy (Compact Frame selection, platform address/port, and scheduling) for the four supported push events and process the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.requestNonMetroLogs(op)

Non metrological logs retrieval operation logic. Retrieves non-metrological event logs from the device by range and processes the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.resetDiagnostic(op)

Reset diagnostic operation logic. Resets the device’s diagnostic status flags by executing the corresponding DLMS method and process the operation response.

Parameter Type Description
op Object Object returned by operation api.

default.restoreOnlineFrameCounter()

This method is used when received compact frame does not contain onlineFrameCounter and it is necessary to request it to the device in order to set correct values for next requests.

In uses previously collected online onlineFrameCounter to initilialize the client’s online frame counter and then it requests the device to retrieve its actual value. If the device does not response it tries again increasing used frames counter with the value specified in onlineFramCounterRetryInc property. It will try to request onlineFrameCounter to the device up to onlineFramCounterRetryMax times.

default.retrieveDailyProfiles()

If the device does not communicate in last days it will ask for all missing daily profiles.

default.retrieveInitialData(force)

Retrieves one-time device information. It will check if device.software datastream is not collected or force parameter is true. If so it will retrieve following data:

  • Metrological and Non-metrological Firmware versions.
  • APN configuration.
  • FOTA block configuration.
Parameter Type Description
force boolean If true, retrieves the data even if it was previously collected.

default.retrieveMetrologicalEvents()

Retrieves missing metrological events from the device by range, starting from the last collected counter.

default.retrievePushEventsConfigurations(force)

Retrieves configuration for all push events (1-4) configuration. It will check for each event if confCFx datastream is not collected or force parameter is true. If so it will retrieve push event configuration.

default.retrieveStatistics(force)

Retrieves periodically communication statistics (Signal Power, RSRQ, RSRP, ECL, Battery remaining time….). It will check statisticsRefDs datastreams at value and if the data is too old (using periodicDataAgeMillis as reference). Statistics retrieval can be forced using force parameter.

Parameter Type Description
force boolean If true, retrieves the data even if the data is not too old.

default.rsrqFromRaw(raw)

Returns converted raw RSRQ to dB/dBm following standard dlms specfication.

default.rsrpFromRaw(raw)

Returns converted raw RSRQ to dB/dBm following standard dlms specfication.

default.setClock()

Checks drift and synchronizes device time.

default.signalQualityFromRaw(raw)

Converts raw CSQ value to dBm following DLMS specification.

Parameter Type Description
raw number Raw signal quality value (0-31).

default.strategy(b1, b0)

Decodes the communication strategy from two bits.

Parameter Type Description
b1 number First bit.
b0 number Second bit.

Return a string with composed strategy.

default.tauInSecondsFromRaw(raw)

Decodes TAU timer to seconds following DLMS specification.

Parameter Type Description
`raw" number 8-bit timer value.

Example:

var s = dlms_gas.manufacturer.function("tauInSecondsFromRaw")(0x21);

default.tmrInSecondsFromRaw(raw)

Decodes raw TMR to seconds following dlms specfication.

Parameter Type Description
`raw" number 8-bit timer value.

default.valveManagement(op)

Valve managment operation logic. Executes valve Open/Close commands and process the operation response.

Property Type Default Description
op Object Operation request object.

dlms_gas.pietro object Properties

There are no specific properties for dlms_gas.pietro.

dlms_gas.pietro object Functions

pietro.decodeFw(fwBytes)

Specific firmware decoding for Pietro devices. It returns a simplified version string.

dlms_gas.honeywell object Properties

Property Type Value Description
conformance string ['GENERAL_PROTECTION', 'SELECTIVE_ACCESS'] Used to define dlms.conformance when initializing client
ignoreSystemTitleInCiphering boolean false Used to define dlms.ignoreSystemTitleInCiphering when initializing client

dlms_gas.honeywell object Functions

honeywell.closeConnection()

Graceful disconnect via DLMS method specific for Honeywell devices.

honeywell.retrieveStatistics(force)

Specific statistics retrieval for Honeywell devices, excluding some attributes not supported by these devices.

honeywell.tauInSecondsFromRaw(raw)

Overrides the default TAU conversion to return directlty the raw value.

honeywell.tmrInSecondsFromRaw(raw)

Overrides the default TMR conversion to return directlty the raw value.

honeywell.eventScheduleArray(scheduleData)

Event DLMS schedule array generation logic. Generates the event schedule array for push events configuration. Adds just the events not disabledwith corresponding periodicity and hour specification.

Parameter Type Description
scheduleData Object Object with event’s day periodicty value and hour specification value from operation paraemeters.

Returns an array of objects with date and time octet. Example:

[
  {
    "dateOctet": "[-1, -1, -1, 3, -40]",
    "timeOctet": "[0, 5, 0, 0]"
  },
  {
    "dateOctet": "[-1, -1, -1, 3, -40]",
    "timeOctet": "[3, 5, 0, 0]"
  }
]

dlms_gas.spark object Properties

Property Type Value Description
forceSetWithoutList boolean true Used to define dlms.forceSetWithoutList when initializing client
eclAttribute number 253 Attribute ID for ECL retrieval.

dlms_gas.spark object Functions

spark.fotaImgVerify(op)

Invokes FOTA image verify DLMS method. It updates the operation status accordingly to the response

Property Type Default Description
op Object Operation request object.

spark.fotaCalculateIdentifier(op)

Calculates the unique image identifier based on KDL, hashtag, and activation date.

Parameter Type Description
op Object Object returned by operation api.

Returns an object with following properties:

Property Type Description
result Array<number> Array with the calculated image identifier.
error string Error message.

Example:

{
  "result": "[14, 50, 145, 16, 132, 16, 233, 67, 18, 99, 235, 189,...]"
}

dlms_gas.watertech object Properties

Property Type Value Description
conformance string ['GENERAL_PROTECTION', 'SELECTIVE_ACCESS'] Used to define dlms.conformance when initializing client
ignoreSystemTitleInCiphering boolean false Used to define dlms.ignoreSystemTitleInCiphering when initializing client

dlms_gas.watertech object Functions

There are no specific properties for dlms_gas.watertech.

IEC102 JavaScript API

Connector functions IEC102 JS API guide

This API allows users to execute operations in the IEC102 client from a connector function.

iec102 Object

The iec object is the main object of the IEC102 client. It allows to connect to communicate with devices using IEC102 protocol.

Establish connection

iec102.connect(registerType)

There is a connect method used to establish the connection with the device. When this method is called, it internally completes several actions:

  • Depending on the registerType parameter (IP, VPN, GSM, ATR), not only will the connection be made, but it may also be necessary to send some commands to establish the connection correctly. If not defined, the IP registration type will be used.
  • Once connection and registration is completed, connection status datapoints will be collected:
    • If ATR or GSM connection types are used, device.communicationModules[].subscription.mobile.presence.gsm with OK or NOK status.
  • In case of error, response status will be set to ERROR_PROCESSING and obtained error description will be added.

After connect method call, returned status must be checked to know if it is possible to continue. If not, response object should be returned.

Connection example:

iec102.ip="127.0.0.1";
iec102.port="3000";
iec102.linkAddress="1";
iec102.useMeasurePoint="1";
iec102.usePasswordAccess="1";

iec102.source="DEVICE_GSM_DATACALL";
iec102.sourcesInfo="Accessing Register through GSM data call to Device";

iec102.msisdn = "123412341324";
iec102.userName = "userName";
iec102.password = "password";
iec102.portConfig = "portConfig";

var connectionStatus = iec102.connect("GSM");
if(!connectionStatus.connected) {
    /* Connection not established. 
    At this point response object is fulfilled 
    with error code and description and skipped steps. 
    */
    return response;
}

In previous example, in case of error, there will be an implicit data collection with some data similar to this:

{
    "datastreams": [
        {
            "id": "device.communicationModules[].subscription.mobile.presence.gsm",
            "datapoints": [
                {
                    "value": "NOK",
                    "at": 1698793200000,
                    "source": "DEVICE_GSM_DATACALL",
                    "sourceInfo": "Accessing Register through GSM data call to Device"
                }
            ]
        }
    ]
}

And the response will be something similar to this:

{
    "version": "8.0",
    "trustedBoot": null,
    "operation": {
        "response": {
            "id": "request_id",
            "name": "GET_METER_INFO",
            "deviceId": "device_id",
            "resultCode": "ERROR_PROCESSING",
            "resultDescription": "Called meter responded an ERROR",
            "steps": [
                {
                    "name": "timeRequest",
                    "result": "SKIPPED",
                    "description": "Unable to make a data call"
                }
            ],
            "timestamp": 1698793200000
        }
    }
}

ASDUs definition and execution.

Once the connection is established, it is possible to execute the desired ASDUs. There are three ways to execute ASDUs:

  1. Execute directly one ASDU.
  2. Define one by one all iec102.asdus and then execute.
  3. Define iec102.asdus to be executed from operation params and then execute.

ASDUs execution behavior specification

Each ASDU to be executed must be defined with some extra params to specify correctly its behavior. For this configuration a JSON object will be used:

Field Type Description
period json Depending on the ASDU, it is necessary to specify a PERIOD
sleepTimeBeforeExec number Wait time in milliseconds before ASDU is executed. If not defined or 0 value, no wait will be done.
step json Specify if related step must added and sent to response object. If not defined, no step will be added to response object
collection json Specify if related collection must added and sent to collection object. If not defined, no datastream will be added to collection object. If defined, default datastreams will be added.

period format:

Field Type Description
initial number Initial instant of the period in milliseconds
final boolean Final instant of the period in milliseconds
type string Period type. This type can be one of: previousQuarter, previousDay, previousWeek, previousMonth, custom, lastMinutes, lastHours, lastDays

There are several utils methods to calculate this period. See date utils

step format:

Field Type Description
name string Step’s name, if not defined default step will be added.
sent boolean If added step must be sent directly after ASDU execution

collection format:

Field Type Description
sent boolean If added datastreams must be sent directly after ASDU execution

An example of ASDU execution configuration:

{
    "period": {
        "initial": 1698840000000,
        "final": 1698840899000,
        "type": "previousQuarter"
    }, 
    "sleepTimeBeforeExec": 1000,
    "step": {
        "name": "custom_name",
        "send": true
    },
    "step": {
        "send": true
    }
}

ASDUs direct execution

iec102.asdus.timeRequest()

It is possible to execute one asdu directly. For example:

var asduResult = iec102.asdus.timeRequest();

Execution result will be an object with following parameters:

Returned value will have following format:

Parameter Type Description
status boolean true if ASDU finished correctly.
description string Descriptive message with execution result
readingState string Parameter used to communicate all iec102.asdus execution status
data object Json with ASDU execution result data. Each ASDU will have specific data

In the previous example, the result could be:

{
    "status": false,
    "description": "Success",
    "readingState": "READ",
    "data":{
        "Datetime": {
            "date": "2023-11-01",
            "time": "12:00:00",
            "timezone": "GMT+1",
            "dst": 0
        }
    }
}

In this case, response steps and collected data must defined and sent manually. For example:

var asduResult = iec102.asdus.timeRequest();
if(asduResult.result){
    response.addStep("TIME_REQUEST", "SUCCESSFUL", asduResult.description);
    response.send();
    collection.addDatapoint("device.clock", asduResult.data.Datetime);
    collection.send();
}

An alternative to previous code:

var execConfig = {
    "step": {
        "sent": true
    },
    "collection": {
        "sent": true
    }
}
var asduResult = iec102.asdus.timeRequest(execConfig);

ASDUs definition from operations parameters

If launched operation has specific parameters and steps, it will be possible to calculate ASDUs from these parameters using iec102.asdus.addFromParams().

Expected parameters are:

  • Booleans with following names to know which iec102.asdus to execute.
    • doTimeRequest
    • doParameters
    • doDeviceAndManufacturer
    • doLoadCurveAbsolut
    • doLoadCurveIncremental
    • doStoredPricing
    • doConfiguration
    • doCurrentPricing
  • dataPeriod.period[0].tipo that is a string with one of following values:
    • previousQuarter
    • previousDay
    • previousWeek
    • previousMonth
    • custom
  • If dataPeriod is custom, following parameters must be defined with dates ISO string:
    • dataPeriod.period[0].parameters[0].startDate
    • dataPeriod.period[0].parameters[0].finishDate

If operation params do not match previous content, no ASDUs will be calculated.

Taking previous operation parameters specification and taking entities datastreams status into account, ASDUS to be executed will be calculated based on some predefined conditions to avoid losing data and avoid unnecessary retries.

By default, login and logout ASDUs will be added to the list.

An example of thi method usage:

/*
    Operation params:
    {
      "doTimeRequest": true,
      "doParameters": true,
      "doDeviceAndManufacturer": false,
      "doLoadCurveAbsolut": false,
      "doLoadCurveIncremental": false,
      "doStoredPricing": false,
      "doConfiguration": false,
      "doCurrentPricing": false,
      "dataPeriod": {
        "period": [
            "tipo": previousQuarter
        ]
      }
    }
*/

iec102.asdus.addFromParams();
var executionResult = iec102.asdus.execute();

/*
    iec102.asdus to be executed:
    [
        {
            "name": "login"
        },{
            "name": "timeRequest",
            "execConfig": {
                "period":{
                    "initial": 1698840000000,
                    "final": 1698840899000,
                    "type": "previousQuarter"
                },
                "sleepTimeBeforeExec": 5000
                "step": {
                    "send": true
                },
                "collection": {
                    "sent": true
                }
            }
        },{
            "name": "parameters",
            "execConfig": {
                "period":{
                    "initial": 1698840000000,
                    "final": 1698840899000,
                    "type": "previousQuarter"
                },
                "sleepTimeBeforeExec": 5000
                "step": {
                    "send": true
                },
                "collection": {
                    "sent": true
                }
            }
        },{
            "name": "logout",
            "execConfig": {
                "sleepTimeBeforeExec": 5000
            }
        }
    ]
*/

In this case, when executing all ASDUS, depending on executed ASDU, default steps could be sent directly and default collection could be done.

As explained, this method implements default behavior for ASDUs executions. If this behaviour is no valid, ASDUs to be executed must be defined manually. See ASDUs manual definition.

ASDUs manual definition:

iec102.asdus.add(name, execConfig)

It is possible to add manually using iec102.asdus.add method. This method expect following parameters to define ASDU execution correctly:

  • name: ASDU to be executed name. One of:
    • login
    • logout
    • dayLightSavingTime
    • timeRequest
    • parameters
    • deviceManufacturer
    • loadCurve
    • loadCurveQuarter
    • loadCurveIncremental
    • loadCurveIncrementalQuarter
    • storedPricing
    • currentPricing
    • configuration
  • execConfig: Json defined ASDU execution configuration

For example to define ’timeRequest’ ASDU this call must be done:

var execConfig = {
    "period":{
        "initial": 1698840000000,
        "final": 1698840899000,
        "type": "previousQuarter"
    },
    "sleepTimeBeforeExec": 5000
    "step": {
        "send": true
    },
    "collection": {
        "sent": true
    }
}
iec102.asdus.add("timeRequest", execConfig);

Previous code will add to asdus.asdusToExec array following object:

{
    "name": "timeRequest",
    "execConfig": {
            "period":{
                "initial": 1698840000000,
                "final": 1698840899000,
                "type": "previousQuarter"
            },
            "sleepTimeBeforeExec": 5000,
            "step": {
                "send": true
            },
            "collection": {
                "sent": true
            }
        }
}

In this case, after executing this ASDU default step will be sent with execution result and default datastream will be collected:

// Step to be sent
{
    "version": "8.0",
    "trustedBoot": null,
    "operation": {
        "response": {
            "steps": [
                {
                    "name": "TIME_REQUEST",
                    "result": "SUCCESS",
                    "description": "Success."
                }
            ],
        }
    }
}
// Collection to be sent
{
    "datastreams": [
        "id": "device.clock",
        "datapoints":[
            {
                "value": {
                    "date": "2023-11-01",
                    "time": "12:00:00",
                    "timezone": "GMT+1",
                    "dst": 0
                },
                "at": 1698793200000
            }
        ]
    ]
}

Defined ASDUs execution

If ASDUs are not executed one by one, but they are added from operation params or defining them one by one, iec102.asdus.execute() method must be used to execute all defined ASDUs.

iec102.asdus.execute() method will execute all added ASDUs one by one, and depending ASDU specification related steps and collection will be send.

For example, first we define manually following ASDUs and then we do execution:

var period = utils.date.period.previousQuarter(iec102.referenceTime); 

iec102.asdus.add("login");

iec102.asdus.add("loadCurveIncremental", {
    "period": period,
    "sleepTimeBeforeExec": 1000,
    "step": {
        "sent": true,
    },
    "collection":{
        "sent": false
    }
});

iec102.asdus.add("loadCurve", 
    "period": period,
    "sleepTimeBeforeExec": 1000,
    "step": {
        "name": "CUSTOM_LOAD_CURVE_STEP",
        "sent": false,
    }
});

iec102.asdus.add("logout",{
    "sleepTimeBeforeExec": 1000
});

var executionResult = iec102.asdus.execute();

/* ASDUs to be executed
[
    {
        "name": "login"
    },{
        "name": "timeRequest",
        "execConfig": {
                "sleepTimeBeforeExec": 1000
                "step": {
                    "send": true
                },
                "collection": {
                    "sent": true
                }
            }
    },{
        "name": "loadCurve",
        "execConfig": {
                "period":{
                    "initial": 1698840000000,
                    "final": 1698840899000
                },
                "sleepTimeBeforeExec": 1000
                "step": {
                    "name": "CUSTOM_LOAD_CURVE_STEP",
                    "send": false
                }
            }
    },{
        "name": "logout",
        "execConfig": {
            "sleepTimeBeforeExec": 5000 
        }
    }
]
*/

In this example, we will suppose that timeRequest ASDU finish correctly:

  1. First, login ASDU will be executed. After execution, no step or collection will be sent.

  2. Before executing timeRequest, 1000 milliseconds wait will be done.

  3. After timeRequest execution, default TIME_REQUEST step will be added because no name has been specified and it will be sent because step.send has been defined to true. This is the step to be sent directly:

    {
        "operation": {
            "response" :{
                //...
                "steps": [
                    {
                        "name": "TIME_REQUEST",
                        "result": "SUCCESSFUL",
                        "description": "Step completed successfully"
                    }
                ]
                //...
            }
        }
    }
  1. After timeRequest execution, following datastream will be added to collection object because collection is defined and it will be sent directly because collection.send is true. Datastream to be collected:
{
    "datastreams": [
        {
            "id": "device.clock",
            "datapoints":[
                {
                    "value": {
                        "date": "2023-11-01",
                        "time": "12:00:00",
                        "timezone": "GMT+1",
                        "dst": 0
                    },
                    "at": 1698793200000
                }
            ]
        }
    ]
}
  1. Before executing loadCurve, 1000 milliseconds wait will be done.

  2. After loadCurve execution, instead of adding default STEP_NAME_LOAD_CURVE_ABSOLUT step, a step with name CUSTOM_LOAD_CURVE_STEP will be added because name parameter has been specified. In this case, the step will be added to response, but not sent send has been defined to false. This is the step added to response object:

    {
        "operation": {
            "response" :{
                //...
                "steps": [
                    {
                        "name": "CUSTOM_LOAD_CURVE_STEP",
                        "result": "SUCCESSFUL",
                        "description": "Step completed successfully"
                    }
                ]
                //...
            }
        }
    }
  1. After loadCurve execution no datastream will be added to collection object because no collection field has been defined in execConfig.

  2. Finally, after 1000 milliseconds wait logout ASDU will be executed.

  3. Final executionResult will contain all ASDUs execution result.

Returned value will have following format:

Parameter Type Description
status boolean true if all ASDUs finished correctly.
iec102.asdus object Json with each ASDU execution result object.

Execution result could be something similar to this

{
    "status": false,
    "asdus": {
        "login": {
            "status": true,
            "description": "Success"
            "readingState": null,
        },
        "timeRequest": {
            "status": true,
            "description": "Success",
            "readingState": "READ",
            "data":{
                "Datetime": {
                    "date": "2023-11-01",
                    "time": "12:00:00",
                    "timezone": "GMT+1",
                    "dst": 0
                }
            }
        },
        "loadCurve": {
            "status": true,
            "description": "Success",
            "readingState": "READ",
            "data":{
                "frames": [
                    {
                        "ImportedActive": 10,
                        "Quadrant4Reactive": 10,
                        "Quadrant2Reactive": 333,
                        "Quadrant3Reactive": 334,
                        "ExportedActive": 1000,
                        "Quadrant1Reactive": 333,
                        "Timestamp": 1705536000000
                    }
                ]
            }
        },
        "logout": {
            "status": false,
            "description": "Error in logout"
            "readingState": null,
        }
    }
}

Although, login, timeRequest, and loadCurve finished correctly, because logout ASDU failed, status is failed. timeRequest, loadCurve ASDUs finished correctly and returns obtained data. Returned data depends on each ASDU.

Default steps for ASDUs

These are defined default steps for each ASDU:

ASDU STEP
login
logout
timeRequest TIME_REQUEST
configuration CONFIGURATION
parameters PARAMETERS
dayLightSavingTime
loadCurve LOAD_CURVE_ABSOLUT
loadCurveQuarter LOAD_CURVE_ABSOLUT
loadCurveIncremental LOAD_CURVE_INCREMENTAL
loadCurveIncrementalQuarter LOAD_CURVE_INCREMENTAL
deviceManufacturer DEVICE_AND_MANUFACTURER
currentPricing CURRENT_PRICING
storedPricing STORED_PRICING

Default datastreams for ASDUs

ASDU Field Datastream
login
logout
timeRequest DateTime device.clock
configuration ManufacturerCode manufacturerCode
configuration Model device.model
configuration Firmware device.software
configuration SerialNumber device.serialNumber
configuration StandardDate protocolRevDate
configuration Datetime protocolDate
configuration BatteryPercentage device.powersupply
configuration SerialPort1Baudrate serialPort1Speed
configuration SerialPort1Codification serialPort1Conf
configuration SerialPort1Mode serialPort1ShipMode
configuration SerialPort1StartingAsciiString serialPort1AsciiString
configuration SerialPort2Baudrate serialPort2Speed
configuration SerialPort2Codification serialPort2Conf
configuration VoltagePrimary voltPrim
configuration VoltageSecondary voltSec
configuration IntensityPrimary intenPrim
configuration IntensitySecondary intenSec
configuration IntegrationPeriod1 IntPerLoadCurve1
configuration IntegrationPeriod2 IntPerLoadCurve2
configuration IntegrationPeriod3 IntPerLoadCurve3
configuration ContractType contractType
configuration Contract1 contractState
parameters LinkAddressCollected elinkAddress
parameters MeasurePointsQuantity measurePointsQuantity
parameters MeasurePoint measurePoint
parameters AccessPassword accessPass
parameters IntegrationPeriod intPeriod
parameters RegistryDepth regDepth
deviceManufacturer ManufacturerCode manufacturerCode
deviceManufacturer DeviceId contIdentifier
dayLightSavingTime ToDaylightSavingTime
dayLightSavingTime ToStandardTime
loadCurve Timestamp
loadCurve ImportedActive eImpActTotDia
loadCurve ExportedActive eExpActTotDia
loadCurve Quadrant1Reactive eImpReQ1TotDia
loadCurve Quadrant2Reactive eImpReQ2TotDia
loadCurve Quadrant3Reactive eImpReQ3TotDia
loadCurve Quadrant4Reactive eImpReQ4TotDia
loadCurveQuarter frames[].Timestamp
loadCurveQuarter frames[].ImportedActive eImpActTot
loadCurveQuarter frames[].ExportedActive eExpActTot
loadCurveQuarter frames[].Quadrant1Reactive eImpReQ1Tot
loadCurveQuarter frames[].Quadrant2Reactive eImpReQ2Tot
loadCurveQuarter frames[].Quadrant3Reactive eImpReQ3Tot
loadCurveQuarter frames[].Quadrant4Reactive eImpReQ4Tot
loadCurveIncremental frames[].Timestamp
loadCurveIncremental frames[].ImportedActive eImpActIncDia
loadCurveIncremental frames[].ExportedActive eExpActIncDia
loadCurveIncremental frames[].Quadrant1Reactive eImpReQ1IncDia
loadCurveIncremental frames[].Quadrant2Reactive eImpReQ2IncDia
loadCurveIncremental frames[].Quadrant3Reactive eImpReQ3IncDia
loadCurveIncremental frames[].Quadrant4Reactive eImpReQ4IncDia
loadCurveIncrementalQuarter frames[].Timestamp
loadCurveIncrementalQuarter frames[].ImportedActive eImpActInc
loadCurveIncrementalQuarter frames[].ExportedActive eExpActInc
loadCurveIncrementalQuarter frames[].Quadrant1Reactive eImpReQ1Inc
loadCurveIncrementalQuarter frames[].Quadrant2Reactive eImpReQ2Inc
loadCurveIncrementalQuarter frames[].Quadrant3Reactive eImpReQ3Inc
loadCurveIncrementalQuarter frames[].Quadrant4Reactive eImpReQ4Inc
currentPricing frames[].Timestamp
currentPricing frames[].RateIndex ({ri})
currentPricing frames[].Memory ({m})
currentPricing frames[].AbsoluteActive eRate{ri}ActTot{m}
currentPricing frames[].IncrementalActive eRate{ri}ActInc{m}
currentPricing frames[].AbsoluteInductiveReactive eRate{ri}ReIndTot{m}
currentPricing frames[].IncrementalInductiveReactive eRate{ri}ReIndInc{m}
currentPricing frames[].AbsoluteCapacitiveReactive eRate{ri}ReCapTot{m}
currentPricing frames[].IncrementalCapacitiveReactive eRate{ri}ReCapInc{m}
currentPricing frames[].MaximumPower eRate{ri}PowerMaxVal{m}
currentPricing frames[].ExcessPower eRate{ri}PowerExVal{m}
currentPricing frames[].InitPeriodDateAsDatetime eRate{ri}PricInitPeri{m}
currentPricing frames[].EndPeriodDateAsDatetime eRate{ri}PricEndPeri{m}
storedPricing frames[].Timestamp
storedPricing frames[].RateIndex ({ri})
storedPricing frames[].Memory ({m})
storedPricing frames[].AbsoluteActive eRate{ri}ActTot{m}
storedPricing frames[].IncrementalActive eRate{ri}ActInc{m}
storedPricing frames[].AbsoluteInductiveReactive eRate{ri}ReIndTot{m}
storedPricing frames[].IncrementalInductiveReactive eRate{ri}ReIndInc{m}
storedPricing frames[].AbsoluteCapacitiveReactive eRate{ri}ReCapTot{m}
storedPricing frames[].IncrementalCapacitiveReactive eRate{ri}ReCapInc{m}
storedPricing frames[].MaximumPower eRate{ri}PowerMaxVal{m}
storedPricing frames[].ExcessPower eRate{ri}PowerExVal{m}
storedPricing frames[].InitPeriodDateAsDatetime eRate{ri}PricInitPeri{m}
storedPricing frames[].EndPeriodDateAsDatetime eRate{ri}PricEndPeri{m}

iec102 Object Properties

Property Type Default Description
ip string IP address to connect.
port number Port to connect
isTls boolean false Specifies if secure protocol must be used
retries number 5 Number of retries.
timeout number 30000 Timeout in milliseconds.
linkAddress number Mandatory parameter used as part of IEC102 protocol
useMeasurePoint number Mandatory parameter used as part of IEC102 protocol
usePasswordAccess number Mandatory parameter used as part of IEC102 protocol
msisdn string Parameter used when connection is done with a data call through some caller
userName string Parameter used when connection is done with a data call through some caller
password string Parameter used when connection is done with a data call through some caller
referenceTime number Current It will be used as reference time for period calculation and as datapoints ‘at’ value
readingState string Current Internally used parameter to keep ASDUs execution status
portConfig string Parameter used when connection is done with a data call through some caller
source string It will be used as datapoints ‘source’ value
sourcesInfo string It will be used as datapoints ‘sourcesInfo’ value
manufacturerCodeName object Manufacturer code->name map
asdus.asdusToExec array Internal array with the list of ASDUs to be executed. It must be initialized before connecting

iec102 Object Methods

connect (registerType, waitFor) ⇒ Object

Establish connection with specified device. Before using this method connection parameters such as ip, port, timeout, etc. must be specified (some of them can have default values).

See Establish connection

Parameter Type Description
registerType string Specify connection procedure.
waitFor array Strings to wait for in the response.

This method will return an object with following format:

{
    "status": true,
    "description": "Success"
}

connectWithIpAndPorts (ports, waitFor) ⇒ Object

Establish connection with specified device trying different ports. Before using this method connection parameters such as ip, timeout, etc. must be specified (some of them can have default values). In this case, a list of ports will be passed as parameters. For each port of the list, the connect method will be called until the connection is established correctly.

See Establish connection

Parameter Type Description
ports array List of ports to be used
waitFor array Strings to wait for in the response.

This method will return an object with following format:

{
    "status": true,
    "description": "Success"
}

connectWithEndpoints (endpoints) ⇒ Object

This method is special case for GSM connection.

Establish connection with specified device trying different endpoints. Each endpoint is an object with following information:

  • ip
  • port
  • userName
  • password

For example:

var endpoints = [
    {
        "ip": "127.0.0.1",
        "port": "3000",
        "userName": "userName",
        "password": "password"
    },
    {
        "ip": "127.0.0.2",
        "port": "3001",
        "userName": "userName2",
        "password": "password2"
    }
];
iec102.connectWithEndpoints(endpoints);

In this case, GSM register type will be used.

See Establish connection

Parameter Type Description
endpoints array List of objects with endpoints spec

This method will return an object with following format:

{
    "status": true,
    "description": "Success"
}

disconnect ()

Closes IEC102 connection

send (command, waitFor, pattern) ⇒ Object

Sends a command.

Parameter Type Description
command string Command to send.
waitFor List Strings to wait for in the response.
pattern string Pattern to extract response from sent command.

Returns a json with status and description properties:

{
    "status": true,
    "description": "Success"
}

iec102.asdus.add(name, execConfig)

Define an ASDU to be executed and add to asdus.asdusToExec array.

See ASDUs Definition and Execution

Parameter Type Description
name string ASDU name
execConfig object Execution configuration

iec102.asdus.addFromParameters()

Calculates all ASDUs to be executed from operations parameters adding them to asdus.asdusToExec array. This method only works if parameters object has specific properties.

See ASDUs Definition and Execution

iec102.asdus.login(execConfig)

Execute directly login ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": null,
}

iec102.asdus.logout(execConfig)

Execute directly logout ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": null,
}

iec102.asdus.timeRequest(execConfig)

Execute directly timeRequest ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "Datetime": {
            "date": "2024-01-19",
            "time": "09:36:58",
            "timezone": "GMT+1",
            "dst": 0
        }
    }
}

data object will contain data retrieved from executed ASDU.

iec102.asdus.configuration(execConfig)

Execute directly configuration ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "Contract1": "unknown",
        "VoltageSecondary": 0,
        "ManufacturerCode": "1",
        "BatteryPercentage": 44,
        "SerialPort1StartingAsciiString": "\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000",
        "IntensityPrimary": 0,
        "IntegrationPeriod3": 0,
        "VoltagePrimary": 0,
        "IntegrationPeriod1": 60,
        "IntegrationPeriod2": 15,
        "SerialPort1Mode": 0,
        "IntensitySecondary": 0,
        "SerialNumber": 333,
        "Model": {
            "name": "AQ",
            "version": "",
            "manufacturer": "",
            "manufacturerOUI": ""
        },
        "SerialPort1Codification": "8/No/2",
        "ContractType": "Contract I",
        "StandardDate": "2002-05-01",
        "Firmware": [
            {
                "name": "Firmware version",
                "version": "2",
                "type": "FIRMWARE"
            }
        ],
        "SerialPort1Baudrate": 9600,
        "SerialPort2Baudrate": 0,
        "SerialPort2Codification": "8/No/2",
        "Datetime": {
            "date": "2002-04-10",
            "time": "00:00:00",
            "timezone": "GMT+1",
            "dst": 0
        }
    }
}

data object will contain data retrieved from executed ASDU.

iec102.asdus.parameters(execConfig)

Execute directly parameters ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "RegistryDepth": 4000,
        "LinkAddressCollected": 1,
        "IntegrationPeriod": 60,
        "AccessPassword": 1,
        "MeasurePoint": 1,
        "MeasurePointsQuantity": 1
    }
}

data object will contain data retrieved from executed ASDU.

iec102.asdus.deviceManufacturer(execConfig)

Execute directly deviceManufacturer ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "ManufacturerCode": "81",
        "DeviceId": "501606407"
    }
}

data object will contain data retrieved from executed ASDU.

iec102.asdus.dayLightSavingTime(execConfig)

Execute directly dayLightSavingTime ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "ToDaylightSavingTime": {
            "date": "2002-04-10",
            "time": "00:00:00",
            "timezone": "GMT+1",
            "dst": 0
        },
        "ToStandardTime": {
            "date": "2002-04-10",
            "time": "00:00:00",
            "timezone": "GMT+1",
            "dst": 0
        }      
    }
}

data object will contain data retrieved from executed ASDU.

iec102.asdus.loadCurve(execConfig)

Execute directly loadCurve ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "ImportedActive": 10,
                "Quadrant4Reactive": 10,
                "Quadrant2Reactive": 333,
                "Quadrant3Reactive": 334,
                "ExportedActive": 1000,
                "Quadrant1Reactive": 333,
                "Timestamp": 1705536000000
            },
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.loadCurveQuarter(execConfig)

Execute directly loadCurveQuarter ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "ImportedActive": 10,
                "Quadrant4Reactive": 10,
                "Quadrant2Reactive": 333,
                "Quadrant3Reactive": 334,
                "ExportedActive": 1000,
                "Quadrant1Reactive": 333,
                "Timestamp": 1705536000000
            },
            {
                "ImportedActive": 0,
                "Quadrant4Reactive": 125,
                "Quadrant2Reactive": 125,
                "Quadrant3Reactive": 125,
                "ExportedActive": 500,
                "Quadrant1Reactive": 125,
                "Timestamp": 1705536900000
            }
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.loadCurveIncremental(execConfig)

Execute directly loadCurveIncremental ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "ImportedActive": 10,
                "Quadrant4Reactive": 10,
                "Quadrant2Reactive": 333,
                "Quadrant3Reactive": 334,
                "ExportedActive": 1000,
                "Quadrant1Reactive": 333,
                "Timestamp": 1705536000000
            }
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.loadCurveIncrementalQuarter(execConfig)

Execute directly loadCurveIncrementalQuarter ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "ImportedActive": 2,
                "Quadrant4Reactive": 0,
                "Quadrant2Reactive": 1,
                "Quadrant3Reactive": 1,
                "ExportedActive": 1,
                "Quadrant1Reactive": 2,
                "Timestamp": 1705536000000
            },
            {
                "ImportedActive": 0,
                "Quadrant4Reactive": 0,
                "Quadrant2Reactive": 0,
                "Quadrant3Reactive": 0,
                "ExportedActive": 2,
                "Quadrant1Reactive": 0,
                "Timestamp": 1705536900000
            }
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.currentPricing(execConfig)

Execute directly currentPricing ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "IncrementalActive": 5060,
                "IncrementalCapacitiveReactive": 54,
                "Memory": "Cur",
                "AbsoluteCapacitiveReactive": 4564,
                "Timestamp": 1705653489884,
                "MaximumPower": 19,
                "EndPeriodDateAsDatetime": {
                    "date": "2024-02-29",
                    "time": "23:59:00",
                    "timezone": "GMT+1",
                    "dst": 0
                },
                "RateIndex": "Tot",
                "InitPeriodDateAsDatetime": {
                    "date": "2024-02-01",
                    "time": "00:00:00",
                    "timezone": "GMT+1",
                    "dst": 0
                },
                "ExcessPower": 0,
                "AbsoluteActive": 595452,
                "AbsoluteInductiveReactive": 1207,
                "IncrementalInductiveReactive": 6
            },
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.storedPricing(execConfig)

Execute directly storedPricing ASDU.

See ASDUs Definition and Execution

Parameter Type Description
execConfig object Execution configuration

Return a json with following format:

{
    "status": true,
    "description": "Success",
    "readingState": "READ",
    "data": {
        "frames": [
            {
                "IncrementalActive": 5060,
                "IncrementalCapacitiveReactive": 54,
                "Memory": "Mem",
                "AbsoluteCapacitiveReactive": 4564,
                "Timestamp": 1705653478357,
                "MaximumPower": 19,
                "EndPeriodDateAsDatetime": {
                    "date": "2024-02-29",
                    "time": "23:59:00",
                    "timezone": "GMT+1",
                    "dst": 0
                },
                "RateIndex": "Tot",
                "InitPeriodDateAsDatetime": {
                    "date": "2024-02-01",
                    "time": "00:00:00",
                    "timezone": "GMT+1",
                    "dst": 0
                },
                "ExcessPower": 0,
                "AbsoluteActive": 595452,
                "AbsoluteInductiveReactive": 1207,
                "IncrementalInductiveReactive": 6
            }
            //...
        ]
    }
}

data object will contain a field named frames that is an array. Each array element is an object with the data retrieved.

iec102.asdus.execute()

Execute one by one all the ASDUs defined in asdus.asdusToExec.

See ASDUs Definition and Execution

Returns an object with following format:

{
    "status": true,
    "asdus": {
        "login": {
            "data": null,
            "description": "Success",
            "readingState": null,
            "status": true
        },
        "timeRequest": {
            "data": {
                "Datetime": {
                    "date": "2024-01-19",
                    "time": "09:36:58",
                    "timezone": "GMT+1",
                    "dst": 0
                }
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "parameters": {
            "data": {
                "RegistryDepth": 4000,
                "LinkAddressCollected": 1,
                "IntegrationPeriod": 60,
                "AccessPassword": 1,
                "MeasurePoint": 1,
                "MeasurePointsQuantity": 1
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "deviceManufacturer": {
            "data": {
                "ManufacturerCode": "81",
                "DeviceId": "501606407"
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "loadCurve": {
            "data": {
                "frames": [
                    {
                        "ImportedActive": 10,
                        "Quadrant4Reactive": 10,
                        "Quadrant2Reactive": 333,
                        "Quadrant3Reactive": 334,
                        "ExportedActive": 1000,
                        "Quadrant1Reactive": 333,
                        "Timestamp": 1705536000000
                    }
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "loadCurveQuarter": {
            "data": {
                "frames": [
                    {
                        "ImportedActive": 10,
                        "Quadrant4Reactive": 10,
                        "Quadrant2Reactive": 333,
                        "Quadrant3Reactive": 334,
                        "ExportedActive": 1000,
                        "Quadrant1Reactive": 333,
                        "Timestamp": 1705536000000
                    }
                    //...
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "loadCurveIncremental": {
            "data": {
                "frames": [
                    {
                        "ImportedActive": 10,
                        "Quadrant4Reactive": 10,
                        "Quadrant2Reactive": 333,
                        "Quadrant3Reactive": 334,
                        "ExportedActive": 1000,
                        "Quadrant1Reactive": 333,
                        "Timestamp": 1705536000000
                    }
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "loadCurveIncrementalQuarter": {
            "data": {
                "frames": [
                    {
                        "ImportedActive": 2,
                        "Quadrant4Reactive": 0,
                        "Quadrant2Reactive": 1,
                        "Quadrant3Reactive": 1,
                        "ExportedActive": 1,
                        "Quadrant1Reactive": 2,
                        "Timestamp": 1705536000000
                    }
                    //...
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "storedPricing": {
            "data": {
                "frames": [
                    {
                        "IncrementalActive": 5060,
                        "IncrementalCapacitiveReactive": 54,
                        "Memory": "Mem",
                        "AbsoluteCapacitiveReactive": 4564,
                        "Timestamp": 1705653478357,
                        "MaximumPower": 19,
                        "EndPeriodDateAsDatetime": {
                            "date": "2024-02-29",
                            "time": "23:59:00",
                            "timezone": "GMT+1",
                            "dst": 0
                        },
                        "RateIndex": "Tot",
                        "InitPeriodDateAsDatetime": {
                            "date": "2024-02-01",
                            "time": "00:00:00",
                            "timezone": "GMT+1",
                            "dst": 0
                        },
                        "ExcessPower": 0,
                        "AbsoluteActive": 595452,
                        "AbsoluteInductiveReactive": 1207,
                        "IncrementalInductiveReactive": 6
                    }
                    //...
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "configuration": {
            "data": {
                "Contract1": "unknown",
                "VoltageSecondary": 0,
                "ManufacturerCode": "1",
                "BatteryPercentage": 44,
                "SerialPort1StartingAsciiString": "\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000\u0000",
                "IntensityPrimary": 0,
                "IntegrationPeriod3": 0,
                "VoltagePrimary": 0,
                "IntegrationPeriod1": 60,
                "IntegrationPeriod2": 15,
                "SerialPort1Mode": 0,
                "IntensitySecondary": 0,
                "SerialNumber": 333,
                "Model": {
                    "name": "AQ",
                    "version": "",
                    "manufacturer": "",
                    "manufacturerOUI": ""
                },
                "SerialPort1Codification": "8/No/2",
                "ContractType": "Contract I",
                "StandardDate": "2002-05-01",
                "Firmware": [
                    {
                        "name": "Firmware version",
                        "version": "2",
                        "type": "FIRMWARE"
                    }
                ],
                "SerialPort1Baudrate": 9600,
                "SerialPort2Baudrate": 0,
                "SerialPort2Codification": "8/No/2",
                "Datetime": {
                    "date": "2002-04-10",
                    "time": "00:00:00",
                    "timezone": "GMT+1",
                    "dst": 0
                }
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "currentPricing": {
            "data": {
                "frames": [
                    {
                        "IncrementalActive": 5060,
                        "IncrementalCapacitiveReactive": 54,
                        "Memory": "Cur",
                        "AbsoluteCapacitiveReactive": 4564,
                        "Timestamp": 1705653489884,
                        "MaximumPower": 19,
                        "EndPeriodDateAsDatetime": {
                            "date": "2024-02-29",
                            "time": "23:59:00",
                            "timezone": "GMT+1",
                            "dst": 0
                        },
                        "RateIndex": "Tot",
                        "InitPeriodDateAsDatetime": {
                            "date": "2024-02-01",
                            "time": "00:00:00",
                            "timezone": "GMT+1",
                            "dst": 0
                        },
                        "ExcessPower": 0,
                        "AbsoluteActive": 595452,
                        "AbsoluteInductiveReactive": 1207,
                        "IncrementalInductiveReactive": 6
                    }
                    //...
                ]
            },
            "description": "Success",
            "readingState": "READ",
            "status": true
        },
        "logout": {
            "data": null,
            "description": "Success",
            "readingState": null,
            "status": true
        }
    }
}

Catalog GetMeterInfo operation example

Following code shows the catalog connector function for GetMeterInfo operation

var registerType = entityValue(entity, 'provision.type');

iec102.ip = entityValue(entity, 'provision.ip');
iec102.port = entityValue(entity, 'provision.port');

iec102.linkAddress = Number(entityValue(entity, 'provision.linkAddress'));
iec102.useMeasurePoint = Number( entityValue(entity, 'provision.measurePoint'));
iec102.usePasswordAccess = Number( entityValue(entity, 'provision.passwordAccess'));

iec102.msisdn =  entityValue(entity, 'provision.device.communicationModules[].subscription.mobile.msisdn', 0);
iec102.userName =  entityValue(entity, 'provision.user');
iec102.password =  entityValue(entity, 'provision.password');
iec102.portConfig =  entityValue(entity, 'provision.portConfig');

if (!registerType) {
    response.errorProcessing('Meter type was not specified');
    return response;
}

var connectionStatus = iec102.connect(registerType);
collection.addDatapoint('atd.response', connectionStatus.description, iec102.referenceTime, iec102.source, iec102.sourceInfo);
if (!connectionStatus.status) {
    collection.addDatapoint('readingState', iec102.readingState, iec102.referenceTime, iec102.source, iec102.sourceInfo);
    collection.send();
    return response;
}

iec102.asdus.addFromParams();
var asdusResult = iec102.asdus.execute();

iec102.disconnect();

collection.addDatapoint('readingState', iec102.readingState, iec102.referenceTime, iec102.source, iec102.sourceInfo);
collection.send();
if (asdusResult.status) {
    response.successful('Finished Correctly');
}

log('Final response: ', response);
return response;

Kite Javascript API

Connector functions Kite JS API guide

This API allows users to execute operations in the Kite connector from a connector function.

Kite Object

The Kite object is the main object of the Kite connector. It allows to connect to the Kite server and execute operations.

Kite Object Properties

Property Type Default Description
uriHost string Host of the Kite server.
uriService string Service of the Kite server.
proxyEnabled boolean false Enable proxy.
proxyHost string Host of the proxy (if the proxy is enabled).
proxyPort number Port of the proxy (if the proxy is enabled).
proxyProtocol string Protocol of the proxy (if proxy is enabled).

It should be noted that these properties will be used in all communication methods with Kite Service.

Specific datastreams to use Kite

Datastream Type Description
provision.administration.connection.kite.certificate String Certificate to communication with Kite
provision.administration.connection.kite.privateKey String Private Key to communication with Kite

These data streams can be specified:

  • To a chosen device.
  • To a chosen channel. Please use these values for all the entities in the selected channel.
  • To a chosen organization. This set of values should be used in the same way in every part of the organization.

Kite Object Methods

kite.requestChangeTerminalStatus(status)

Changes the subscription status using the specified parameter and completes the collection object with a new administrative status.

Parameter Type Description
status string Status of the subscription.

Returns an object with the following properties:

  • isOk (boolean): true if the request is ok
  • description: Result description of the operation.

This method also triggers the collection of the following data stream:

  • device.communicationModules[].subscription.administrativeState

This data stream is automatically populated after calling the method.

Example of use:

let result = kite.requestChangeTerminalStatus()
if (result.isOk) {
    collection.send()
    response.successful(result.description)
} else {
    response.errorProcessing(result.description)
}

return response

kite.requestTerminalDetails()

Gets the details of the subscription and complete collection object with result.

Returns an object with the following properties:

  • isOk (boolean): true if the request is ok
  • description: Description of the operation’s result.

This method also triggers the collection of the following data streams:

  • device.communicationModules[].mobile.imei
  • device.communicationModules[].model
  • device.communicationModules[].subscription.address
  • device.communicationModules[].subscription.administrativeState
  • device.communicationModules[].subscription.counters.totalBytesLastDay
  • device.communicationModules[].subscription.counters.totalBytesLastMonth
  • device.communicationModules[].subscription.identifier
  • device.communicationModules[].subscription.mobile.ggsn.ipAddress
  • device.communicationModules[].subscription.mobile.icc
  • device.communicationModules[].subscription.mobile.imsi
  • device.communicationModules[].subscription.mobile.msisdn
  • device.communicationModules[].subscription.mobile.ratType
  • device.communicationModules[].subscription.mobile.sgsn.countryCode
  • device.communicationModules[].subscription.mobile.sgsn.ipAddress
  • device.communicationModules[].subscription.mobile.sgsn.operatorName
  • device.communicationModules[].subscription.mobile.uli.cgi
  • entity.location

These data streams are automatically populated after calling the method.

Example of use:

let result = kite.requestTerminalDetails()
if (result.isOk) {
    collection.send()
    response.successful(result.description)
} else {
    response.errorProcessing(result.description)
}
return response

SNMP JavaScript API

Connector functions SNMP JS API guide

This JavaScript code provides predefined functions to execute SNMP requests from the connector function. They are explained below.

JS SNMP API

For REQUEST Connector Functions we will use the functions get and set described below. You have an object, named snmp, with those functions described. You must use snmp.get or snmp.set.

If you want to collect data after executing any of these function you can call collectCF and you can set various oids in the URL provided as you can see in the next example:

collectCF(result.data, "snmps://<oidValue>");

snmp.addOid()

Adds an OID to the list of OIDs to be retrieved/setted.

Param Type Description
oid string OID to add.
type string Type of the value.
value string Value to set.

Example of use:

// Example for get
snmp.addOid('1.3.6.1.4.1.2007.4.1.2.2.2.18.3.2.1.10.3');
snmp.get()

//Example for set
snmp.addOid('1.0.1.4.5.123456.1.6', 'INTEGER', '3');
snmp.set()

snmp.get()

Executes a multi SNMP get attribute request with specified payload. You must have previously given value to the properties snmp.ip, snmp.port (161 by default), snmp.community (in case of snmp version 1), snmp.version (3 by default), snmp.retries (3 by default), snmp.timeout (5000 by default) and security info in case of snmpv3 version (snmp.securityName, snmp.authentication, snmp.privacy, snmp.authPassphrase and snmp.privPassphrase). In addition, you have to add the oids you want to get using the snmp.addOid function with the oid string as many times as you want.

Kind: global function
Returns: String - A JSON with response. This JSON will have two fields: ‘result’ of the get operation and ‘data’ with response of the device.

SNMP Field Type Description
ip string IP address of the device you want to connect to.
port number Port of the device you want to connect to. By default is 161.
oids Array Array of strings with the list of wanted oids. To add items to the list, you must call the function ‘snmp.addOid’ with the oid as parameter as many times as you want oids.
community string The community octet string. This is a convenience method to set the security name for community based SNMP (v1 and v2c).
securityName string The security name of the user (typically the user name).
authentication string The authentication protocol ID to be associated with this user. If set to null, this user only supports unauthenticated messages.
authPassphrase string The authentication passphrase. If not null, authentication must also be not null.
privacy string The privacy protocol ID to be associated with this user. If set to null, this user only supports unencrypted messages.
privPassphrase string The privacy passphrase. If not null, privacy must also be not null.
version number Version number of the SNMP. By default is 3.
retries number Number of retries for the request. By default is 3.
timeout number Timeout of the request in millis. By default is 5000.

Here is an example of use for the snmp.addOid function for snmp.get:

snmp.addOid('1.3.6.1.4.1.2007.4.1.2.2.2.18.3.2.1.10.3');
snmp.addOid('1.3.6.1.4.1.2007.4.1.2.2.2.18.3.2.1.11.3');
snmp.get();

snmp.set()

Executes a multi SNMP set attribute request with specified payload. You must have previously given value to the properties snmp.ip, snmp.port (161 by default), snmp.community (in case of snmp version 1), snmp.version (3 by default), snmp.retries (3 by default), snmp.timeout (5000 by default) and security info in case of snmpv3 version (snmp.securityName, snmp.authentication, snmp.privacy, snmp.authPassphrase and snmp.privPassphrase). In addition, you have to add the oids you want to set using the snmp.addOid function with the oid string, the type of the value and the value you want to set to as many times as you want.

Kind: global function
Returns: String - A JSON with response. This JSON will have two fields: ‘result’ of the get operation and ‘data’ with response of the device. This ‘data’ contains pairs of (oid, value).

SNMP Field Type Description
ip string IP address of the device you want to connect to.
port number Port of the device you want to connect to. By default is 161.
oids Array Array of items with the list of oids you want to set. To add items to the list, you must call the function ‘snmp.addOid’ with the oid you want to set, the type of the value for that oid and the value you want to set as parameters as many times as you want oids.
community string The community octet string. This is a convenience method to set the security name for community based SNMP (v1 and v2c).
securityName string The security name of the user (typically the user name).
authentication string The authentication protocol ID to be associated with this user. If set to null, this user only supports unauthenticated messages.
authPassphrase string The authentication passphrase. If not null, authentication must also be not null.
privacy string The privacy protocol ID to be associated with this user. If set to null, this user only supports unencrypted messages.
privPassphrase string The privacy passphrase. If not null, privacy must also be not null.
version number Version number of the SNMP. By default is 3.
retries number Number of retries for the request. By default is 3.
timeout number Timeout of the request in millis. By default is 5000.

Here is an example of use for the snmp.addOid function for snmp.set:

snmp.addOid('1.0.1.4.5.123456.1.5', 'OCTET_STRING', params.variableList[0].value);
snmp.addOid('1.0.1.4.5.123456.1.6', 'INTEGER', '3');
snmp.set();

The allowed values for type are: OBJECT_IDENTIFIER, INTEGER, BIT_STRING, OCTET_STRING, GAUGE32, COUNTER32, COUNTER64, TIMETICKS, OPAQUE and IPADDRESS.

Here is a successful response example:

{
  "result": {
    "code": "SUCCESSFUL",
    "description": "Operation executed successfully"
  },
  "data": {
    "oid":"value",
    "oid1":"value1",
    ....
    "oidN":"valueN"
  }
}

And here an error response example:

{
  "result": {
    "code": "ERROR_PROCESSING",
    "description": "Error getting data"
  },
  "data": {}
}

SSH JavaScript API

Connector functions SSH JS API guide

This API allows users to execute operations in the SSH client from a connector function.

Ssh Object

The ssh object is the main object of the SSH client. It allows to connect to an SSH server, send commands and receive responses and disconnect from the SSH server.

Ssh Object Properties

Property Type Default Description
ip string IP address of the SSH server.
port number 23 Port of the SSH server.
retries number 3 Number of retries.
timeout number 5000 Timeout in milliseconds.
user string SSH user.
password string SSH password.
identity string Rsa key content.

Ssh Object Methods

ssh.connect(waitFor)

Establish a connection with the SSH server.

Property Type Default Description
waitFor List Strings to wait for in the response.

Connects to the SSH server using the properties of the ssh object:

  • ip: IP address of the SSH server.
  • port: Port of the SSH server.
  • retries: Number of retries.
  • timeout: Timeout in milliseconds.
  • user: SSH user.
  • password: SSH password.
  • identity: Rsa key content.

Returns an object with the following properties:

  • result: true if the connection was successful, false otherwise.
  • message: Empty if the connection was successful, error message otherwise.

Example of use:

ssh.ip = "[IP_ADDRESS]";
ssh.port = 22;
ssh.user = "sshuser";
ssh.password = "password";

// this example shows how to connect to an SSH server and wait for the "Connection established" string.
var connectResult = ssh.connect(["Connection established"]);

if (connectResult.result) {
    // Connection was successful
} else {
    // Connection failed
}

ssh.send(command, pattern, waitFor)

Sends a command to the SSH server and waits for the response.

Parameter Type Description
command string Command to send to the SSH server.
pattern string Pattern to extract response from sent command.
waitFor List Strings to wait for in the response.
  • retries: Number of retries.
  • timeout: Timeout in milliseconds.

Returns the response of the SSH server in string format.

Example of use:

// this example shows how to send a command to an SSH server and wait for the "/home/sshuser" string.
var sendResult = ssh.send("ls -la", "*", ["/home/sshuser"]);

ssh.disconnect()

Disconnects from the SSH server.

Example of use:

ssh.disconnect();

Telnet Javascript API

Connector functions Telnet JS API guide

This API allows users to execute operations in the Telnet connector from a connector function.

Telnet Object

The Telnet object is the main object of the Telnet connector. It allows to connect to a Telnet server, send commands and receive responses, and disconnect from the Telnet server.

Telnet Object Properties

Property Type Default Description
ip string IP address of the Telnet server.
port number 23 Port of the Telnet server.
retries number 3 Number of retries.
timeout number 5000 Timeout in milliseconds.

Telnet Object Methods

telnet.connect (waitFor)

Connects to the Telnet server using the properties of the Telnet object and the specified parameters.

Parameter Type Description
waitFor string String to wait for in the response.
  • ip: IP address of the Telnet server.
  • port: Port of the Telnet server.
  • retries: Number of retries.
  • timeout: Timeout in milliseconds.

Returns an object with the following properties:

  • result: true if the connection was successful, false otherwise.
  • message: Empty if the connection was successful, error message otherwise.

Example of use:

telnet.ip = "[IP_ADDRESS]";
telnet.port = 23;

var connectResult = telnet.connect(">");

if (connectResult.result) {
    // Connection was successful
} else {
    // Connection failed
}

telnet.send (command, pattern, waitFor)

Sends a command to the Telnet server and waits for the response with the specified parameters:

Parameter Type Description
command string Command to send to the Telnet server.
pattern string String to pattern match in the response. In RegExp format.
waitFor string String to wait for in the response. If not specified, the default is >.
  • retries: Number of retries.
  • timeout: Timeout in milliseconds.

Returns the response of the Telnet server in an array of strings.

Example of use:

var sendResult = telnet.send("ls -la", "*", ">");

telnet.disconnect ()

Disconnects from the Telnet server.

Example of use:

telnet.disconnect();

ICMP JavaScript API

Introduction

This API allows users to send PING operations to an IP address.

Icmp Object

The icmp object is the main object of the ICMP client. It allows sending a PING operation to an IP address, and receiving the response (in synchronous or asynchronous mode).

Icmp Object Properties

Property Type Default Description
ip string (*) IP address to send PING.
retries number 5 Number of PING delivery retries.
timeout number 2500 Timeout in milliseconds of retry.
async boolean true Decide if the request is asynchronous (true) or synchronous (false).

(*) By default, select the IP of the device or the provisioned subscription.

Icmp Object Methods

icmp.send()

Send PING using the properties of the icmp object:

  • ip: IP address to send PING.
  • retries: Number of PING delivery retries.
  • timeout: Timeout in milliseconds of retry.
  • async: Decide if the request is asynchronous or synchronous.
  • RETURN: If the async property is false, then returns an object with the following properties:

    • result: String. The value will be “OK” when the result is successfull or “NOK” when the result of the request had error, for example, timeout.
    • deviceId: String. Entity receiving the ping.
    • datastreams: An array with the information of the request result.

Example of use:

icmp.ip = "10.10.10.174";
icmp.send();

Result:

  • SUCESSFULL:
{
  "result": "OK",
  "datastreams": [
    {
        "id":"device.communicationModules[].subscription.address",
        "datapoints":[
            {
                "value":{
                    "value": "10.10.10.174"
                }
            }
        ]
    },
    {
        "id":"device.communicationModules[].subscription.presence.ip",
        "datapoints":[
            {
                "value": "OK"
            }
        ]
    },
    {
        "id":"device.communicationModules[].subscription.presence.ipRtt",
        "datapoints":[
            {
                "value": 6
            }
        ]
    }
  ]
}
  • ERROR:
{
  "result": "NOK",
  "deviceId": "deviceId",
  "datastreams": [
    {
      "datastreamId": "collected.device.communicationModules.subscription.address",
      "value": "172.19.18.95"
    },
    {
      "datastreamId": "collected.device.communicationModules.subscription.presence.ip",
      "value": "NOK"
    }
  ]
}

ICMP Response Javascript

Connector function ICMP-Response JS API guide

This API allows users to receive response of another ICMP-Request Connector Function. You can process the data as necessary.

Response Object

The response object is the main object of the response, it is the payload.

The object received has the following properties:

  • operationResult: Parent object of the result.
    • version: String. Version of the response message received.
    • trustedboot: Boolean. Trusted boot value.
    • operation: Object with the operation properties:
      • response: Object with the response operation properties:
        • id: String. Request Id of the launched operation.
        • name: String. The name of the launched operation.
        • deviceId: String. Entity identifier that receives the operation.
        • resultCode: String. Result code of the launched operation.
        • resultDescription: String. Result description of the launched operation.
        • additionalDescription: String. Additional result description of the launched operation.
        • path: String. Device usage URL.
        • variables: Array with the device usage variables.
        • entityType: Enum. Type of entity that receives the operation. Possible values: “DEVICE”, “SUBSCRIPTION”, “SUBSCRIBER”, “COMMS_MODULE”
        • steps: Array with the steps of the launched operation.
          • name: String. Result step name.
            • result: String. Result step code.
            • description: String. Result step description
            • response: Json. Json information of the step.
            • timestamp: Number. Timestamp of the step.
        • timestamp: Number. Timestamp of the launched operation.
        • iotData: Collection object with the following properties:
          • version: String. Version of the message IoT received.
          • datastreams: Array with information about the launched operation. (IoT message)
            • id: String. Identifier of the datastream collected.
            • datapoints: Array with the information of the datastream.

Example:

{
  "operationResult": {
    "operation": {
      "response": {
      	"id": "86a52ffe-9f4f-427b-8154-aef7bc2935a0",
      	"name": "REFRESH_PRESENCE",
        "resultCode": "SUCCESSFUL",
      	"resultDescription": "RESULT OK",
      	"additionalDescription": "",
      	"deviceId": "devicedId",
      	"timestamp": 1701288987,
      	"path": [ "/deviceId/request" ],
      	"steps": [{
      	  "name": "Step Name",
        	"result": "Step Result",
        	"description": "Step description",
        	"response": {},
        	"timestamp": 1701288960
      	}],
      	"variables": [ "address", "" ],
      	"replacements": {
      	},
      	"entityType": {
      	  "enum": ["DEVICE", "SUBSCRIPTION", "SUBSCRIBER", "COMMS_MODULE"]
      	},
      	"iotData": {
          "version": "1.0",
          "datastreams":[
            {
              "id":"device.communicationModules[].subscription.address",
              "datapoints":[
                {
                   "value":{
                       "value": "10.10.10.174",
                       "type": "IPV4",
                       "apn": "movistar.es"
                   }
                }
              ]
            }
          ]
        }
      }
    }
  }
}