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 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.
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.
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=newUint8Array([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:
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:
// After connection has been established
dlms.addAttr(1, "1.2.3.4.5.6", 2, "unsigned", 254)
varsetResult=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)
varsetResult=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)
vargetResult=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
varsetResult=dlms.set() // More details on set next
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).
// 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
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
varresult=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
varresult=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
varresult=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.
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
varresult=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}
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.
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-stringtype 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)
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:
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 typedate-time, date, time or octet-string with its 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)
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
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.
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.
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:
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:
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:
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:
constcustom48= {
"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(...);
...
}
};
constdecodeResult=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:
constcustom48= {
"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);
}
};
constdecodeResult=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:
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:
constnewBehavior= {/*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.
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.
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.
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.
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.
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.
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:
varres=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:
sync clock: check and sync device clock
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.
retrieve push events configurations: like initial data retrieving but for push events configurations, it will be asked if it is not collected already.
periodic actions: used to retrieve data that must be retrieved periodically like statistics.
automatic actions: used to retrieve data depending on previously collected data and received data in push notification.
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.
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.
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": ...returnedvaluefromdlms.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.
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.
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.
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.
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:
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():
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:
constchain=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'
constchain=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:
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:
constcb= {
"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
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:
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.
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:
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.
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.
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).
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.
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:
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:
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.
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.
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:
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.
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.
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.
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:
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";
varconnectionStatus=iec102.connect("GSM");
if(!connectionStatus.connected) {
/* Connection not established.
At this point response object is fulfilled
with error code and description and skipped steps.
*/returnresponse;
}
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:
Execute directly one ASDU.
Define one by one all iec102.asdus and then execute.
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
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.
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:
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:
In this example, we will suppose that timeRequest ASDU finish correctly:
First, login ASDU will be executed. After execution, no step or collection will be sent.
Before executing timeRequest, 1000 milliseconds wait will be done.
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:
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:
Before executing loadCurve, 1000 milliseconds wait will be done.
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:
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).
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.
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.
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:
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:
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.
varconnectResult=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.
varsendResult=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;
varconnectResult=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:
varsendResult=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.