DLMS-Client-UserManual C#

Download as pdf or txt
Download as pdf or txt
You are on page 1of 101

DLMS/COSEM Client Library C#

User Manual

www.kalkitech.com

Version 3.15.1, 20th Dec 2022


Copyright Notice

© 2013 Kalki Communication Technologies. All rights reserved.


This user manual is a publication of Kalki Communication Technologies Private Ltd. and is provided for use by its
customers only. The contents of the user manual are copyrighted by Kalkitech; reproduction in whole or in part, for use
other than in support of Kalkitech equipment, is prohibited without the specific written permission of Kalkitech.

Disclaimer

Information in this document is subject to change without notice.


Information provided in this manual is intended to be accurate and reliable. However, Kalki Communication
Technologies assumes no responsibility for its use. Kalki Communication Technologies makes no commitment to
update or keep current the information contained in this user manual.

Contact Information

Kalki Communication Technologies Private Limited


The Address, 4th Floor, # 17/1, Outer Ring Road,
Opposite Prestige Cessna Business Park
Kadubeesanahalli, Bangalore
INDIA 560103
Phone: +91-80-67021900

Technical Support Contact Information

Online Technical Enquiry www.kalkitech.com/support


Support

E-mail Support [email protected]


DLMS/COSEM Client SCL User Manual Version 3.15.1

About the Document

Purpose

This manual serves as a guide for using DLMS/COSEM Client Source Code Library. This manual
familiarizes the user with the source code library and provides a step–by–step instruction on how to
integrate the code with the user application.

Intended Audience

This User's Guide is intended for application developers.

Organization of the Document

This document is organized in to three parts as follows:

Chapter Chapter Name Description


Chapter 1 Introduction The chapter provides an introduction to the
DLMS Client SCL
Chapter 2 Implementation This chapter provides instructions for the
procedure Implementation procedure

Chapter 3 Call Sequence This chapter provides a general call sequence of


functions

Table 1: Organization of the document

Confidential
3
DLMS/COSEM Client SCL User Manual Version 3.15.1

Documentation Conventions

The following table shows the conventions used in the document:


Sl.No Item Conventions Used

1 Field Name, Screen Name and Button Arial, Bold face font
2 Note Note:

3 Each step in the task is numbered Identified by numbered list


First Step
Second Step

Table 2: Document Conventions

Confidential
4
DLMS/COSEM Client SCL User Manual Version 3.15.1

List of Abbreviations
The following table shows the acronyms/abbreviations used in this document:

Acronyms/Abbreviations Description
COSEM Companion Specification for Energy Metering
DLMS Device Language Message Specification
IP Internet Protocol
LN Logical Name
OBIS Object Identification System
OEM Original Equipment Manufacturer
PDU Protocol Data Unit
SAP Service Access Point
SN Short Name

Table 3: List of abbreviations

Confidential
5
DLMS/COSEM Client SCL User Manual Version 3.15.1

Contents
1 Introduction...........................................................................................................................................9
1.1 Overview of The Protocol Stack...................................................................................................9
1.2 Sample Implementations...............................................................................................................9
1.3 Key Features..................................................................................................................................9
2 Implementation Procedure..................................................................................................................10
2.1 Overview.....................................................................................................................................10
2.2 Client Library Functions.............................................................................................................10
2.2.1 initClient()..........................................................................................................................10
2.2.2 initPort()..............................................................................................................................12
2.2.3 modeEInit()..........................................................................................................................13
2.2.4 closePort()............................................................................................................................14
2.2.5 closeClient().........................................................................................................................14
2.2.6 setParamsHDLC()................................................................................................................14
2.2.7 sendSNRM()........................................................................................................................16
2.2.8 sendDISC()..........................................................................................................................17
2.2.9 SetParamsCosemWrapper().................................................................................................17
2.2.10 SetParamsAARQ...............................................................................................................18
2.2.11 sendAARQ()......................................................................................................................21
2.2.12 SetParamsPreEstablishedAssociation................................................................................23
2.2.13 sendRLRQ().......................................................................................................................26
2.2.14 getData()............................................................................................................................28
2.2.15 cleanupMemory()..............................................................................................................31
2.2.16 setData().............................................................................................................................31
2.2.17 CleanUpMemoryForSet.....................................................................................................33
2.2.18 executeAction()..................................................................................................................34
2.2.19 createSocket.......................................................................................................................36
2.2.20 acceptSocket......................................................................................................................36
2.2.21 initIncomingPort................................................................................................................37
2.2.22 closeSocket........................................................................................................................37
2.2.23 setParamsUnsolicitedCommunication...............................................................................38
2.2.24 registerSecurityCallbacks..................................................................................................39
2.2.25 registerCertCallback.........................................................................................................43
2.2.26 registerCipheringKeysCallback.........................................................................................43
2.2.27 registerPushCallback.........................................................................................................44
2.3 Special Functions........................................................................................................................44
2.3.1 registerErrCallback..............................................................................................................44
2.3.2 registerDiagCallback...........................................................................................................45
2.3.3 UpdateHdlcAdvancedSettings.............................................................................................45
2.3.4 updateSerialAdvancedSettings............................................................................................46
2.3.5 Set Frame Counter...............................................................................................................47
2.3.6 CosemEncodeAXDR..........................................................................................................47
2.3.7 CosemEncodeAARQ...........................................................................................................51
2.3.8 CleanUpEncodedAXDR......................................................................................................56

Confidential
6
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.9 CosemDecodeAXDR...........................................................................................................57
2.3.10 CleanupDecodedAXDR...................................................................................................60
2.3.11 cosemDecodeCompactFrameData.....................................................................................60
2.3.12 cleanDecodedCompactFrameData....................................................................................61
2.3.13 getSystemTitleFromPushNotification...............................................................................62
2.3.14 cleanUpencodeComHeader...............................................................................................62
2.3.15 encodeComProfileParams..................................................................................................63
2.3.16 decodeComProfileParams..................................................................................................64
2.3.17 cleanUpdecodedComHeader.............................................................................................65
2.3.18 EncodeHDLCrequest.........................................................................................................65
2.3.19 cleanUpEncodedHDLC.....................................................................................................68
2.3.20 DecodeHDLCrequest.........................................................................................................68
2.3.21 CleanUpEncodedAXDR....................................................................................................71
2.3.22 Sendpacket.........................................................................................................................71
2.3.23 Call Sequence(HDLC).......................................................................................................72
2.3.24 setGatewayParams.............................................................................................................72
2.3.25 useDedicatedCiphering......................................................................................................73
2.3.26 cosemEncodeRLRQ..........................................................................................................74
2.3.27 processChallenge...............................................................................................................78
2.3.28 setFrameCounter................................................................................................................79
2.3.29 cleanPushData....................................................................................................................80
2.3.30 getAssociationParameters..................................................................................................80
2.3.31 cleanEventData..................................................................................................................80
2.3.32 getEvent.............................................................................................................................81
2.3.33 triggerEventNotification....................................................................................................81
2.3.34 imageTransfer....................................................................................................................81
2.4 Structures and Unions.................................................................................................................83
2.4.1 DLMS_UNION_CS............................................................................................................83
2.4.2 ACTION_UNION_CS.........................................................................................................84
2.5 Security Implementation.............................................................................................................85
3 Call Sequence......................................................................................................................................90
3.1 Multichannel Operation...............................................................................................................91
4 Debugging Options.............................................................................................................................91
5 Running on Linux (+Windows)..........................................................................................................92
6 Appendix A.........................................................................................................................................93
6.1 Return Codes in SCL...................................................................................................................93
6.1.1 Generic return codes............................................................................................................93
6.1.2 Library generated HDLC specific return codes...................................................................93
6.1.3 Library generated COSEM specific return codes................................................................93
6.1.4 Server generated return codes..............................................................................................94
7 Appendix B: Interoperability Details of DLMS Client SCL...............................................................96

Confidential
7
DLMS/COSEM Client SCL User Manual Version 3.15.1

Index of Tables
Table 1: Organization of the document......................................................................................3
Table 2: Document Conventions................................................................................................4
Table 3: List of abbreviations.....................................................................................................5

Confidential
8
DLMS/COSEM Client SCL User Manual Version 3.15.1

1 Introduction

Introduction has the following topics:

• Overview of the protocol stack.

• Sample implementations.

• Key features.
1.1 Overview of The Protocol Stack
The DLMS/COSEM Client Source Code Library provides a complete implementation of a 62056
DLMS/COSEM protocol stack to enable interested OEMs to create DLMS Client Applications to
read/write DLMS enabled meters and devices.

The stack is based on the following specifications

▪ IEC-62056-42: Physical Layer

▪ IEC-62056-46: HDLC Datalink Layer

▪ IEC 62056-47 COSEM Transport Layers for IPv4 networks

▪ IEC-62056-53: COSEM Application Layer

▪ IEC-62056-61: OBIS (Object Identification System)

▪ IEC-62056-62: Interface Classes

The protocol source is written in ANSI-C and can be used on most platforms as-is without any
changes.
1.2 Sample Implementations
The SCL ships with sample implementations using either source code or object library, depending on
the type of delivery opted by the OEM. The OEM can build this sample implementation and start
running the client on a Windows/Linux machine and test against a server to trace the flow and logic of
the protocol-stack.
1.3 Key Features
• DLMS UA attested stack
• Platform independent with default implementation for Windows and Linux
• Supports HDLC and UDP TCP/IP communication profiles
• Support for IEC 62056-21 Mode E

Confidential
9
DLMS/COSEM Client SCL User Manual Version 3.15.1

2 Implementation Procedure

The chapter on Implementation Procedure covers the following topics:

• Overview of the Implementation Procedure.

• Client Library Functions.

• Structures and Unions.


2.1 Overview
The Client Object Library is provided as a Windows DLL or as a Linux shared library. Other platform-
implementations can also be provided on request.

The object library is shipped with a sample application to demonstrate the implementation
methodology.

The exported library functions provide a means to open and initialize a serial or IP port/, establish a
HDLC connection (only for HDLC based communication profile), establish an application association,
and then functions to read/write/execute attributes and methods in the connected DLMS server
(meter). The client application can then call functions to disconnect from the meter, close the
communication port and cleanup memory.
2.2 Client Library Functions
The following are the exported functions in the Client Object Library. The following description is specific to
usage from within a .NET application.

2.2.1 initClient()

This function is to be used to initialize the client as the first step when using the library.

Prototype

IntPtr initClient ( uint ResTimeOut,


ushort interframeTmOut,
ushort linkBuffsz,
uint cosemBufsz,
byte commProfile,
byte cipheringSupport,
ushort channelNo)

Arguments
ResTimeOut
Response timeout used by the client, in milliseconds. This is the amount of time

Confidential
10
DLMS/COSEM Client SCL User Manual Version 3.15.1

that the Client is to wait after sending a request without receiving a response
before declaring that the request has timed-out.

interframeTmOut
Frame timeout in milliseconds. This is the amount of time that the Client will wait
after receiving the initial few bytes of a frame-header, for the rest of the frame to
be received.

linkBuffsz
HDLC/wrapper(for IPv4) buffer size. Suggested value is 512 bytes. This allocates
the size of the HDLC or TCP/IP Layer buffers for received and transmit data.

cosemBufsz
COSEM buffer size, This is the size of the COSEM Application Layer buffers that
hold the received data when performing a Get/Read operation. This should be a
large value to hold the largest possible attribute value that may be read from the
meter. Certain array-type attributes (for example, the Buffer attribute of a Profile
object) may contain several entries. This buffer should be sized appropriately to
hold the entire response.

commProfile
Communication Profile .This is the type of communication profile in use

(Direct HDLC, Mode-E, TCP/IP and UDP.)

cipheringSupport Used to indicate ciphering support


0 => not supported
1 => supported
channelNo
This is any ushort value given by user application that can be optionally used by
application in future to distinguish the client handle(especially in case of
push/event receipt)

Return Value Pointer to the newly created DLMS Handle

NOTE: Stack will use this value only for some initialization and buffer allocations. Actual ciphering depends on
the ciphering values passed in further functions (like sendAARQ / getData/ setData/ executeAction ). User
should ensure cipheringSupport to be consistent with appCtxt of setParamsAARQ, cipheringType of getData
/ setData / executeAction. If user is doubtful or may “sometimes” want to use ciphering in Application
association, then cipheringSupport shall be set to 1.

Confidential
11
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.2.2 initPort()

This function initializes and opens a communication port.

Prototype

byte initPort( IntPtr clientHandle,


IntPtr clientIpAddr_p,
IntPtr serverIpAddr_p,
ushort serverPort,
IntPtr port_p,
uint BaudRate,
byte Parity,
byte enableUnsolicitedService,
ushort max_no_of_conn_retries,
uint retry_delay,
uint connWaitTimeout)

Arguments

clientHandle Client handle returned by the initClient() function

clientIpAddr_p Required only for IP based communication profile. IP address of client as string
(ending with ‘\0’) (e.g. “127.0.0.1”).

serverIpAddr_p Required only for IP based communication profile. IP address of server as string
(ending with ‘\0’) (e.g. “127.0.0.1”).

serverPort Required only for IP based communication profile. UDP/TCP port of server.

port_p Only for serial . The serial port name as a string(char string, e.g. “”//./COM1” ).

BaudRate [ Only for serial ] The baud rate for communication.(integer, e.g. 9600 ) .

Parity Specifies the parity scheme to be used, 0-4 = no, odd, even, mark, space

enableUnsolicitedService Enumeration to indicate if unsolicited(server initiated; e.g. Push Data notification /


Event notification ) communication is to be supported. 1 => Enable unsolicited
communication 0=> Does not support unsolicited communication.

max_no_of_conn_retries This argument is used to define the maximum number of retries that client should
perform to connect to server before invoking application error callback . This

Confidential
12
DLMS/COSEM Client SCL User Manual Version 3.15.1

automatic reconnection mechanism is available only for pre-established


association with TCP communication profile. This is applicable only for cases in
which an existing connection fails and not applicable in the very first connection
attempt(i.e. InitPort() fails).

retry_delay Specify the delay used between successive retries.

connWaitTimeout 0 - blocking mode, >0 - time in ms for select() timeout in non -blocking mode

Return Value SUCCESS if function succeeds, else FAILURE. (Here SUCCESS is 0, and
FAILURE is 1).

2.2.3 modeEInit()

This function performs the mode E (IEC 62056-21) handshaking before switching to COSEM/ HDLC.

Note:- This function is required only if opening mode is Mode E.

Prototype

byte modeEInit ( IntPtr clientHandle,


string deviceAdd,
string strXXX,
string idenString)

Arguments

clientHandle Client handle returned by the initClient() function

deviceAdd Device address is string (optional field, manufacturer specific, 32 characters


maximum)

strXXX String (Manufacturer’s identification comprising of three upper case letters)

idenString String (Identification, manufacturer specific, 16 printable characters maximum


except for “/” and “!”)

Return Value SUCCESS if function succeeds, else FAILURE. (Here SUCCESS is 0, and
FAILURE is 1).

Confidential
13
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.2.4 closePort()

For closing the communication port.

Prototype
byte closePort (IntPtr clientHandle)

Arguments

clientHandle Client handle returned by the initClient() function.

Return Value SUCCESS if function succeeds, else FAILURE.

2.2.5 closeClient()

For closing the DLMS Client.

Prototype

void closeClient (IntPtr clientHandle)

Arguments

clientHandle Client handle returned by the initClient() function.

Return Value SUCCESS if function succeeds, else FAILURE.

2.2.6 setParamsHDLC()

Set HDLC parameters in stack. This function will only set HDLC parameters and will not establish
HDLC connection .

NOTE: For users who are familiar with previous versions(versions prior to 3.3.0) of DLMS Client stack,
it shall be noted that sendSNRM() function has been now split into two functions : setParamsHDLC()
and sendSNRM().

Prototype

Confidential
14
DLMS/COSEM Client SCL User Manual Version 3.15.1

byte setParamsHDLC(IntPtr clientHandle,


byte addressSize,
byte clntID,
ushort serverID,
ushort devAddr,
byte windowRx,
byte windowTx,
ushort infoFieldLenRx,
ushort infoFieldLenTx)

Arguments
clientHandle Client handle returned by the initClient() function
addressSize Number of bytes used for addressing the server. Possible values are 1, 2
or 4. When a value of 1 is specified, the destination address (server-
address) contains only 1 byte which contains the Upper HDLC address
of the meter. This can be used for point-to-point communication. In case
of a multi-drop scenario (daisy-chained meters), the address must also
specify the lower HDLC or device-address to identify which physical
device is being addressed. This can use a 2-byte or a 4-byte destination
address. In case of a 2-byte address, the server address has 1-byte
Upper HDLC address and 1-byte Lower HDLC address. In case of 4-
byte addressing, the server-address contains 2-bytes Upper and 2-bytes
Lower HDLC addresses.
ClntID Client id for current association. This is the ID of DLMS client . The client-
ID is used by the server to determine which association in the addressed
Logical-device is to be activated. A value of 16 (0x10) is
predefined by the DLMS standard to specify a Public-Access client. Any
DLMS server must provide at least one Public-Access association. Other
Client IDs supported shall be obtained from meter manufacturer or from
respective project/companion specification.
ServerID Upper HDLC address of the server. This identifies which Logical-device
in the addressed-meter is being queried. Any DLMS server will provide at
least one Logical-device with an address of 1, which indicates the
Management Logical device.
devAddr Lower HDLC address of the server. This is the physical-device address
of the meter. Please note that a physical device can contain multiple
logical devices identified by unique Upper HDLC addresses In turn, each
Logical device can support multiple associations (with different object-lists
and access-rights) defined by unique client-IDs.
windowTx Number of windows receive. This identifies the number of segmented

Confidential
15
DLMS/COSEM Client SCL User Manual Version 3.15.1

frames that can be received at a go by this client, before requiring


to send a RR (Request-Ready) handshake. The DLMS default value is 1.
infoFieldLenRx Number of windows transmit. This identifies the number of segmented
frames that can be transmitted at a go by this client, before requiring a
RR (Request-Ready) handshake from the server. The DLMS
default value is 1.
infoFieldLenTx Information field length receive. This defines the size of the Info-field part
of a received DLMS frame. The info-field is the carrier of all COSEM data
destined to be processed by the upper Layers. The DLMS default
value is 128 .
Return Value SUCCESS if function succeeds, else FAILURE.

2.2.7 sendSNRM()

Function is used to establish a HDLC-MAC connection by sending an SNRM (Set Normal Response Mode)
frame. This function if successful establishes a link layer connection to the Meter. The significant parameters are
the client and server addresses which will be compared by the Meter against its configured list of Association
client IDs and server logical device ids. This function also allows user to make use of optional HDLC parameter
negotiation (Maximum Information Size Transmit and Receive, Maximum windows Size Transmit and
Receive).The user is expected to send the required values, however the final values used in further
communication may be different from these, since the meter will negotiate these parameters and set the
minimum values that is acceptable to both client and server.

Note:- This function is required only for HDLC based communication profile.

Prototype

byte sendSNRM (IntPtr clientHandle,


byte negParams)

Arguments

clientHandle Client handle returned by the initClient() function.

negParams Enumeration indicating if HDLC parameters(Maximum Information size


transmit and receive, maximum window size transmit and receive) shall
be negotiated with server. Possible values are0 => No negotiation, 1 =>
Negotiate.

Return Value SUCCESS if function succeeds, else an error code indicating the
reason for error.

Confidential
16
DLMS/COSEM Client SCL User Manual Version 3.15.1

When a value of 1 is specified, the destination address (server-address) contains only 1 byte which
contains the Upper HDLC address of the meter. This can be used for point-to-point communication.

In case of a multi-drop scenario (daisy-chained meters), the address must also specify the lower
HDLC or device-address to identify which physical device is being addressed. This can use a 2-byte
or a 4-byte destination address. In case of a 2-byte address, the server address has 1-byte Upper
HDLC address and 1-byte Lower HDLC address. In case of 4-byte addressing, the server-address
contains 2-bytes Upper and 2-bytes Lower HDLC addresses.

2.2.8 sendDISC()

This function can be used to send the disconnect frame which disconnects both the Link-layer as well
as the Application layers. A DISC frame can be sent after a successful SNRM and also after a
successful Association.

If a DISC frame is not sent after either case above and if there is no further activity from the client, the
DLMS server will automatically go to disconnected mode (DM) after a configured Inactivity timeout.
• Note:- This function is required only for HDLC based communication profile.

Prototype

byte sendDISC (IntPtr clientHandle)

Arguments

clientHandle Client handle returned by the initClient() function.

Return Value SUCCESS if function succeeds, else FAILURE.

2.2.9 SetParamsCosemWrapper()

Set Application address parameters(Client address and Server Logical address) in stack, in case of
IP(Cosem-Wrapper) communication profile. This function will only set parameters and will not
establish Application Association. This function is required only in IP based communication.

Prototype

byte SetParamsCosemWrapper(IntPtr clientHandle,


ushort wClientAddr,
ushort wServerAddr)

Confidential
17
DLMS/COSEM Client SCL User Manual Version 3.15.1

Arguments

clientHandle Client handle returned by the initClient() function.

wClientAddr Client wrapper port number(Client Address)

wServerAddr Server wrapper port number(Server Logical Device Address)

Return Value 0 in case of success, otherwise an error code.

2.2.10 SetParamsAARQ
Set Application layer (AARQ) parameters in stack. This function will only set parameters and will not
establish Application Association. This function is required in both IP and HDLC based communication.

Prototype

ushort SetParamsAARQ(IntPtr clientHandle,


byte appCtxt,
byte authMech,
byte[] authKey,
byte[] encKey,
byte[] dedicatedKey,
byte[] globalbroadcastkey,
byte[] priKeyClient,
byte[] pubKeyServer,
byte securityPolicy,
byte secSuite,
uint authTagLen,
byte[] clientSystemTitle,
byte[] passwrd,
byte passwrdLen,
ushort maxApduSizeRecv,
uint conformance,
byte generalGlobalCipher,
byte curUserId)

Arguments

Confidential
18
DLMS/COSEM Client SCL User Manual Version 3.15.1

Client handle returned by the initClient() function


clientHandle

appCtxt Application context. Values can be 1, 2, 3 or 4. The application context


defines the referencing method to be used (LN or SN)

• 1 for LN Association with No ciphering

• 2 for SN Association with No ciphering


3 for LN Association with ciphering4 for SN Association with ciphering.
authMech Authentication mechanism used. Values can be 0, 1, 2, 3, 4, or 5.
0 for Lowest Level Security (without password)

1 for Low Level Security (with static password)

2 for High Level Security (with coded password)

3 for High Level Security (with encrypted password using md5


algorithm)

4 for High Level Security (with encrypted password using sha-1


algorithm)

5 for High Level Security (with encrypted password using GMAC


algorithm)

6 for High Level Security (with encrypted password using SHA256


algorithm )

7 for High Level Security (with encrypted password using ECDSA


algorithm)

authenticationKey_p authentication key used for security policies 1 and 3. This key is used in
protecting APDUs exchanged within application
association.encryptionKey_p → encryption key used for ciphered
application contexts. This key is used in protecting APDUs exchanged within
application association.

encryptionKey_p
encryption key used for ciphered application contexts. This key is used in
protecting APDUs exchanged within application association.dedEncKey_p

dedEncKey_p dedicated key used for dedicated Key ciphering.

Confidential
19
DLMS/COSEM Client SCL User Manual Version 3.15.1

globalbroadcastkey
Global broadcast key used to secure broadcast communication between a
DLMS client and several DLMS servers.

priKeyClient Private key to use for signature generation. Either 32 or 48 bytes based on
security suite.

pubKeyServer Public key to use for signature verification. Either 64 or 96 bytes based on
security suite.

SecurityPolicy Security policy for the association. 0 for No Security


1 for Authentication Only
2 for Encryption Only
3 for Authentication and Encryption
securitySuite Information field length receive. This defines the size of the Info-field part
of a received DLMS frame. The info-field is the carrier of all COSEM data
destined to be processed by the upper Layers. The DLMS default value is
128 .
authTagLen Length of GMAC Authentication tag of APDUs used within Application
Association Possible values are 12(normal Authentication tag) 8(short
Authentication tag)
clientSystemTitle_p Client system title. This should be a string of length 8.This key is used for
generating Initialization Vector used in ciphering .
passwrd_p
auth_mech is 0 : in case of Lowest level security, this field is not used by library.

auth_mech is 1 : in case of Low level security, this field will be the pointer
to the unsigned character array which contains authentication value.
auth_mech is 2,3,4 and 5: in case of High level security, this field will be the
pointer to the unsigned character array which contains the key used for HLS.
Presently the library expects key to be always 16 bytes long
passwrdLen Length(number of bytes) of the password filled.
maxApduSizeRecv This is the maximum APDU size that the client can receive. This is used only in
LN referencing contexts that support Block transfer. In SN contexts a value of
0xFFFF can be specified.
conformance This is the conformance block that specifies which functional components of the
server are required by the client. This is a number formed by enabling the
appropriate bits corresponding to specified functionality. For more details refer
Appendix B
• For example a value of 0x180000 indicates Read and Write
functions for SN and a value of 0x001818 indicates Get, Set, Block
Transfer with Get and Block Transfer with Set functions. The supplied
conformance block will be negotiated by the server by “AND”-ing with its
own conformance block to return a negotiated value that contains the
functions that are common to both.Example: 0xFFFFFF

Confidential
20
DLMS/COSEM Client SCL User Manual Version 3.15.1

generalGlobalCipher Enumeration indicating the kind of ciphering used for Action service during HLS
0 for service specific global ciphering

1 for General Global ciphering with out system title(System title length =
0)

2 for General Global ciphering with system title(System title length = 8)

It shall be noted that this is used only to specify the type of ciphering used in
APDU for Action service used during HLS. This does not have any influence on
ciphering used after Association establishment.

• curUserId Specify the ID for current user information to encode in AARQ request.
Return Value 0 in case of success, otherwise an error code.

2.2.11 sendAARQ()

This function is used to establish an application association which connects the COSEM layers of the client
and server. This can only be called after a successful SNRM which connects the lower layers. The parameters
of the Association must match the settings in the meter for the Association that was identified in the SNRM by
the client and server ids.

Prototype

byte SendAARQ(IntPtr clientHandle,


byte supportUserIdEncoding,
SECURITY_PARAM securityParam,
byte[] clientChallenge,
byte clientChallengeLen,
byte serviceClass,
byte dedicatedKeyPresent,
ushort maxApduSizeSend,
byte priority);

NOTE: Before calling sendAARQ() user should set Application layer parameters using following
functions

Confidential
21
DLMS/COSEM Client SCL User Manual Version 3.15.1

For IP communication profile:-


setParamsCosemWrapper()
setParamsAARQ()
For HDLC communication profile:-
setParamsHDLC()
setParamsAARQ()

Arguments

clientHandle Client handle returned by the initClient() function.

supportUserIdEncoding Enumeration to indicate if user id is to be encoded in AARQ

0 => user id not encoded

1 => user id encoded

NOTE: this is required only in case of encryption/decryption.


securityParam typedef struct SecurityParam
{
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;
KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;
meaning of each bit in cipheringType as shown below:
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and to
enable or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is 1 or
TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if 7 th bit

Confidential
22
DLMS/COSEM Client SCL User Manual Version 3.15.1

is 1 or TRUE, it indicates compression is enabled.

typedef struct FrameCounter


{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;

There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In
other method, user can pass frame counter values to library which shall
be used while applying protection. For former method set “userCfg” to 0
and for latter method, user shall set “userCfg” to 1 and also pass frame
counter value in “ frameCounterToUse” variable

Contains the client challenge to be used.


clientChallenge

Indicates length of the client Challenge


clientChallengeLen

serviceClass Possible values are


0 - To send unconfirmed AARQ.
1 - To send confirmed AARQ.
This information shall be encoded in responseallowed field of
InitiateRequest.
dedicatedKeyPresent Indicates if dedicated Key is present in the InitiateRequest sequence
contained in the AARQ request.By setting this to "1" , data
communication in Application Association will use dedicated key
ciphering. It is possible to change ciphering type by using
"useDedicatedCiphering" function.
MaxApduSizeSend The size of the PDU for pre-establised association is controlled by this
argument. It has no effect on normal associations.
Priority This argument used to control the priority of Action request in Pass 3 of
HLS association establishment. It has effect only in HLS associations.
0 – For normal priority
1 – For high priority.

Return Value 0 in case of success, otherwise an error code.

2.2.12 SetParamsPreEstablishedAssociation
For pre-established association, the cosem parameters initialized in SetParamsAARQ is not sufficient.
Additional parameters for pre-established association are set by using this function. If Client Server
communication is using HDLC as communication profile, then this function shall be called only after
ensuring a valid HDLC connection. The parameters to initialize application association in client shall be
set by calling SetParamsAARQ.

Confidential
23
DLMS/COSEM Client SCL User Manual Version 3.15.1

NOTE: Before calling setParamsPreEstablishedAssociation() user should set


Application layer parameters using following functions
For IP communication profile:-
SetParamsCosemWrapper()
setParamsAARQ()
For HDLC communication profile:-
setParamsHDLC()
setParamsAARQ(

Prototype

byte setParamsPreEstablishedAssociation(IntPtr clientHandle,


IntPtr serverSystemTitle,
byte serverSystemTitleLen,
uint conformance,
ushort maxApduSizeSend,
SECURITY_PARAM SecurityParam);

Arguments

clientHandle Client handle returned by the initClient() function.

String of length 8.This is the default server system title used to


serverSystemTitle decrypt a encrypted APDU received from server. If system title is
present in received APDU then DLMS client library use the system title
received for decrypting that APDU. serverSystemTitleLen →
Length(number of bytes) of server system title
Value 0 will cause library to discard server system title
Example: 0.
serverSystemTitleLen Length(number of bytes) of server system title Value 0 will cause library
to discard server system title Example: 0.
conformance This is the conformance block that specifies which functional
components of the server are required by the client. This is a number
formed by enabling the appropriate bits corresponding to specified
functionality. For example a value of 0x180000 indicates Read and
Write functions for SN and a value of 0x001818 indicates Get, Set,
Block Transfer with Get and Block Transfer with Set functions. Example:

Confidential
24
DLMS/COSEM Client SCL User Manual Version 3.15.1

0xFFFFFF.
maxApduSizeSend This is the maximum APDU size that the client can send in a frame.
Example: 512.

securityParam NOTE: this is required only in case of encryption/decryption.

typedef struct SecurityParam{

KDEFS_UCHAR cipheringType;

FRAME_COUNTER_CFG *frameCounter;

KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;

meaning of each bit in cipheringType as shown below:

0 unused, shall be set to 0,

1 unused, shall be set to 0,

2 authenticated request,

3 encrypted request,

4 digitally signed request,

5 authenticated response,

6 encrypted response,

7 digitally signed response

6th and 7th bit of security control byte is reserved for key set and to
enable or disable the compression respectively.

Confidential
25
DLMS/COSEM Client SCL User Manual Version 3.15.1

If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is 1 or


TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if 7 th bit
is 1 or TRUE, it indicates compression is enabled.
typedef struct FrameCounter{

KDEFS_UCHAR userCfg;

KDEFS_ULONG frameCounterToUse;

}FRAME_COUNTER_CFG;

There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In
other method, user can pass frame counter values to library which shall
be used while applying protection. For former method set “userCfg” to 0
and for latter method, user shall set “userCfg” to 1 and also pass frame
counter value in “ frameCounterToUse” variable.

dedicatedKeyPresent Indicates if dedicated Key is present in the InitiateRequest sequence


contained in the AARQ request.By setting this to "1" , data
communication in Application Association will use dedicated key
ciphering. It is possible to change ciphering type by using
"useDedicatedCiphering" function.
MaxApduSizeSend The size of the PDU for pre-establised association is controlled by this
argument. It has no effect on normal associations.
Priority This argument used to control the priority of Action request in Pass 3 of
HLS association establishment. It has effect only in HLS associations.
0 – For normal priority
1 – For high priority.

Return Value 0x0000 in case of success, otherwise an error code.

2.2.13 sendRLRQ()

Release an already established application association.

• Note:- This function is required only for IP based communication profile.

Confidential
26
DLMS/COSEM Client SCL User Manual Version 3.15.1

Prototype

byte sendRLRQ(IntPtr clientHandle,


byte Reason,
SECURITY_PARAM securityParam,
byte serviceClass)

Arguments

clientHandle Client handle returned by the initClient() function.

Reason Error Code indicating reason for release

NOTE: this is required only in case of encryption/decryption.


securityParam typedef struct SecurityParam
{
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;
meaning of each bit in cipheringType as shown below:
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and to
enable or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is
1 or TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if
7th bit is 1 or TRUE, it indicates compression is enabled.

typedef struct FrameCounter


{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;

Confidential
27
DLMS/COSEM Client SCL User Manual Version 3.15.1

There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In other
method, user can pass frame counter values to library which shall be used
while applying protection. For former method set “userCfg” to 0 and for
latter method, user shall set “userCfg” to 1 and also pass frame counter
value in “ frameCounterToUse” variable

serviceClass Possible values are


0 - To send unconfirmed AARQ.
1 - To send confirmed AARQ.
This information shall be encoded in responseallowed field of
InitiateRequest.

Return Value 0 in case of success and error code in case of failure

2.2.14 getData()

This function can be used to get values from the meter. The function accepts the reference to a structure in
which the read data is filled. The definition for this structure can be found in the ICStructs.h header file.

The function automatically checks which context is being used and sends either a Get (for LN contexts) or a
Read (for SN contexts). The referenced structure contains all attributes of all Interface classes supported. The
user of the library is required to only read or process the attribute of the object that was requested. Attempts to
read other attributes or other class objects may result in NULL errors.

Prototype

IntPtr GetData (IntPtr clientHandle,


COSEM_ATTR_METH_DESC_LIST getListData,
byte priority,
byte invokeId,
SECURITY_PARAM securityParam)

Arguments

clientHandle Client handle returned by the initClient() function.

getListData COSEM_ATTR_METH_DESC_LIST structure containing list of cosem


attribute descriptors

typedef struct CosemAttrMethDescList

Confidential
28
DLMS/COSEM Client SCL User Manual Version 3.15.1

{
KDEFS_ULONG numDescriptors;
COSEM_ATTR_METH_DESC *cosemAttrMethDesc;
KDEFS_UCHAR useWithList;
}COSEM_ATTR_METH_DESC_LIST;

useWithList shall be set if multiple reference(get with list) is to be


used

typedef struct CosemAttrMethDesc


{
OBISCODE *obis_p;
KDEFS_USHORT base;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
SELACCESSPARAMS selParams_p;
} COSEM_ATTR_METH_DESC;

NOTE: The response data will be in the same sequence as that of


request.

priority priority bit to be inserted in request(0=Normal priority, 1=High priority).


This argument causes to set priority bit accordingly in request sent to
server.

invokeId Invoke id of the request. Only last 4 bit value will be used for encoding
Range : 0 to 15
securityParam typedef struct SecurityParam{
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;

}SECURITY_PARAM;
meaning of each bit in ciphering type is as shown below:Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and to enable

Confidential
29
DLMS/COSEM Client SCL User Manual Version 3.15.1

or disable the compression respectively.


If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is 1 or
TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if 7 th bit is
1 or TRUE, it indicates compression is enabled.

typedef struct FrameCounter{


KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;

There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In other
method, user can pass frame counter values to library which shall be used
while applying protection. For former method set “userCfg” to 0 and for
latter method, user shall set “userCfg” to 1 and also pass frame counter
value in “ frameCounterToUse” variable

Return Value Null pointer : unknown error

Non zero pointer :Pointer to COSEMDATA structure


• typedef struct CosemData{
DLMS_UNION *dlmsData;
KDEFS_USHORT result;
}COSEMDATA;

Result in COSEMDATA indicate general/overall result. Individual object


attribute wise result is contained in result variable inside each
DLMS_UNION structure.For each cosem attribute descriptor passed in
request, there will be a corresponding DLMS_UNION in the same
sequence they were filled in request

The first element of the DLMS_UNION structure is a “result” value that


indicates success or failure. The values in the proper fields of the structure
are valid only if the ‘result’ field is 0 indicating success.
Library updates result code in “result” variable inside DLMS_UNION
structure.
Result code 0 => success In this case Client user shall fetch data from
appropriate sub-structure according to the interface class requested.
Result code non zero => error. See Appendix A for more details of error
code.

Confidential
30
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.2.15 cleanupMemory()

This function must be called after the getData() function call, to free the memory allocated by that
function. getData() returns a DLMS_UNION pointer that has various elements allocated dynamically.
Before calling another getData() call, this function must be called to enable the library to clean-up the
memory used.

• NOTE: This function need not be called from a managed code, as it has been already
handled in the wrapper DLL.

Prototype

void cleanUpMemory (IntPtr clientHandle)

Arguments •

clientHandle
Client handle returned by the initClient() function

2.2.16 setData()

This function can be used to write data to the meter. Before invoking this function, the write data must be filled
within a DLMS_UNION_CS structure variable. Its address has to be passed through this function.

The user of the library is expected to allocate and fill in a DLMS_UNION_CS structure with the appropriate
attribute data to be set. After the call completes the user is also expected to cleanup and release the memory
used. The client library does not clean-up setdata.

Prototype
IntPtr SetData( IntPtr clientHandle,
SETDATAINFO setDataInfo,
byte priority,
byte serviceClass,
byte invokeId,
SECURITY_PARAM securityParam);

• Arguments

clientHandle Client handle returned by the initClient() function.

setDataInfo List of cosem attribute descriptors and data to set

Confidential
31
DLMS/COSEM Client SCL User Manual Version 3.15.1

typedef struct SetDataInfo{


COSEM_ATTR_METH_DESC_LIST cosemAttrDescrList;
DLMS_UNION *setCosemData;
}SETDATAINFO;
typedef struct CosemAttrMethDesc{
OBISCODE *obis_p;
KDEFS_USHORT base;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
SELACCESSPARAMS selParams_p;
} COSEM_ATTR_METH_DESC;

NOTE: The response data will be in the same sequence as that of


request.

priority priority bit to be inserted in request(0=Normal priority, 1=High priority).


This argument causes to set priority bit accordingly in request sent to
server.

serviceClass service class bit to be inserted in request(0 = unconfirmed, 1 =


confirmed). If service class is set as unconfirmed, then Client will send
requested data and return immediately without waiting for response. User
shall ensure that for communication involving segmentation(in case of
HDLC) or block transfer, service class shall always be set as confirmed.
InvokeId
Invoke id of the request (Only last 4 bit value will be used for encoding.)

securityParam
typedef struct SecurityParam {
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;
meaning of each bit in ciphering type is as shown below:
Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response

Confidential
32
DLMS/COSEM Client SCL User Manual Version 3.15.1

6th and 7th bit of security control byte is reserved for key set and to
enable or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it
is 1 or TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if
7th bit is 1 or TRUE, it indicates compression is enabled.

typedef struct FrameCounter


{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;
There are two methods to handle frame counters. In one method,
library will take care of frame counters and user need not
interfere at all. In other method, user can pass frame counter
values to library which shall be used while applying protection.
For former method set “userCfg” to 0 and for latter method, user
shall set “userCfg” to 1 and also pass frame counter value in “
frameCounterToUse” variable

Return Value 0x0000 : List of results in the same sequence as cosem attribute
descriptors filled in request. IntPtr : points to structure:

typedef struct ResultInfo{
KDEFS_ULONG numDescriptors;
KDEFS_USHORT *dataResult;
KDEFS_USHORT genResult;
}RESULTINFO;

Non zero :indicates error. See Appendix A for detailed list of error codes

2.2.17 CleanUpMemoryForSet

Clean memory allocated to store set result for each cosem attribute descriptor. User shall call this
function after every setData()

Prototype

void cleanUpMemoryForSet( IntPtr ClientHandle);

Arguments •

Confidential
33
DLMS/COSEM Client SCL User Manual Version 3.15.1

clientHandle
Client handle returned by the initClient() function

2.2.18 executeAction()

This function can be used to execute methods of objects. The method arguments have to be filled in a
structure variable before invoking the function. The definitions of the ACTION_UNION_CS structure can
be found in ICStructs.h file.

Prototype

IntPtr ExecuteAction(IntPtr clientHandle,


COSEM_METH_DESC_LIST actionReqList,
byte priority,
byte serviceClass,
byte invokeId,
SECURITY_PARAM securityParam);

Arguments

clientHandle Client handle returned by the initClient() function.

COSEM_METH_DESC_LIST structure containing list of cosem method


actionReqList descriptors
typedef struct CosemAttrMethDescList{
KDEFS_ULONG numDescriptors;
COSEM_METH_DESC *cosemMethDesc;
KDEFS_UCHAR useWithList;
ACTION_UNION *actionData_p;
}COSEM_METH_DESC_LIST;
useWithList shall be set if multiple reference(get with list) is to be
used
typedef struct CosemMethDesc{
OBISCODE *obis_p;
KDEFS_USHORT base;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
} COSEM_METH_DESC;

priority priority bit to be inserted in request(0=Normal priority, 1=High priority).

Confidential
34
DLMS/COSEM Client SCL User Manual Version 3.15.1

This argument causes to set priority bit accordingly in request sent to


server.

serviceClass service class bit to be inserted in request(0 = confirmed, 1 =


unconfirmed).
InvokeId
invoke id of the request (Only last 4 bit value will be used for encoding.)

securityParam
typedef struct SecurityParam {
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;
meaning of each bit in ciphering type is as shown below:
Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and to enable
or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is 1 or
TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if 7 th bit is
1 or TRUE, it indicates compression is enabled.
typedef struct FrameCounter
{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;
There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In
other method, user can pass frame counter values to library which shall
be used while applying protection. For former method set “userCfg” to 0
and for latter method, user shall set “userCfg” to 1 and also pass
frame counter value in “ frameCounterToUse” variable.

Return Value 0x0000 : List of results in the same sequence as cosem attribute

Confidential
35
DLMS/COSEM Client SCL User Manual Version 3.15.1

descriptors filled in request. IntPtr : points to structure:


typedef struct ResultInfo{
KDEFS_ULONG numDescriptors;
KDEFS_USHORT *dataResult;
KDEFS_USHORT genResult;
}RESULTINFO;

Non zero :indicates error. See Appendix A for detailed list of error codes

2.2.19 createSocket
This function is used to create TCP or UDP sockets. The socket handle returned by the
function shall used to pass as argument on API's expecting TCP/UDP sockets.
In case of TCP sockets, this function shall create sockets, bind to a TCP port and start
listening on the newly created port.
In case of UDP sockets, this function shall create sockets and bind to a UDP port.

Prototype

IntPtr createSocket(ushort portNum,


byte commProfile,
byte option,
int backlog);

Arguments
portNum port number through which the socket is to communicate.
commProfile Indicates the chosen communication profile- TCP or UDP.

options 1.Ipv4
2.Ipv6
backlog the limit for the queue of incoming connections

Return Value Handle to the created socket.

2.2.20 acceptSocket
This function is used to accept incoming connection on TCP sockets. This function shall return a
valid socket number on a valid connection to socket created by createSocket() API.
Prototype

Confidential
36
DLMS/COSEM Client SCL User Manual Version 3.15.1

IntPtr acceptSocket(IntPtr sock);


Arguments
sock Handle to created socket.

Return Value Pointer to socket.

2.2.21 initIncomingPort
This function initializes all thread to read and process push/ event data received on the TCP/UDP
sockets.
Prototype

ushort initIncomingPort(IntPtr clientHandle,


IntPtr Sock,
ushort wClientAddr,
ushort wServerAddr);

Arguments
clientHandle clientHandle returned by initClient().

Sock Socket created for unsolicited communication.


WclientAddr Client port number.

WserverAddr Server port number.

Return Value 0 if Success, else returns an error code.

2.2.22 closeSocket

This function closes the created sockets.

Prototype

void closeSocket(IntPtr sockHandle);

• Arguments

Confidential
37
DLMS/COSEM Client SCL User Manual Version 3.15.1

sockHandle Handle to created socket.

Return Value void

2.2.23 setParamsUnsolicitedCommunication
• This function is used to set the parameters for unsolicited communication(Server
initiated).
• This parameter shall used to process packets received on server initiated connections.
Prototype

ushort setParamsUnsolicitedCommunication(IntPtr clientHandle,


byte[]authenticationKey,
byte[] encryptionKey,
byte[] serverSystemTitle,
byte[] clientSystemTitle,
ushort serverSystemTitleLen,
uint authTagLen,
byte appCntx,
byte securitySuite,
byte securityPolicy,
byte[] pubKeyServer);

• Arguments
clientHandle clientHandle returned by initClient().
authenticationKey_p authentication key for ciphered application contexts
encryptionKey_p encryption key for ciphered application contexts
serverSystemTitle System title of associated server
clientSystemTitle System title of associated client
serverSystemTitleLen length of system title
authTagLen length of authentication tag
appCntx Application context. Values can be 1, 2, 3 or 4. The application context
defines the referencing method to be used (LN or SN)
1 for LN Association with No ciphering

Confidential
38
DLMS/COSEM Client SCL User Manual Version 3.15.1

2 for SN Association with No ciphering

3 for LN Association with ciphering


4 for SN Association with ciphering.
securitySuite SecuritySuite of the security object used for the association. It Specifies
the security algorithms available.
0 for AES_GCM_128
1 for AES_GCM_128_ECDSA_256
2 for AES_GCM_256_ECDSA_384
securityPolicy Security policy for the association. 0 for No Security
1 for Authentication Only
2 for Encryption Only
3 for Authentication and Encryption
pubKeyServer
Public key to use for signature verification. Either 64 or 96 bytes based on
security suite.

Return Value void

2.2.24 registerSecurityCallbacks
This function registers the security callback function. Library shall use the registered
function to encrypt/decrypt, prepare hash values.
Prototype
void registerSecurityCallbacks( CryptCallback encryptFn,
CryptCallback decryptFn,
HashCallback hashFn,
SigGenCallback sigGenFunPtr,
SigVerCallback sigVerFunPtr,
ParseCRTCallback parseCRTFunPtr,
DigKeyPairGenCallback digKeyPairFunPtr,
GetCRTCallback getCRTFunPtr,
DigKeyPairGenCallback digKeyPairFunPtr,
GenSharedKeyCallback genSharedKeyFunPtr,
KeyDerivCallback keyDerivFunPtr,
AssymHashCallback assymHashGenFunPtr,
GetSignKeysCallback getSignKeysFunPtr);

Arguments

Confidential
39
DLMS/COSEM Client SCL User Manual Version 3.15.1

encryptFn Encryption callback function pointer.


decryptFn Decryption callback function pointer
hashFn Hashing callback function pointer
sigGenFunPtr SigGenFunPtr callback function pointer
sigVerFunPtr SigVerFunPtr callback function pointer
parseCRTFunPtr ParseCRTFunPtr callback function pointer
digKeyPairFunPtr CdigKeyPairFunPtr allback function pointer
getCRTFunPtr GetCRTFunPtr callback function pointer
genSharedKeyFunPtr GenSharedKeyFunPtr callback function pointer
keyDerivFunPtr KeyDerivFunPtr callback function pointer
assymHashGenFunPtr KeyDerivFunPtr callback function pointer
getSignKeysFunPtr GetSignKeysFunPtr callback function pointer

Return Value void

HashCallback is defined as:


byte HashCallback(byte hashMethod, /* Hashing algorithm used, 3 for MD5 and 4 for SHA1 */
IntPtr plainText_p, /* The plaintext */
ushort ptLen, /* The length of the plaintext (ciphertext length is the same) */
IntPtr cipherText_p); /* The ciphertext */

SigGenCallback is defined as :
byte SigGenCallback( IntPtr privateKey,
IntPtr plainText,
uint ptLen,
byte notUsedByteIndex,
IntPtr sig,
IntPtr sigLen,
byte DER_Encoding,
byte SecuritySuite)
This function is used to generate digital signature on the data pointed to by the plainText pointer,
length of which is contained in ptLen. The private key used for signing is held in privateKey pointer,
and the flag DER_Encoding is 1 if DER encoding is to be used. The generated signature is held in sig
pointer with length in sigLen pointer.

SigVerCallback is defined as :
byte SigVerCallback( IntPtr publicKey,
IntPtr plainText,
uint ptLen,

Confidential
40
DLMS/COSEM Client SCL User Manual Version 3.15.1

byte notUsedByteIndex,
IntPtr sig,
uint slen,
byte DER_Encoding,
byte SecuritySuite)
This function is used to verify digital signed data contained in the plainText pointer, length of which is
contained in ptLen. The public key used for verification is held in publicKey pointer, and the flag
DER_Encoding is 1 if DER encoding is used. The signature contained in the packet is passed to this
function through the sig pointer with length in slen pointer.

ParseCRTCallback is defines as :
byte ParseCRTCallback( IntPtr cert,
uint certLen,
IntPtr certificate_publicKey,
IntPtr certificate_Signature,
IntPtr signLen)
This function is used to parse the input certificate, stored in cert pointer with length in certLen variable.
The user is also required to pass the digital signature and its length in pointers certificate_Signature
and signLen. The function parses the certificate and returns the public key stored in the certificate
incertificate_publicKey pointer.

DigKeyPairGenCallback is defined as
byte DigKeyPairGenCallback( IntPtr privateKey,
IntPtr publicKey)
This function is used to generate a pair of keys consisting of private and public key to be used for
digitally signing and verifying data.

GetCertificateIdentificationByserial is defined as
byte DigKeyPairGetCertificateIdentificationByserial( IntPtr serial_number,
byte serial_numberLen,
IntPtr issuer,
byte issuerLen,
IntPtr Certifcate,
uint CertificateLen,
IntPtr CRT,
IntPtr len)
This function is used to obtain a digital keys and certificate on passing serial number and its length,
issuer and length and also the certificate length.CRT is the certificate request pointer.

GetCertCallback is defined as
byte GetCertCallback( IntPtr certBuf_Len_CRT,
IntPtr Cert_Buf,
IntPtr PrivateKey,
IntPtr PublicKey,
IntPtr PublicKey2,
byte flag)
This function is used to obtain a digital certificate on passing the private key and public key in the
PrivateKey and PublicKey pointers. The generated certificate is stored into the Cert_Buf pointer by the

Confidential
41
DLMS/COSEM Client SCL User Manual Version 3.15.1

function, with length in the certBuf_Len_CRT pointer. The arguments PublicKey2 and flag are not used
in the current stack.

GenSharedKeyCallback is defined as
byte GenSharedKeyCallback( IntPtr PrivateKeyServer,
IntPtr PublicKeyClient,
IntPtr result,
byte SecuritySuite)

This function is used in the Key Agreement method (IC64 version 1, method 3) to generate a shared
key. The user is required to pass the private key of the Server and public key of the client into the
PrivateKeyServer and PublicKeyClient pointers, with algorithm ID I in the Algo_ID pointer and system
titles of server and client in the Server_Sys and Client_Sys pointers respectively. The generated
shared key will be contained in the result pointer on execution of this function.

KeyDerivCallback is defined as
byte KeyDerivCallback (IntPtr cntr,
IntPtr sharedSecret,
IntPtr algID,
IntPtr SystitleClient,
IntPtr SystitleServer,
IntPtr DerivedKey,
byte secSuite)
This function is also used in the Key Agreement method (IC64 version 1, method 3) to derive the new
key from the shared key generated by the above function.The user is reured to pass the generated
shared key into sharedSecret pointer, along with required values into the cntr, algID, SystitleClient
(Client System title), SystitleServer(server system title) pointers and the security suite used into the
secSuite argument. The new key to be used will be returned in the DerivedKey pointer.

assymHashGenerate is defined as
byte assymHashGenerate( byte hashMethod,
IntPtr plainText_p,
byte ptLen,
IntPtr hash)
This function decrypts the data for HLS Authentication and data transport security. Its arguments
include the hashMethod which indicates the Hashing algorithm used (3 for MD5 and 4 for SHA1, 6 for
SHA256), plainText_p pointer contains the plaintext, length of which is stored in ptLen (ciphertext
length is the same). The function returns the hash which is pointed to by the hash pointer.

getCertificate is defined as
byte getCertificate( IntPtr certSignLen,
IntPtr certBuffer,
IntPtr privKey,
IntPtr pubKey,
IntPtr dlmsInstance)
This function is used to obtain a digital certificate on passing the private key and public key in the

Confidential
42
DLMS/COSEM Client SCL User Manual Version 3.15.1

PrivateKey and PublicKey pointers.Generated certificate is stored in Cert_Buf pointer with length in
the certBuf_Len_CRT pointer.

2.2.25 registerCertCallback

This function registers the diagnostic callback function.


Prototype

void registerCertCallback(CertCallback certCbk);

Arguments
certCbk Registers the getCertificate callback function:
byte getCertificate( IntPtr certSignLen,
IntPtr certBuffer,
IntPtr privKey,
IntPtr pubKey,
IntPtr dlmsInstance,
ushort ChannelNo)

Return Value void

2.2.26 registerCipheringKeysCallback
To register call back function to get ciphering keys.
Prototype

void registerCipheringKeysCallback(
CIPHERING_KEYS_CALLBACK cipheringKeysFunPtr)

Arguments
callbackPointer typedef void(*CIPHERING_KEYS_CALLBACK)(void *dlmsInstance,
KDEFS_USHORT ChannelNo,
KDEFS_UCHAR *key,
KDEFS_UCHAR KeyType,
KDEFS_UCHAR operation,
KDEFS_UCHAR secSuite,
KDEFS_UCHAR* SystitleServer);

Return Value void

Confidential
43
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.2.27 registerPushCallback
This function registers the data notification callback function. Library will invoke the
registered function on a valid push processed by library.
Prototype

void registerPushCallback(PUSH_CALLBACK callbackPointer);

• Arguments
• callbackPointer
void PUSH_CALLBACK(IntPtr clientHandle, /* uniquely identifies the
communication channel */

IntPtr pushData, /* pointer to structure


containing Pushed data */

ushort wCport, /* Client port number */

ushort wSport /* Server port number */

ushort ChannelNo);/*number indicating the


channel instance*/

Return Value void


2.3 Special Functions

2.3.1 registerErrCallback
This function registers the error reporting callback function.
Prototype

void registerErrCallback(ERROR_CALLBACK callbackPointer);

• Arguments
• callbackPointer
void ERROR_CALLBACK(IntPtr clientHandle, /* uniquely identifies
the communication channel */

ushort ErrorCode, /*Error code, Only socket termination from other

Confidential
44
DLMS/COSEM Client SCL User Manual Version 3.15.1

partis supported now by the stack*/

ushort ChannelNo)/*number indicating the channel instance */

Return Value void


2.3.2 registerDiagCallback
This function registers the diagnostic callback function.
Prototype

void registerDiagCallback(DiagCallback callbackPointer);

Arguments
callbackPointer Diagnostic callback function pointer.

void DiagCallback(IntPtr clientHandle, /* uniquely identifies the


communication channel */

byte layerId, /* identifies the layer that produces the


diagnostic message */

byte diagType, /* Identifies the type of message */

IntPtr pMsg, /* reference to the message/ buffer */

uint msgLen, /* length of message/ buffer */

ushort ChannelNo);/*number indicating the channel instance */

Return Value void

2.3.3 UpdateHdlcAdvancedSettings
This function is used to configure a delay between the sending of HDLC frames.

Confidential
45
DLMS/COSEM Client SCL User Manual Version 3.15.1

Prototype

byte UpdateHdlcAdvancedSettings(IntPtr clientHandle,


ushort hdlcSendDelay)

• Arguments
• clientHandle Handle returned by initClient()

hdlcSendDelay Delay between the frames in milliseconds

Return Value void

2.3.4 updateSerialAdvancedSettings

This function is used to update the serial port advanced settings.

Prototype
byte UpdateSerialAdvancedSettings(IntPtr clientHandle,
ref SER_ADV_PORT_SETTINGS portSettings)

Arguments
clientHandle Handle returned by initClient()

portSettings Pointer to the structure containing the serial port parameters to be


updated.Definiton as follows
public struct SER_ADV_PORT_SETTING
{
public uint readIntervalTimeout; /* Maximum time between
read chars. */
public uint readTotalTimeoutMultiplier; /* Multiplier of characters.
*/
public uint readTotalTimeoutConstant; /* Constant in
milliseconds. */
public uint writeTotalTimeoutMultiplier; /* Multiplier of characters.
*/
public uint writeTotalTimeoutConstant; /* Constant in milliseconds.
*/
}

Confidential
46
DLMS/COSEM Client SCL User Manual Version 3.15.1

Return Valu void

2.3.5 Set Frame Counter

This is an optional function using which user application can set or change frame counter used by library to
build IV which is used while applying protection to APDUs while sending.

Prototype
void setFrameCouter(void *clientHandle,

KDEFS_ULONG frameCounterToUse)

• Arguments
• clientHandle Handle returned by initClient()

• frameCounterToUse Frame counter to be used - 32 bit integer value .

Return Value void

2.3.6 CosemEncodeAXDR

This function is used if user want library to prepare a data communication service request APDU(such as
Get request / Set Request / Action Request) and return the APDU back to user(instead of following the
usual Client state machine where in library send the request to server by library itself).

Prototype
IntPtr CosemEncodeAXDR(SECURITY_PARAM securityParam,
byte appCtxt,
byte SecuritySuite,
byte[] clientSystemTitle,
byte[] ServerSystemTitle,
byte[] authenticationKey,
byte[] encryptionKey,
byte[] globalbroadcastkey,
uint authTagLen,
byte serviceClass,
byte priority,
byte invokeId,
ushort maxApduSizeSend,
byte useGenGloCiph,

Confidential
47
DLMS/COSEM Client SCL User Manual Version 3.15.1

byte useGlobalCiph,
byte service,
uint cosemBufSize,
GENERAL_ATTR_METH_DESC_LIST generalAttrMethDescList,
byte[] privateKey,
ushort channelNo,
byte enableLLCHeader);

• Arguments
securityParam
typedef struct SecurityParam{
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

KDEFS_UCHAR enablebroadcastkey;
}SECURITY_PARAM;
meaning of each bit in ciphering type is as shown
below:
Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and
to enable or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it
is 1 or TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if
7th bit is 1 or TRUE, it indicates compression is enabled.

typedef struct FrameCounter {


KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;
There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In
other method, user can pass frame counter values to library which shall
be used while applying protection. For former method set “userCfg” to 0
and for latter method, user shall set “userCfg” to 1 and also pass frame

Confidential
48
DLMS/COSEM Client SCL User Manual Version 3.15.1

counter value in “ frameCounterToUse” variable

appCtxt Application context. Values can be 1, 2, 3 or 4. The application


context defines the referencing method to be used (LN or SN)

1 for LN Association with No ciphering

2 for SN Association with No ciphering

3 for LN Association with ciphering

4 for SN Association with ciphering.

SecuritySuite Security suit used for PDU’s generation shall be configured by this
argument. IC64 version 0 supports only security suit 0.

clientSystemTitle_p Client system title used by the library to generate IV required while
applying protection. This parameter will be used only if security policy
demand authentication/encryption to be applied.

ServerSystemTitle_p Server system title is used for generating PDU’s with server system title
encoded in it like Generel signing request..

authenticationKey_p Authentication key used in protection

encryptionKey_p Encryption key used in protection .

globalbroadcastkey Global broadcast key used to secure broadcast communication between


a DLMS client and several DLMS servers.

authTagLen Length of GMAC Authentication tag of APDUs used within Application


Association Possible values are12 and 8

serviceClass service class bit to be inserted in request(0 = unconfirmed, 1 =


confirmed)

priority Priority bit to be inserted in request(0=normal, 1 = high)

invokeId Invoke ID to be inserted in 4 bit invoke ID field of request

maxApduSizeSend This is the maximum APDU size that the client can included in a block. If

Confidential
49
DLMS/COSEM Client SCL User Manual Version 3.15.1

the generated request APDU exceeds this value the APDU will be
returned in multiple blocks.

useGenGloCiph Specify the type of ciphering used APDU.

1 for General Global ciphering

0 for service specific global ciphering

useGlobalCiph Use to enable dedicated(0) / global (1) ciphering.

service Three choices for service type are as follows :

0xC0 for Get request

0xC1 for Set Request

0xC3 for Action request

cosemBufSize This is the size of the COSEM Application Layer buffer that hold the
APDU's on the function execution. This should be a large value to hold
the largest possible APDU that may be generated by the function.
Example: 10000

generalAttrMethDescList User can specify one or more cosem attribute /method descriptor which
is being referred in the APDU to be generated.
typedef struct CosemServiceSpecAttrMethDescList {
KDEFS_ULONG numDescriptors;
GENERAL_ATTR_METH_DESC *generalAttrMethDesc;
KDEFS_UCHAR useWithList;
}GENERAL_ATTR_METH_DESC_LIST;
typedef struct ServiceIndepAttrMethDesc{
OBISCODE * obis_p;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
void * serviceSpecificData_p;
} GENERAL_ATTR_METH_DESC;
This pointer can hold 3 kinds of data based on the value of service.if
Service is

• 0xC0 then this pointer is optional. If not used then set as NUL.If

Confidential
50
DLMS/COSEM Client SCL User Manual Version 3.15.1

used, then it shall contaiin selective access parameters(as if


passed in getData() )

• 0xC1 then this pointer shall contain DLMS_UNION structure with


set data filled in(as if passed in setData() ).
0xC3 then this pointer shall contain ACTION_UNION structure with
action data filled in(as if passed in executeAction() ).

privateKey private key used in digital signature

channelNo any ushort value given by user application that can be optionally used
by

application in future to distinguish the client handle(especially in case of


push/event receipt)

• enableLLCHeader Enabling this flag shall generate packet with LLC header. This can be
used to generate packets for HDLC communication profile. Use 0 for IP
based communication.

IntPtr : points to.PREPARED_APDU * Structure with list of


Return Value structures(each structure contain one APDU block); length of list is
indicated in blockCount
typedef struct PrepareApduParams
{
ENCODED_AXDR *cosemPreparedApdu;
KDEFS_USHORT blockCount;
KDEFS_UCHAR curServiceType;
KDEFS_USHORT result;
} PREPARED_APDU;
typedef struct EncodedAXDR
{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

2.3.7 CosemEncodeAARQ

This function is used if user want library to prepare a AARQ APDU and return the APDU back to
user(instead of following the usual Client state machine where in library send the request to server by
library itself).

Confidential
51
DLMS/COSEM Client SCL User Manual Version 3.15.1

IntPtr CosemEncodeAARQ(byte appCtxt,


byte authMech,
byte[] authenticationKey,
byte[] encryptionKey,
byte[] dedEncKey,
byte[] globalbroadcastkey,
byte securityPolicy,
byte securitySuit,
byte authTagLen,
byte[] clientSystemTitle,
byte[] password,
byte passwrdLen,
ushort maxApduSizeRecv,
byte curUserId,
byte enableUserIdEncoding,
SECURITY_PARAM securityParam,
byte[] clientChallenge,
byte clientChallengelen,
byte ServiceClass,
byte useGenGloCiph,
byte enableDedicatedKey,
uint conformance,
uint cosemBufSize,
byte[] privateKey,
ushort channelNo,
byte enableLLCHeader)

Arguments

appCtxt Application context. Values can be 1, 2, 3 or 4. The application context


defines the referencing method to be used (LN or SN)

1 for LN Association with No ciphering

2 for SN Association with No ciphering

3 for LN Association with ciphering

4 for SN Association with ciphering.

Confidential
52
DLMS/COSEM Client SCL User Manual Version 3.15.1

authMech Authentication mechanism used. Values can be 0, 1, 2, 3, 4, or 5.

0 for Lowest Level Security (without password)

1 for Low Level Security (with static password)

2 for High Level Security (with coded password)

3 for High Level Security (with encrypted password using md5 algorithm)

4 for High Level Security (with encrypted password using sha-1


algorithm)

5 for High Level Security (with encrypted password using GMAC


algorithm)

6 for High Level Security (with encrypted password using SHA256


algorithm)

7 for High Level Security (with encrypted password using ECDSA


algorithm)

authenticationKey_p authentication key used for security policies 1 and 3. This key is used in
protecting APDUs exchanged within application association.

encryptionKey_p encryption key used for ciphered application contexts. This key is used
in protecting APDUs exchanged within application association.

dedEncKey_p dedicated key used for dedicated Key ciphering

globalbroadcastkey Global broadcast key used to secure broadcast communication between a


DLMS client and several DLMS servers.

SecurityPolicy SecurityPolicy → Security policy for the association.

0 for No Security

1 for Authentication Only

2 for Encryption Only

3 for Authentication and Encryption

secSuite SecuritySuite of the security object used for the association. It Specifies

Confidential
53
DLMS/COSEM Client SCL User Manual Version 3.15.1

the security algorithms available.

0 for AES_GCM_128

1 for AES_GCM_128_ECDSA_256
2 for AES_GCM_256_ECDSA_384

authTagLen Length of GMAC Authentication tag of APDUs used within Application


Association Possible values are
12(normal Authentication tag)

8(short Authentication tag)

clientSystemTitle_p Client system title. This should be a string of length 8.This key is used
for generating Initialization Vector used in ciphering .

password auth_mech is 0 : in case of Lowest level security, this field is not used by
library.

auth_mech is 1 : in case of Low level security, this field will be the


pointer to the unsigned character array which contains authentication
value.
auth_mech is 2,3,4, 5, 6 and 7: in case of High level security, this field will
be the pointer to the unsigned character array which contains the key
used for HLS. Presently the library expects key to be always 16 bytes
long
passwrdLen Length(number of bytes) of the password filled.

maxApduSizeRecv This is the maximum APDU size that the client can receive. This is used
only in LN referencing contexts that support Block transfer. In SN
contexts a value of 0xFFFF can be specified.

curUserId Specify the ID for current user information to encode in AARQ request

supportUserIdEncoding indicate if UserID need to encoded in callingAEInvocationId field of


AARQ or not

securityParam typedef struct SecurityParam{


KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;

Confidential
54
DLMS/COSEM Client SCL User Manual Version 3.15.1

KDEFS_UCHAR enablebroadcastkey;

}SECURITY_PARAM;
Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,
3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response
6th and 7th bit of security control byte is reserved for key set and to
enable or disable the compression respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is being used. If it is 1 or
TRUE, Broadcast Key is being used.
If 7th bit is 0 or FALSE, it indicates compression is disabled and if 7 th bit
is 1 or TRUE, it indicates compression is enabled.
typedef struct FrameCounter {
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;
There are two methods to handle frame counters. In one method, library
will take care of frame counters and user need not interfere at all. In other
method, user can pass frame counter values to library which shall be
used while applying protection. For former method set “userCfg” to 0 and
for latter method, user shall set “userCfg” to 1 and also pass frame
counter value in “ frameCounterToUse” variable
clientChallenge Client challenge

clientChallengelen Indicates length of the client Challenge

ServiceClass • 1 -> confirmed, 0->unconfirmeds

generalGlobalCipher Specify the type of ciphering used APDU.

1 for General Global ciphering

0 for service specific global ciphering

dedicatedKeyPresent • dedicateKeyPresent : Indicate if dedicated key should be encoded in


AARQ
• 1 dedicate key present in AARQ

• Conformance This is the conformance block that specifies which functional

Confidential
55
DLMS/COSEM Client SCL User Manual Version 3.15.1

componentsof the server are required by the client. This is a number


formed by enabling the appropriate bits corresponding to specified
functionality. For more details refer Appendix B
For example a value of 0x180000 indicates Read and Write functions for
SN and a value of 0x001818 indicates Get, Set, Block Transfer with Get
and Block Transfer with Set functions. The supplied conformance
block will be negotiated by the server by “AND”-ing with its own
conformance block to return a negotiated value that contains the
functions that are common to both.Example: 0xFFFFFF

• cosemBufSize This is the size of the COSEM Application Layer buffer that hold the
APDU's on the function execution. This should be a large value to hold
the largest possible APDU that may be generated by the function.
Example: 10000
privateKey private key used in digital signature

channelNo any ushort value given by user application that can be optionally used
byapplication in future to distinguish the client handle(especially in case
of push/event receipt)

enableLLCHeader Enabling this flag shall generate packet with LLC header. This can be
used to generate packets for HDLC communication profile. Use 0 for IP
based communication.

IntPtr :
Return Value points to.PREPARED_APDU * Structure with list of structures(each
structure contain one APDU block); length of list is indicated in
blockCount
typedef struct PrepareApduParams{
ENCODED_AXDR *cosemPreparedApdu;
KDEFS_USHORT blockCount;
KDEFS_UCHAR curServiceType;
KDEFS_USHORT result;
} PREPARED_APDU;
typedef struct EncodedAXDR{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

2.3.8 CleanUpEncodedAXDR

This function must be called after the cosemEncodeAXDR(), cosemEncodeAARQ() and cosemEncodeRLRQ()
functions returned and CleanUpEncodedAXDR() is used by user to free the memory allocated by library during
cosemEncodeAXDR() , cosemEncodeAARQ() and cosemEncodeRLRQ() functions. cosemEncodeAXDR()
returns a PREPARED_APDU pointer that has various elements allocated dynamically. Before calling another

Confidential
56
DLMS/COSEM Client SCL User Manual Version 3.15.1

cosemEncodeAXDR() call, this function must be called to enable the library to clean-up the memory used. Client
user can call this function irrespective of the result(Success/Failure) returned by cosemEncodeAXDR().
Prototype

cleanUpEncodedAXDR(IntPtr preparedAPDU);

Arguments
preparedAPDU This is a pointer to a structure variable which hold the encoded APDU (returned
by cosemEncodeAXDR() function).

• void
Return Value

2.3.9 CosemDecodeAXDR

This function is used if user want library to decode a data communication response APDU(such as Get
response / Set Response / Action Response/AARQ/RLRQ) and return the result and data(if any) in
DLMS UNION(in case of Get response).
IntPtr CosemDecodeAXDR(byte securityPolicy,
byte[] serverSystemTitle,
byte[] authenticationKey,
byte[] encryptionKey,
byte[] globalbroadcastkey,
uint authTagLen,
uint cosemBufSize,
GENERAL_ATTR_METH_DESC_LIST generalAttrMethDescList,
ENCODED_PRIMARY_APDU apduData,
byte[] ClientSystemTitle,
SECURITY_PARAM securityParam,
byte[] publicKey,
ushort channelNo,
byte securitySuite,
byte enableLLCHeader);

Arguments
securityPolicy Security policy(this is used for the library to decide on the kind of protection to
be applied on APDU being generated)
meaning of each bit in ciphering type is as shown elow:
Bit Security policy
0 unused, shall be set to 0,
1 unused, shall be set to 0,
2 authenticated request,

Confidential
57
DLMS/COSEM Client SCL User Manual Version 3.15.1

3 encrypted request,
4 digitally signed request,
5 authenticated response,
6 encrypted response,
7 digitally signed response

serverSystemTitle_p Server system title required for library to generate IV required while verifying
protection

authenticationKey_p Authentication key used in protection

encryptionKey_p Encryption key used in protection

globalbroadcastkey Global broadcast key used to secure broadcast communication between a


DLMS client and several DLMS servers.

authTagLen Length of GMAC Authentication tag of APDUs used within Application


Association Possible values are 12 and 8 .

cosemBufSize
This is the size of the COSEM Application Layer buffer that hold the APDU's on
the function execution. This should be a large value to hold the largest possible
APDU that may be handled by the function.Example: 10000

generalAttrMethDescList
User can specify one or more cosem attribute /method descriptor which is
being referred in the APDU to be generated.

typedef struct CosemServiceSpecAttrMethDescList


{
KDEFS_ULONG numDescriptors;
GENERAL_ATTR_METH_DESC *generalAttrMethDesc;
KDEFS_UCHAR useWithList;
}GENERAL_ATTR_METH_DESC_LIST;
typedef struct ServiceIndepAttrMethDesc
{
OBISCODE * obis_p;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
void * serviceSpecificData_p;
} GENERAL_ATTR_METH_DESC;
serviceSpecificData_p shall be NULL when used in cosemDecodeAXDR()
function.

ApduData User have to pass the complete response PDU to decode, in this structure. If
the response in received in different block then full response need to be stored

Confidential
58
DLMS/COSEM Client SCL User Manual Version 3.15.1

in "cosemApdu" array pointer with each element in the array pointing to


different block data in the order of block number. The total number of blocks
need to be stored in "blockCount" element.
typedef struct EncodedPrimaryApdu
{
ENCODED_AXDR *cosemApdu;
KDEFS_USHORT blockCount;
} ENCODED_PRIMARY_APDU;
typedef struct EncodedAXDR
{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

clientSystemTitle_p will be used in case of block transfer. For example, while decoding an APDU
which is Get response wit data block, this function will also prepare Get request
next block for which client system title is required.

securityParam this will be used in case of block transfer. For example, while decoding an
APDU which is Get response wit data block, this function will also prepare Get
request next block for which client system title is required.

PublicKey public key to be used in signature verification

channelNo any ushort value given by user application that can be optionally used by
application in future to distinguish the client handle(especially in case of
push/event receipt)
securitySuite SecuritySuite of the security object used for the association. It Specifies the
security algorithms available.
0 for AES_GCM_128

1 for AES_GCM_128_ECDSA_256
2 for AES_GCM_256_ECDSA_384

enableLLCHeader Enabling this flag shall make function to decode packet with LLC header. This
can be used to generate packets for HDLC communication profile. Use 0 for IP
based communication.

IntPtr : points to DECODED_PRIMARY_DATA structure with list of


Return Value DLMS__UNION and Cosem Attribute / Method structures.

typedef struct DecodedPrimaryData


{
DLMS_UNION *DecodedData;
COSEM_ATTR_METH_DESC *cosemAttrMethDesc;
KDEFS_ULONG numDescriptors;
} DECODED_PRIMARY_DATA;

DLMS_UNION *DecodedData => list of DLMS_UNION each containing

Confidential
59
DLMS/COSEM Client SCL User Manual Version 3.15.1

data corresponding to one cosem attribute descriptor

COSEM_ATTR_METH_DESC *cosemAttrMethDesc => list of


COSEM_ATTR_METH_DESC each containing one cosem attribute
descriptor

numDescriptors => length of DLMS_UNION* list and


COSEM_ATTR_METH_DESC* list.

2.3.10 CleanupDecodedAXDR

This function must be called after the cosemDecodeAXDR() function call, to free the memory allocated
by library during cosemDecodeAXDR() function. This function must be called to enable the library to
clean-up the memory used. Client user can call this function irrespective of the result(Success/Failure)
returned by cosemDecodeAXDR().

Prototype

void cleanUpDecodeAXDR(IntPtr decodedData);

Arguments
decodedData pointer returned by cosemDecodeAXDR function.
• void
Return Value

2.3.11 cosemDecodeCompactFrameData
This function must be called after the cosemDecodeAXDR() function call, to free the memory allocated by library
during cosemDecodeAXDR() function. This function must be called to enable the library to clean-up the memory
used. Client user can call this function irrespective of the result(Success/Failure) returned by
cosemDecodeAXDR().

IntPtr cosemDecodeCompactFrameData(byte service,


COMPACT_FRAME_ASN_LIST asnList,
VARVALUE serviceSpecificData,
DLMS_UNION dlmsUnionforS2 );

Arguments

Confidential
60
DLMS/COSEM Client SCL User Manual Version 3.15.1

service 1 for Get(if compact frame was received as Get response)

2 for Push(if compact frame was received as Push Data Notification callback)

asnList List of ASN1 structures (each structure having template ID and ASN1 string)

ServiceSpecificData DLMS_UNION pointer (in case of get) or VARVALUE pointer contained in the inner
structure of PUSH_STR (in case of push) containing compact frame.

Null pointer : unknown error


Return Value Non zero IntPtr pointer : The first element of the DLMS_UNION structure is a
“result” value that indicates success or failure. The values in the proper fields of
the structure are valid only if the ‘result’ field is 0 indicating success.
Library updates result code in “result” variable inside DLMS_UNION structure.
Result code 0 => success In this case Client user shall fetch data from appropriate
sub-structure according to the interface class requested.
• Result code non zero => error. See Appendix A for more details of error code

• Note:- PUSH_STR is designed to have data type of structure of length 2, with second element hold
the push data (varvalue). This element (varvalue) contains data in structure format with each inner
element of structure hold the data of each entry in push_object_list. User need to identify the entry
which contains compact frame and need to pass this element as ServiceSpecificData. If User pass
invalid data then function return negative response.
Eg: For push this argument can be
VARVALUE ServiceSpecificData;
ServiceSpecificData =
(VARVALUE*)pushPtr->varvalue[0].value_p;
Assume that zero indexed element hold the compact frame data.

2.3.12 cleanDecodedCompactFrameData

After every cosemDecodeCompactFrameData() function, user shall call cleanDecodedCompactFrameData() to


free memory allocated inside cosemDecodeCompactFrameData(). The argument passed is the DLMS_UNION
pointer which was returned by cosemDecodeCompactFrameData().

Prototype

IntPtr cleanDecodedCompactFrameData (IntPtr decodedData);

Arguments
decodedData DLMS_UNION pointer was returned by cosemDecodeCompactFrameData().


Return Value

Confidential
61
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.13 getSystemTitleFromPushNotification

This function is used to get system title from a Data notification APDU.
Prototype

IntPtr getSystemTitleFromPushNotification(byte[] APDU,


byte[]serverSystemTitle,
IntPtr serverSystemTitlePresent);

Arguments
APDU Data notificaiton APDU input to library as byte array

serverSystemTitle library will search for system title in received data notification APDU and
if found, will update in the memory indicated in this argument

serverSystemTitlePresent Flag updated by library to indicate whether received APDU contain


system title or not. Since system title is an optional field when this flag=0
it means received APDU is a valid data notification request but does not
contain system title.
• zero if success, non zero if failed
Return Value

2.3.14 cleanUpencodeComHeader
This function is used to clear the memory allocated by encodeComProfileParams().User need to be
aware that after this function call, the pointer and memory created by library during
encodeComProfileParams() will not more be available

Prototype

void cleanUpencodedComHeader(IntPtr encodedHdrInfo);

Arguments
encodedHdrInfo pointer returned by library in encodeComProfileParams()

• void
Return Value

Confidential
62
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.15 encodeComProfileParams
This function is used to encode communication profile header. Communication profile may be either of the
following two :
 Wrapper header (Cosem Transport layer) only
 Gateway header and Wrapper header
If the function succeeds, library will return the header which application can prefix to the
APDU(generation of APDU need to be done separately using CosemEncodeAXDR or encodeAARQ
or encodeRLRQ functions).

Prototype

IntPtr encodeComProfileParams(byte comProfile,


ushort apduLen,
ushort wPortClient,
ushort wPortServer,
byte netWorkID,
byte phyAddLen,
IntPtr phyAddr);

Arguments
comProfile Any of the following three values
3 : TCP
4: UDP
9 : GATEWAY
apduLen COSEM APDU Length

wPortClient Wrapper Client ID

wPortServer Wrapper Server ID

netWorkID network ID for Gateway protocol

phyAddLen 1 byte – length(number of octets) of physical address in gateway header. This


argument will be used while encoding gateway header. If commProfile = 3(TCP)
or 4(UDP), this argument value can be zero
phyAddr Byte array – Physical address(octet string) to be encoded in gateway header.
This argument will be used while encoding gateway header. Size of this string
shall be same as specified in “PhyAddrLen” argument. If commProfile = 3(TCP)
or 4(UDP), this argument value can be null string
• zero if success, non zero if failed
Return Value

Confidential
63
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.16 decodeComProfileParams
This function is used to decode an APDU which contain communication profile header(either wrapper
header or both wrapper header and Gateway header
Prototype

IntPtr decodeComProfileParams(COM_HDR_ENC_DATA
decodeComHdr);

Arguments
decodeComHdr COM_HDR_ENC_DATA decodeComHdr - structure containing

buf_p[] : APDU prefixed with communication profile Header(this can be


either wrapper header alone or wrapper header | gateway header)
bufLen : size of APDU with prefix
• IntPtr pointing to strcture as below:
Return Value • typedef struct decodeHdrParams
• {
• WRAPPER_HDR *wrapperHdr; // a structure containing wrapper
header info viz wrapper client id, wrapper server id and a flag indicating
whether wrapper header is present or not
• GATEWAY_HDR *gatewayHdr; // a structure containing gateway
header info viz network id, physical id length, physical id(string) and a
flag indicating whether gateway header is present or not
• KDEFS_USHORT APDULen; //Length of APDU(after deducting
wrapper header and gateway header(if any)
• KDEFS_USHORT apduStartPosition; //position in buf_p[]
argument where APDU starts(zero based index)
• KDEFS_UCHAR apduType; // 0xE6(indicates request) or
0xE7(indicates response). This can be useful for application to identify
Data notification as it is the only packet from meter which would have
apduType=0xE6
• KDEFS_UCHAR comProfile; //3 for TCP and UDP or 9 for
Gateway
• KDEFS_USHORT result; //zero is success, non-zero is failure
• }DECODE_HDR_DATA;

Confidential
64
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.17 cleanUpdecodedComHeader
This function is used to clear the memory allocated by decodeComProfileParams(). User need to be
aware that after this function call, the pointer and memory created by library during
decodeComProfileParams() will not more be available.
Prototype

void cleanUpdecodedComHeader(IntPtr decodedhdrInfo);

Arguments
decodedhdrInfo DECODE_HDR_DATA returned in decodeComProfileParams()

void
Return Value

2.3.18 EncodeHDLCrequest

User can generate HDLC packets from the application layer packet using the EncodeHDLCrequest().
The application layer packet with LLC header is the expected input (Only for I / UI frame). The function
can also used to generate other HDLC frames like RR frame, SNRM, DISC etc.

Prototype

IntPtr encodeHDLCrequest(byte addressSize,


ushort clntID,
ushort serverID,
ushort devAddr,
byte windowRx,
byte windowTx,
ushort infoFieldLenRx,
ushort infoFieldLenTx,
byte serviceClass,
ushort linkBufSz,
ENCODED_AXDR apduData,
byte frameType,
byte[] rrr,
byte[] sss);

Confidential
65
DLMS/COSEM Client SCL User Manual Version 3.15.1

Arguments
addressSize Number of bytes used for addressing the server. Possible values are 1, 2 or 4.
When a value of 1 is specified, the destination address (server-address)
contains only 1 byte which contains the Upper HDLC address of the meter. This
can be used for point-to-point communication. In case of a multi-drop scenario
(daisy
chained meters), the address must also specify the lower HDLC or device-
address to identify which physical device is being addressed. This can use a 2-
byte or a 4-byte destination address. In case of a 2-byte address, the server
address has 1-byte Upper
HDLC address and 1-byte Lower HDLC address. In case of 4-byte addressing,
the server-address contains 2-bytes Upper and 2- bytes Lower HDLC
addresses. Example: 1

clntID
Client id for current association. This is the ID of DLMS client. The
client-ID is used by the server to determine which association in the
addressed Logical-device is to be activated. A value of 16 (0x10) is
predefined by the DLMS standard to specify a Public Access client. Any
DLMS server must

serverID Upper HDLC address of the server. This identifies which Logical-device
in the addressed-meter is being queried. Any DLMS server will provide at
least one Logical device with an address of 1, which indicates the
Management Logical device Example: 1

devAddr Lower HDLC address of the server. This is the physical-device address of
the meter. Please note that a physical device can contain multiple logical
devices identified by unique
Upper HDLC addresses In turn, each Logical device can support
multiple associations (with different object lists and access-rights) defined
by unique client-IDs Example: 0

windowRx Number of windows receive. This identifies the number of segmented frames
that can be received at a go by this client, before requiring to send a RR
(Request-Ready)
handshake. The DLMS default value is 1. Example: 1

windowTx Number of windows transmit. This identifies the number of segmented frames
that can be transmitted at a go by this client, before requiring a RR (Request-
Ready) handshake from the server. The DLMS default value is 1. Example: 1

infoFieldLenRx Information field length receive. This defines the size of the Info-field part of a
received DLMS frame. The info-field is the carrier of all COSEM data destined to
be processed by the upper Layers. The DLMS default value is 128. Example:
128

Confidential
66
DLMS/COSEM Client SCL User Manual Version 3.15.1

infoFieldLenTx Information field length transmit. This defines the size of the Info-field part of a
transmitted DLMS frame. The info-field is
the carrier of all COSEM data destined to be processed by the upper Layers.
The DLMS default value is 128. Example: 128

serviceClass Shall set 1 for I frame. 0 for UI frame.

linkBufSz HDLC/ IP wrapper buffer size. This is the maximum number of bytes which
needs to be buffered in link layer for both transmission as well as reception. User
should set this value judiciously depending on server's Maximum APDU/block
size transmit/receive. A recommended value can be Maximum Transmit/Receive
APDU size (in case of HDLC HDLC protocol overhead 17 bytes also shall be
added to APDU size to calculate LinkBufSize). Example: 1024

apduData Application layer data along with LLC header shall pass here. This
argument is only applicable to I-frame. Application layer frame (AARQ,
Get Request, Set Request, Action request, .etc) with LLC header (0xE6,
0xE6, 0x00) shall pass here along with number pf bytes.

Ex: E6 E6 00 C0 01 C1 00 08 00 00 01 00 00 FF 02 00, Length =16

frameType Type of frame to encode. Supported values are.


0: I Frame (AARQ, Get, Set, Action requests)
1: RR Frame
2: SNRM frame
3: DISC frame

rrr N( R ), Receive sequence number to use in the HDLC packet.

sss N( S ), Send sequence number to use in HDLC packet

IntPtr :
Return Value
points to.ENCODED_PRIMARY_APDU * Structure with list of structures(each
structure contain one APDU block); length of list is indicated in blockCount .

IntPtr.zero or a valid pointer. If valid pointer, it can be converted to


ENCODED_PRIMARY_APDU structure. The structure includes the number of
blocks available in the packet based on the information size. Only I-frame type
expects more than 1 block. The structure also include individual blocks data with
length field. If the “application layer packet size” + “LLC header” length is more
than the HDLC information size sent, then the function shall encode the
information in multiple blocks.

typedef struct PrepareApduParams{


ushort blockCount;
IntPtr cosemApdu_p;
} ENCODED_PRIMARY_APDU;

Confidential
67
DLMS/COSEM Client SCL User Manual Version 3.15.1

typedef struct EncodedAXDR{


KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

2.3.19 cleanUpEncodedHDLC

• The function used to release the memory allocated by the encodeHDLCrequest() function.
Prototype

void cleanUpEncodedHDLC(IntPtr preparedAPDU);

Arguments
preparedAPDU This is a pointer to a structure variable which hold the encoded APDU
(returned by encodeHDLCrequest() function).

void
Return Value

2.3.20 DecodeHDLCrequest

User shall extract the application layer+LLC header content from I /UI frames using
DecodeHDLCrequest() function. This function also tells the frame type and information included in it
(Receive sequence number of RR frame, Information size and window size of RR frame, etc). The
function shall return only 1 application layer packets. Also handle segmented I frame.

IntPtr DecodeHDLCrequest(ENCODED_PRIMARY_APDU apduData,


byte addressSize,
ushort clntID,
ushort serverID,
ushort devAddr,
byte windowRx,
byte windowTx,
ushort infoFieldLenRx,
ushort infoFieldLenTx,
uint cosemBufSize,
byte[] rrr,
byte[] sss)


• Arguments

Confidential
68
DLMS/COSEM Client SCL User Manual Version 3.15.1

apduData User have to pass the complete response PDU to decode, in this structure. If the
response in received in different HDLC segments then full response need to be
stored in "apduData" array pointer with each element in the array pointing to
different block data in the order of sequence number. The total number of blocks
need to be stored in "blockCount" element. Partial block input shall return partial
data response.

addressSize Number of bytes used for addressing the server. Possible values are 1, 2 or 4.
When a value of 1 is specified, the destination address (server-address)
contains only 1 byte which contains the Upper HDLC address of the meter. This
can be used for point-to-point communication. In case of a multi-drop scenario
(daisy
chained meters), the address must also specify the lower HDLC or device-
address to identify which physical device is being addressed. This can use a 2-
byte or a 4-byte destination address. In case of a 2-byte address, the server
address has 1-byte Upper
HDLC address and 1-byte Lower HDLC address. In case of 4-byte addressing,
the server-address contains 2-bytes Upper and 2- bytes Lower HDLC
addresses. Example: 1

clntID Number of bytes used for addressing the server. Possible values are 1, 2 or 4.
When a value of 1 is specified, the destination address (server-address)
contains only 1 byte which contains the Upper HDLC address of the meter. This
can be used for point-to-point communication. In case of a multi-drop scenario
(daisy
chained meters), the address must also specify the lower HDLC or device-
address to identify which physical device is being addressed. This can use a 2-
byte or a 4-byte destination address. In case of a 2-byte address, the server
address has 1-byte Upper
HDLC address and 1-byte Lower HDLC address. In case of 4-byte addressing,
the server-address contains 2-bytes Upper and 2- bytes Lower HDLC
addresses. Example: 1
Client id for current association. This is the ID of DLMS client. The client-ID is
used by the server to determine which association in the addressed Logical-
device is to be activated. A value of 16 (0x10) is predefined by the DLMS
standard to specify a Public Access client. Any DLMS server must
provide at least one Public-Access association. Other Client IDs supported shall
be obtained from meter manufacturer or from
respective project/companion specification. Example: 16

serverID Upper HDLC address of the server. This identifies which Logical-device in the
addressed-meter is being queried. Any DLMS server will provide at least one
Logical device with an address of 1, which indicates the Management Logical
device Example: 1

devAddr Lower HDLC address of the server. This is the physical-device address of the
meter. Please note that a physical device can contain multiple logical devices
identified by unique
Upper HDLC addresses In turn, each Logical device can support

Confidential
69
DLMS/COSEM Client SCL User Manual Version 3.15.1

multiple associations (with different object lists and access-rights) defined by


unique client-IDs Example : 0

windowRx Number of windows receive. This identifies the number of segmented frames
that can be received at a go by this client, before requiring to send a RR
(Request-Ready)
handshake. The DLMS default value is 1. Example: 1

windowTx Number of windows transmit. This identifies the number of segmented frames
that can be transmitted at a go by this client, before requiring a RR (Request-
Ready) handshake from the server. The DLMS default value is 1. Example: 1

infoFieldLenRx Information field length receive. This defines the size of the Info-field part of a
received DLMS frame. The info-field is the carrier of all COSEM data destined to
be processed by the upper Layers. The DLMS default value is 128. Example:
128
infoFieldLenTx Information field length transmit. This defines the size of the Info-field part of a
transmitted DLMS frame. The info-field is
the carrier of all COSEM data destined to be processed by the upper Layers.
The DLMS default value is 128. Example: 128

serviceClass Shall set 1 for I frame.

cosemBufSize Application size buffer size. This is the maximum number of bytes which needs
to be buffered in application layer for both transmission as well as reception.
User should set this value judiciously depending on server's Maximum APDU. A
recommended value can be Maximum Transmit/Receive APDU size. Example:
1024

Rrr N( R ), Receive sequence number of processed frame. Only valid for RR & T
frame

Sss N( S ), Send sequence number of processed I frame.

intPtr points to.ENCODED_PRIMARY_APDU * Structure with list of


Return Value
structures(each structure contain one APDU block); length of list is indicated in
blockCount .

NULL or valid pointer. The pointer to the structure shall tell you the number of
blocks available in the structure. Only 1 block expected on return. The structure
also includes individual blocks with length field. Data in the buffer on index 0
indicate type of frame. 1- RR frame, 2- I Frame, 3- UA frame, 4 – Partial I frame,
5- UI frame.
In case of complete I-frame segments, full application layer data shall
return with LLC header. 1st byte shall be 2, indicate I frame. Followed by
LLC header and application layer data.

Confidential
70
DLMS/COSEM Client SCL User Manual Version 3.15.1

Eg: 02 E6 E7 00 C4 01 C1 00 0F 01, Length = 10.


In case of partial I frame, buffer shall return the type as 4 followed by
receive and sent sequence numbers.
Eg: 04 00 00
In case of UA frame, buffer shall return the type as 3 followed by
negotiated information size send (2 bytes), negotiated information size
receive (2 byte), Negotiated window size receive (1 byte), Negotiated
window size sent (1 byte)
Eg: 03 01 00 01 00 01 01
In case of RR frame, buffer shall the return type as 1 followed by receive
sequence number and sent sequence number.

typedef struct PrepareApduParams{


ushort blockCount;
IntPtr cosemApdu_p;
} ENCODED_PRIMARY_APDU;
typedef struct EncodedAXDR{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

2.3.21 CleanUpEncodedAXDR

• The function used to release the memory allocated by the decodeHDLCrequest() function.
Prototype

void cleanUpDecodedHDLC(IntPtr preparedAPDU);

Arguments
preparedAPDU This is a pointer to a structure variable which hold the encoded APDU (returned
by decodeHDLCrequest() function).

void
Return Value

2.3.22 Sendpacket

The function used to release the memory allocated by the decodeHDLCrequest() function.

Confidential
71
DLMS/COSEM Client SCL User Manual Version 3.15.1

Prototype

byte[] Sendpacket(IntPtr clientHandle,


byte[] data,
uint waitingduration,
ushort resplen);

Arguments

clientHandle Handle returned by initClient()


data The data to send over existing connection.
waitingduration Maximum duration to be wait for response. Value 0 make the function to
return immediately after sending data.
resplen Expected length of response. Value 0 will make function to wait for full
waiting duration for response. In other cases, the function will return on
receiving resplen bytes response.
Response data.
Return Value

2.3.23 registerWrapperAppDataCallback

The function used register the callback to notify the received bytes on existing TCP/UDP connection.
Prototype

registerWrapperAppDataCallback(APPLNDATA_CALLBACK callbackPointer)

Arguments
callbackPointer The prototype of callbackPointer is
public delegate ushort APPLNDATA_CALLBACK(IntPtr applnDataBuf,
uint appDataLen,
IntPtr clientHandle,
byte wait,
ushort recvPortClient,
ushort recvWPortServer,
byte result).

Confidential
72
DLMS/COSEM Client SCL User Manual Version 3.15.1

The applnDataBuf hold the recived bytes on the existing TCP/UDP


connection. The appDataLen give the number of bytes. The clientHandle
is the handle of existing channel. The recvPortClient and recvPortServer
hold the client and server addresses of recieved packet. The result filed
indicate if the recived packet with valid DLMS wrapper header.

2.3.24 Call Sequence(HDLC)


The function call sequence on HDLC communication is given below.
1. EncodeHDLCrequest() to generate SNRM
2. DecodeHDLCrequest() to decode UA frame. Return NULL for DM frame.
3. EncodeHDLCrequest() to encode AARQ request.
4. DecodeHDLCrequest() to decode AARE response and extract application layer frame + LLC
Header. Remove 1st 4 byte and decode application layer frame. This step may repeat if the packet
received with segmentation
5. EncodeHDLCrequest() to encode Get request.
6. DecodeHDLCrequest() to decode Get response and extract application layer frame + LLC Header.
Remove 1st 4 byte and decode application layer frame. This step may repeat if the packet received
with segmentation.
7. EncodeHDLCrequest() to send DISC frame.
8. DecodeHDLCrequest() to decode UA response. Return NULL for DM frame.

2.3.25 setGatewayParams
This function shall be called to initialize DLMS Gateway profile header parameters when gateway
profile is being used in regular synchronous mode of library(i.e. when not using encodeXXX functions).
Prototype

ushort setGatewayParams(IntPtr clientHandle,


byte NetworkId,
byte PhyAddrLen,
IntPtr PhyAddr,
byte srcPhyAddrLen,
IntPtr srcPhyAddr);

Arguments
clientHandle Handle returned by initClient()

NetworkId 1 byte network ID to be used in GW Header

Confidential
73
DLMS/COSEM Client SCL User Manual Version 3.15.1

PhyAddrLen 1 byte – length(number of octets) of physical address in gateway header.


This argument will be used while encoding gateway header.
PhyAddr Byte array – Physical address(octet string) to be encoded in gateway
header. This argument will be used while encoding gateway header. Size
of this string shall be same as specified in “PhyAddrLen” argument
srcPhyAddrLen 1 byte – length(number of octets) of physical address in gateway header.
This argument will be used while decoding gateway header
srcPhyAddr Byte array – Physical address(octet string) to be encoded

2.3.26 useDedicatedCiphering
This is an optional function called before a data communication service( Get/ Set/ Action requests) to
change ciphering type( from dedicated ciphering to global ciphering or vice versa).Note that this
setting will be effective for one data communication service only.

Prototype

ushort useDedicatedCiphering(IntPtr clientHandle,


byte dedicatedSupport);

Arguments
clientHandle Handle returned by initClient()

dedicatedSupport byte – KDEFS_TRIUE for dedicated key usage and KDEFS_FALSE for
global key usage
Return value zero if success, non zero if failed

2.3.27 cosemEncodeRLRQ
This function is used if user want library to prepare a RLRQ APDU and return the APDU back to
user(instead of following
IntPtr the usual Client state machine
cosemEncodeRLRQ(byte appCtxt,where in library send the request to server by
library itself).. byte authMech,
IntPtr authenticationKey_p,
Prototype
IntPtr encryptionKey_p,
IntPtr dedEncKey_p,
IntPtr globalbroadcastkey,
byte securityPolicy,
byte secSuite,
byte authTagLen,
IntPtr clientSystemTitle_p,
IntPtr serverSystemTitle_p,
ushort maxApduSizeRecv,
SECURITY_PARAM securityParam,
uint conformance,
byte reason,
Confidential
byte dedicatedKeyPresent,
74
uint cosemBufSize,
byte serviceClass,
byte[] privateKey,
ushort channelNo
byte enableLLCHeader);
DLMS/COSEM Client SCL User Manual Version 3.15.1

Argument
appContext Application context. Values can be 1, 2, 3 or 4. The
application context defines the referencing method to
be
used (LN or SN)
• 1 for LN Association with No ciphering
• 2 for SN Association with No ciphering
• 3 for LN Association with ciphering
• 4 for SN Association with ciphering.
authMech Authentication mechanism used. Values can be 0, 1,
2, 3, 4, 5, 6 or 7.
0 for Lowest Level Security (without password)
1 for Low Level Security (with static password)
2 for High Level Security (with coded password)
3 for High Level Security (with encrypted password
using md5 algorithm)
4 for High Level Security (with encrypted password
using sha-1 algorithm)
5 for High Level Security (with encrypted password
using GMAC algorithm)
6 for High Level Security (with encrypted password
using SHA-256 algorithm)
7 for High Level Security (with encrypted password
using ECDSA algorithm)
authenticationKey authentication key used for security policies 1 and 3.
This key is used in protecting APDUs exchanged
within application association. Also used for
processing challenge in HLS mechanism id 5.
encryptionKey Encryption key used for ciphered application
contexts and processing challenge in HLS mechanism
id 5. This key is used in protecting APDUs exchanged
within application association.

Confidential
75
DLMS/COSEM Client SCL User Manual Version 3.15.1

dedicatedKey dedicated key used for dedicated ciphering. It is a


symmetric key used within a single instance of an
Application Association
globalbroadcastkey
Global broadcast key used to secure broadcast
communication between a DLMS client and several
DLMS servers.

secPolicy Security policy for the association. Define the


security level policy (Security control and digital
signature) used in AARQ request.

meaning of each bit is as shown below:


•0 unused, shall be set to 0,
•1 unuse`d, shall be set to 0,
•2 authenticated request,
•3 encrypted request,
•4 digitally signed request,
•5 authenticated response,
•6 encrypted response,
•7 digitally signed response

secSuite SecuritySuite of the security object used for the


association.It Specifies the security algorithms
available.

0 for AES_GCM_128
1 for AES_GCM_128_ECDSA_256
2 for AES_GCM_256_ECDSA_384
authTagLen Length of GMAC Authentication tag of APDUs used
within Application Association
Possible values are
12(normal Authentication tag)
8(short Authentication tag)
clientSystemTitle Client System title
ServerSystemTitle_p Server System tile
maxApduSize This is the maximum APDU size that the client can
receive. This is used only in LN referencing contexts
that support Block transfer. In SN contexts a value of
0xFFFF can be specified.
0 := this is a special value in DLMS to indicate there is
no limit on PDU size received. It is recommended to
use this value only when necessary(i.e. Some servers
require client max receive PDU size to be 0)
secrtyParam NOTE: this is required only in case of

Confidential
76
DLMS/COSEM Client SCL User Manual Version 3.15.1

encryption/decryption.

typedef struct FrameCounter


{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;

typedef struct SecurityParam


{
KDEFS_UCHAR cipheringType;
FRAME_COUNTER_CFG *frameCounter;
KDEFS_UCHAR enbCompression;
KDEFS_UCHAR enablebroadcastkey;

}SECURITY_PARAM;

There are two methods to handle frame counters. In


first method, library will completely take care of frame
counters and user need not interfere at all. In second
method, user can pass frame counter values to library
which shall be used while applying protection. For
former method set “userCfg” to 0 and for latter
method, user shall set “userCfg” to 1 and also pass
frame counter value in “ frameCounterToUse”
variable. Along with the frame counter information, the
SecurityParam variable also contains the ciphering
type to be used in the request. Meaning of each bit is
as shown below:
•0 unused, shall be set to 0,

•1 unused, shall be set to 0,

•2 authenticated request,

•3 encrypted request,

•4 digitally signed request,

•5 authenticated response,

•6 encrypted response,
6th and 7th bit of security control byte is reserved for
key set and to enable or disable the compression
respectively.
If 6th bit is 0 or FALSE, it indicates Unicast key is
being used. If it is 1 or TRUE, Broadcast Key is being

Confidential
77
DLMS/COSEM Client SCL User Manual Version 3.15.1

used.
If 7th bit is 0 or FALSE, it indicates compression is
disabled and if 7th bit is 1 or TRUE, it indicates
compression is enabled.
conformance Proposed conformance to use in AARQ
reason Reason field in RLRQ
dedKeyFlag Set to enable dedicated key encoding in RLRQ
cosemBufSize This is the size of the COSEM Application Layer
buffer that hold the APDU's on the function execution.
This should be a large value to hold the largest
possible APDU that may be generated by the function.
Example: 10000
serviceClass 1 -> confirmed, 0->unconfirmeds
privateKey PrivateKey used for digital signing
channelNo any ushort value given by user application that can
be optionally used by application to distinguish the
client handle.
enableLLCHeader
Enabling this flag shall generate packet with LLC
header. This can be used to generate packets for
HDLC communication profile. Use 0 for IP based
communication.

Return
IntPtr pointing to structure Structure with list of structures(each structure contain
PREPARED_APDU one APDU block); length of list is indicated in
blockCount

typedef struct PrepareApduParams


{
ENCODED_AXDR *cosemPreparedApdu;
KDEFS_USHORT blockCount;
KDEFS_UCHAR curServiceType;
KDEFS_USHORT result;
} PREPARED_APDU;

typedef struct EncodedAXDR


{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

Confidential
78
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.28 processChallenge
This function is used if user want library to process the challenge based on the HLS authentication
mechanism and return the processed challenge back to user(instead of following the usual Client state
machine where in library send the request to server by library itself).

Prototype
IntPtr processChallenge(IntPtr plainText,
byte length,
IntPtr cipherText,
byte authMech,
IntPtr HLSKey_p,
IntPtr clientSystemTitle_p,
IntPtr ServerSystemTitle_p,
IntPtr encryptionKey_p,
IntPtr authenticationKey_p,
uint frameCounterToUse,
uint SignatureVerify,
byte securitySuite,
byte[] privateKey,
byte[] publicKey)

Argument
plainText The challenge string to process.
length Length of challenge
cipherText Processed challenge shall be available in this pointer. The
pointer shall have sufficient space to hold it the
processed challenge.
authMech Client system title used by the library to generate IV required
while applying protection. This parameter will be used
only if security policy demand
authentication/encryption to be applied.
HLSKey_p HLS secret
clientSystemTitle_p Client system title
ServerSystemTitle Server system title
encryptionKey Encryption key
authenticationKey_p Authentication key.
frameCounterToUse Frame counter. Applicable only or authentication mechanism

SignatureVerify Flag indicating whether HLS7 signature verification


required/not
securitySuite SecuritySuite of the security object used for the
association. It Specifies the security algorithms

Confidential
79
DLMS/COSEM Client SCL User Manual Version 3.15.1

available.

0 for AES_GCM_128
1 for AES_GCM_128_ECDSA_256
2 for AES_GCM_256_ECDSA_384
privateKey Privatekey used for digital signing
PublicKey Publickey used for signature verification
Return
void

2.3.29 setFrameCounter

This is an optional function using which user application can set or change frame counter used by
library to build IV which is used while applying protection to APDUs while sending.

Prototype

void setFrameCouter(IntPtr clientHandle,


uint frameCounterToUse );

Argument
clientHandle Handle returned by initClient()
frameCounterToUse Frame counter to be used - 32 bit integer
value
Return

2.3.30 cleanPushData
After using push data received via Push call back function, user shall call cleanPushData() to free
dynamically allocated memory.

Prototype

void cleanPushData(PUSH_STR decodedData)

Argument
PUSH_STR decodedData Push structure

Confidential
80
DLMS/COSEM Client SCL User Manual Version 3.15.1

Return

2.3.31 getAssociationParameters
This function shall be called by user to get specific application layer and link layer parameters of
current association. The argument passed is the handle returned by initClient(). The return value is a
structure holding the parameters of current association.

Prototype
IntPtr getAssociationParameters(IntPtr ClientHandle);

Argument
IntPtr ClientHandle Handle returned by initClient
Return

2.3.32 cleanEventData
After using event data received via Event call back function, user shall call cleanEventData() to free
dynamically allocated memory.

Prototype

void cleanEventData(IntPtr eventData, ushort len);

2.3.33 getEvent
Call back function registered using registerEventCallback() will be called by library when one / more
events are received. Call back function is only meant to notify user-application about receipt of event
and event information is not send in call back function. Client user-application shall retrieve events
separately by calling API : getEvent().

Prototype
getEvent(IntPtr clientHandle, ushort len);

Confidential
81
DLMS/COSEM Client SCL User Manual Version 3.15.1

2.3.34 triggerEventNotification
This function shall be called by user to get specific application layer and link layer parameters of
current association. The argument passed is the handle returned by initClient(). The return value is a
structure holding the parameters of current association.

Prototype

IntPtr getAssociationParameters(IntPtr ClientHandle);

Argument
IntPtr ClientHandle Handle returned by initClient
Return

2.3.35 imageTransfer

Prototype
ushort imageTransfer(IntPtr clientHandle,
byte cipheringType,
byte clientID,
IntPtr servLogID_p,
IntPtr servPhyID_p,
byte serverAddrLen,
byte broadCastFlag,
ushort numServers,
byte appContext,
byte authMechLevel,
IntPtr authValue_p,
byte authValLen,
IntPtr authenticationKey_p,
IntPtr encryptionKey_p,
IntPtr dedEncKey_p,
byte securityPolicy,
IntPtr clientSystemTitle_p,
ushort clientMaxReceivePduSz,
[MarshalAs(UnmanagedType.LPStr)] string fileName,
IntPtr identifierName,
OBISCODE obj,
ushort delay);

Arguments:

IntPtr clientHandle
byte cipheringType
byte clientID
IntPtr servLogID_p
IntPtr servPhyID_p

Confidential
82
DLMS/COSEM Client SCL User Manual Version 3.15.1

byte serverAddrLen
byte broadCastFlag
ushort numServers
byte appContext
byte authMechLevel
IntPtr authValue_p
byte authValLen
IntPtr authenticationKey_p
IntPtr encryptionKey_p
IntPtr dedEncKey_p
byte securityPolicy
IntPtr clientSystemTitle_p
ushort clientMaxReceivePduSz
[MarshalAs(UnmanagedType.LPStr)] string fileName
IntPtr identifierName
OBISCODE obj
ushort delayIntPtr clientHandle
byte cipheringType
byte clientID
IntPtr servLogID_p
IntPtr servPhyID_p
byte serverAddrLen
byte broadCastFlag
ushort numServers
byte appContext
byte authMechLevel
IntPtr authValue_p
byte authValLen
IntPtr authenticationKey_p
IntPtr encryptionKey_p
IntPtr dedEncKey_p
byte securityPolicy
IntPtr clientSystemTitle_p
ushort clientMaxReceivePduSz
MarshalAs(UnmanagedType.LPStr)] string fileName
IntPtr identifierName
OBISCODE obj
ushort delay

Return
zero if success, non zero if failed

2.4 Structures and Unions

2.4.1 DLMS_UNION_CS

The DLMS_UNION_CS structure is not a UNION, but a structure with all supported Interface-Class object
structures within. This structure is the means to pass data between the user-application and the library. In case
of Get/Read operations, the structure is allocated, filled-in and passed to the user-application from the library. In
case of Set/Write operations, the user-application must allocate, fill-in and pass the structure to the library.
Please refer the corresponding IC files file for complete structure definitions.

Confidential
83
DLMS/COSEM Client SCL User Manual Version 3.15.1

In case of Set/Write the user-application must also handle the freeing of memory allocated to the structure (In
Get/Read, simply calling the cleanupMemory() function in the library will do)

Definition
public struct DLMS_UNION_CS
{
public byte result;
public GENIC_CS genericIc;
public DATA_CS data;
public REGISTER_CS register;
public EXTREGISTER_CS extRegister;
public DEMANDREG_CS dmdRegister;
public REGISTER_ACTIVATION_CS regAct;
public PROFILE_CS profile;
public CLOCK clock;
public SCRIPT_TABLE_CS scriptTable;
public SCHEDULE_CS schedule;
public SPECDAYTABLE_CS specDaysTable;
public ACTIVITYCALENDAR_CS actCal;
public REG_MONITOR_CS regMonitor;
public ASSOC_LN_CS assocLN;
public ASSOC_SN_CS assocSN;
public SAPASSIGN_CS SAPAssign;
public IMAGE_TRANSFER_CS imageTransfer;
public SINGLEACTIONSCHEDULE_CS SingleActionSchedule;
public IECLOCALPORT_CS IECLocal;
public MBUS_SLAVEPORT_SETUP mbusSlavePortSetup;
public UTILITY_TABLE_CS utilityTable;
public PSTNMODEMCONFIG_CS PSTNmc;
public PSTN_AUTOANSWER_CS PSTNAutoAnswer;
public AUTOCONNECT_CS autoConnect;
public HDLC_SETUP hdlcSetup;
public PUSH_SETUP_CS pushSetup;
public TCPUDPSETUP tcpUdpSetup;
public IPv4SETUP_CS ipv4;
public IPv6_SETUP_CS ipv6;
public ETHERNETSETUP_CS ethernetSetup;
public PPP_SETUP_CS pppSetup;
public GPRSMODEMSETUP_CS GPRSModemSetup;
public SMTPSETUP_CS SMTPSetup;
public GSM_DIAG_CS gsmDiag;
public LLC432SETUP_CS LLC432Setup;
public LLC80222T1SETUP_CS LLC80222T1Setup;
public LLC80222T2SETUP_CS LLC80222T2Setup;
public LLC80222T3SETUP_CS LLC80222T3Setup;
public REGISTER_TABLE_CS registerTable;
public SECURITY_SETUP securitySetup;
public COMPACT_DATA_CS compactData;
public PARAMETER_MONITOR_CS paramMonitor;
public SENSOR_MANAGER_CS sensorManager;
public DISC_CONTROL discControl;
public LIMITER_CS limiter;

Confidential
84
DLMS/COSEM Client SCL User Manual Version 3.15.1

public MBUS_CLIENT_CS mbusClient;


public WIRELESS_MODEQ_CHANNEL_CS wirelessModeQChannel;
public MBUS_MASTERPORT_SETUP mbusMasterPortSetup;
//public EXTENDED_DATA_CS extendedData;
public CL_432_SETUP cl432Setup;
public PRIME_PLC_PHY_COUNTER primePLCPhyCounter;
public PRIME_PLC_MAC_SETUP primePLCMACSetup;
public PRIME_PLC_MAC_FUNC_PARAMS_CS primePLCMACFuncParams;
public PRIME_PLC_MAC_COUNTER primePLCMACCounter;
public PRIME_PLC_MAC_NETWORK_ADMIN_DATA_CS primePLCMACNwkAdminData;
public PRIME_PLC_APPL_IDENT_CS primePLCApplIdent;
public G3_PLC_MAC_COUNTER g3PLCMacCounter;
public G3_PLC_MAC_SETUP_CS g3PLCMacSetup;
public G3_PLC_ADAPT_SETUP_CS g3PLCAdaptSetup;
public ACCOUNT_OBJ_CS accountObject;
public CREDIT_OBJ creditObject;
public CHARGE_OBJ_CS chargeObject;
public TOKEN_OBJ_CS tokenObject;
public ZIGBEE_SAS_JOIN_OBJECT zigbeeSASJoinObject;
public ZIGBEE_SAS_FRAGMENTATION_OBJECT zigbeeSASFragmentationObject;
public ZIGBEE_SETC_CONTROL_OBJECT_CS zigbeeSETCControlObject;
public ZIGBEE_TUNNEL_SETUP_CS zigbeeTunnelSetup;
public ZIGBEE_SAS_STARTUP_OBJECT_CS zigbeeSASStartupObject;
public RATE_PLAN ratePlan;
}

2.4.2 ACTION_UNION_CS

The ACTION_UNION_CS structure is similar in procedure to the Set/Write operation. (In fact when using SN
referencing the executeAction() method actually sends a Write command). When calling executeAction(), the
user-application must allocate, fill-in and pass this structure to the library.

Please refer the corresponding IC files for complete structure definitions.

Definition
public struct ACTION_UNION_CS
{
public GENERIC_IC_ACTION_CS genAction;
public REG_ACTN regAct;
public EXT_REG_ACTN exRegAct;
public DMD_REG_ACT dmdRegAct;
public REG_ACT_ACT_CS regActivationAct;
public PROF_ACTN profAct;
public CLOCK_ACTN clockAct;
public SCR_TAB_ACTN scrAct;
public SCHEDULE_ACTN_CS schedActn;
public SPEC_DAY_TAB_ACTN spDayAct;
public ACT_CAL_ACTN actCalAct;
public ASSOC_LN_ACTN_CS assocLNAct;
public ASSOC_SN_ACTN_CS assocSNAct;

Confidential
85
DLMS/COSEM Client SCL User Manual Version 3.15.1

public SAP_ASSIGN_ACTN_CS sapAct;


public IPv4_SETUP_ACTN ipv4Act;
public IMG_TX_ACTN_CS imgTxAct;
public REG_TABLE_ACTN regTableAct;
public PUSH_ACTN pushAct;
public SENSOR_MANAGER_ACTN sensorManagerAct;
public DISC_CONTROL_ACTN discCntrlAct;
public SECURITY_CONTROL_ACTN_CS securityCntrlAct;
public MBUS_CLIENT_ACTN_CS mbusClientAct;
public EXT_DATA_ACTN extDataAct;
public CL432SETUP_ACTN cl432SetupActn;
public PRIMEPLC_PHY_LYR_CNTR_ACTN primePLCPhyLyrCntrActn;
public PRIMEPLC_MAC_CNTR_ACTN primePLCMACCntrActn;
public PRIMEPLC_NWK_ADMIN_DATA_ACTN primePLCNwkAdminDataActn;
public G3_PLC_MAC_COUNTER_ACTN g3PLCMacCounterAct;
public G3_PLC_MAC_SETUP_ACTN_CS g3PLCMacSetupAct;
public ACCOUNT_ACTN accountObj;
public CREDIT_ACTN creditObj;
public CHARGE_ACTN_CS chargeObj;
public TOKEN_ACTN_CS tokenObj;
public COTS_OBJ_ACTN coTsObjAct;
public ZIGBEE_DRLC_CLUSTER_OBJECT_ACTN zigbeeDRLCClusterObjAct;
public BLOCK_TARIFF_CONFG_OBJ_ACTN blockTariffConfgobjAct;
public ZIGBEE_SETC_CONTROL_OBJECT_ACTN_CS zigbeeSETCControlObjActn;
}
2.5 Security Implementation
The user is expected to implement the security suite in order to avail Data Access
Security(HLS Authentication Mechanisms) or Data Transport Security(Ciphering) features. Its
done by defining the following functions, which are available as templates in security.cs file
available in the sample application folder

encrypt/decrpyt
encrypt(byte encMeth,
IntPtr key,
ushort keyLen,
IntPtr plainText_p,
uint ptLen,
IntPtr cipherText_p,
IntPtr initialisationVector,
ushort ivLen,
IntPtr aad,
uint aadLen,
IntPtr authTag,
uint authTagLen)

decrypt(byte encMeth,

Confidential
86
DLMS/COSEM Client SCL User Manual Version 3.15.1

IntPtr key,
ushort keyLen,
IntPtr plainText_p,
uint ptLen,
IntPtr cipherText_p,
IntPtr initialisationVector,
ushort ivLen,
IntPtr aad,
uint aadLen,
IntPtr authTag,
uint authTagLen)
The function encrypt encrypts he data for HLS Authentication and data transport security and
the function decrypt performs the corresponding decryption. The variable definitions are as
follows

encMeth - Identifies the encryption used. The values are 2 for encryption using AES used in challenge
for HLS Mechanism_Id(2) and 5 for encryption using GCM used in HLS_Mechanism_ID(5) and for
data transport security(ciphering)
key - The secret key required for encryption
keyLen - The key length in bytes
plainText_p - The plain text. It will contain the challenge for authentication mechanism and frame the
to be encrypted in case of encryption and the decrypted output obtained in case of decryption.
ptLen - The length of the plain text (cipher text length is the same)
cipherText_p - The cipher text. It will contain the data to be decrypted in case of decryption and
encrypted data output in case of encryption
initialisationVector - The initialization vector used in GCM encryption
ivLen - The length of the initialization vector(will be 12 bytes in DLMS)
aad - The additional authentication data used in GCM encryption
aadLen - The length of the aad
authTag - pointer to authentication tag. This should be filled with authentication tag generated after
encryption if aad is not empty. The length of authTag is fixed at 12 bytes.
AuthTagLen - Length of authTag hash function

computeHash(byte hashMethod,
IntPtr plainText_p,
ushort ptLen,
IntPtr cipherText_p)

Confidential
87
DLMS/COSEM Client SCL User Manual Version 3.15.1

The function computeHash is called to generate digest/hash for HLS_mechanism_Id(3)(MD5


Algorithm) and HLS_mechanism_Id(4)(SHA1 Algorithm) respectively. The arguments of the function is
as follows
hashMethod -The method used for generating hash. 3 for MD5 and 4 for SHA1
plainText_p -pointer to plain Text out of which digest/hast is to be generated ptLen -length of the plain
Text
cipherText_p -pointer to cipher Text where the output generated is to be filled. The length is 16 bytes
for MD5 and 20 bytes for SHA1 digital signature
signatureGeneration( IntPtr privateKey,
IntPtr plainText,
uint ptLen,
byte notUsedByteIndex,
IntPtr sig,
IntPtr sigLen,
byte DER_Encoding,
byte SecuritySuite)
This function is used to generate digital signature on the data pointed to by the plainText pointer,
length of which is contained in ptLen. The private key used for signing is held in privateKey pointer,
and the flag DER_Encoding is 1 if DER encoding is to be used. The generated signature is held in sig
pointer with length in sigLen pointer.
signatureVerification( IntPtr privateKey,
IntPtr plainText,
uint ptLen,
byte notUsedByteIndex,
IntPtr sig,
uint slen,
byte DER_Encoding,
byte SecuritySuite)
This function is used to verify digital signed data contained in the plainText pointer, length of which is
contained in ptLen. The public key used for verification is held in publicKey pointer, and the flag
DER_Encoding is 1 if DER encoding is used. The signature contained in the packet is passed to this
function through the sig pointer with length in slen pointer.

parseCertificate_CRT( IntPtr cert,


uint certLen,
IntPtr certificate_publicKey,
IntPtr certificate_Signature,
IntPtr signLen)
This function is used to parse the input certificate, stored in cert pointer with length in certLen
variable.The user is also required to pass the digital signature and its length in pointers
certificate_Signature and signLen. The function parses the certificate and returns the public key stored

Confidential
88
DLMS/COSEM Client SCL User Manual Version 3.15.1

in the certificate incertificate_publicKey pointer.

digitalSigKeyPairGen( IntPtr privateKey,


IntPtr publicKey)
This function is used to generate a pair of keys consisting of private and public key to be used for
digitally signing and verifying data.

DigKeyPairGetCertificateIdentificationByserial( IntPtr serial_number,


byte serial_numberLen,
IntPtr issuer,
byte issuerLen,
IntPtr Certifcate,
uint CertificateLen,
IntPtr CRT,
IntPtr len)
This function is used to obtain a digital keys and certificate on passing serial number and its length,
issuer and length and certificate length.CRT is the certificate request pointer
getDigCertificateCRT( IntPtr certBuf_Len_CRT,
IntPtr Cert_Buf,
IntPtr PrivateKey,
IntPtr PublicKey,
IntPtr PublicKey2,
byte flag)
This function is used to obtain a digital certificate on passing the private key and public key in the
PrivateKey and PublicKey pointers. The generated certificate is stored into the Cert_Buf pointer by the
function, with length in the certBuf_Len_CRT pointer. The arguments PublicKey2 and flag are not used
in the current stack.

GenerateSharedKey_SHA256( IntPtr PrivateKeyServer,


IntPtr PublicKeyClient,
IntPtr result,
IntPtr Algo_ID,
IntPtr Server_Sys,
IntPtr Client_Sys)
This function is used in the Key Agreement method (IC64 version 1, method 3) to generate a shared
key. The user is required to pass the private key of the Server and public key of the client into the
PrivateKeyServer and PublicKeyClient pointers, with algorithm ID I in the Algo_ID pointer and system
titles of server and client in the Server_Sys and Client_Sys pointers respectively. The generated
shared key will be contained in the result pointer on execution of this function.

KeyDerivationFunction (IntPtr cntr,


IntPtr sharedSecret,
IntPtr algID,
IntPtr SystitleClient,
IntPtr SystitleServer,
IntPtr DerivedKey,

Confidential
89
DLMS/COSEM Client SCL User Manual Version 3.15.1

byte secSuite)
This function is also used in the Key Agreement method (IC64 version 1, method 3) to derive the new
key from the shared key generated by the above function.The user is required to pass the generated
shared key into sharedSecret pointer, along with required values into the cntr, algID, SystitleClient
(Client System title), SystitleServer(server system title) pointers and the security suite used into the
secSuite argumemnt. The new key to be used will be returned in the DerivedKey pointer.

assymHashGenerate( byte hashMethod,


IntPtr plainText_p,
byte ptLen,
IntPtr hash)
This function decrypts the data for HLS Authentication and data transport security. Its arguments
include the hashMethod which indicates the Hashing algorithm used (3 for MD5 and 4 for SHA1, 6 for
SHA256), plainText_p pointer contains the plaintext, length of which is stored in ptLen (ciphertext
length is the same). The function returns the hash which is pointed to by the hash pointer.

getCertificate( IntPtr certSignLen,


IntPtr certBuffer,
IntPtr privKey,
IntPtr pubKey,
IntPtr dlmsInstance)
This function is used to obtain a digital certificate on passing the private key and public key in the
PrivateKey and PublicKey pointers.Generated certificate is stored in Cert_Buf pointer with length in
the certBuf_Len_CRT pointer.

Using Security in Client SCL


For using HLS authentication mechanisms and data encryption, the client SCL provides an API to
register the above functions as callbacks. The registerSecurityCallbacks() function definition is as
follows:

void registerSecurityCallbacks(CryptCallback encryptFn,


CryptCallback decryptFn,
HashCallback hashFn,
SigGenCallback sigGenFunPtr,
SigVerCallback sigVerFunPtr,
ParseCRTCallback
parseCRTFunPtr,
DigKeyPairGenCallback
digKeyPairFunPtr,
GetCertSerialCallback
getCertSerialFunPtr,
GetCertCallback
getCRTFunPtr,
GenShared256KeyCallback

Confidential
90
DLMS/COSEM Client SCL User Manual Version 3.15.1

genSharedKey256FunPtr,
KeyDerivCallback
keyDerivFunPtr,
AssymHashCallback
assymHashGenFunPtr,
GetSignKeysCallback
getSignKeysFunPtr);
NOTE: A sample implementation of the security callback functions for Windows/Linux based on the
publicly available LibTomCrypt library is available from us on demand.

3 Call Sequence

The typical sequence of calling the library functions is as below

registerSecurityCallbacks(), optional. Global setting, and the call needs to be made only once.

registerDiagCallback(), optional. Global setting, and the call needs to be made only once. For description, see
Chapter 4.

initClient()

initPort()

modeEInit() only for HDLC based communication profile, and opening mode is Mode E

sendSNRM() only for HDLC based communication profile

sendAARQ()

Followed by any number of the following three in any order

getData() (always followed by cleanupMemory() after processing data)

setData()

executeAction()

Finally

sendDISC() only for HDLC based communication profile

sendRLRQ()

closePort()

closeClient()

Confidential
91
DLMS/COSEM Client SCL User Manual Version 3.15.1

Please note that you can go back to sendSNRM() after doing a sendDISC() and continue polling another meter
(or another association/logical-device in the same meter). HDLC functions (modeEInit(), sendSNRM(),
sendDISC()) are not used for TCP/ UDP based communication profile.

3.1 Multichannel Operation


Kalkitech DLMS/COSEM Client SCL supports multiple channels and the different channels are identified by the
clientHandle argument in the APIs. All the client APIs are blocking calls. SCL functions can be called
simultaneously from different threads for different channels. SCL Functions should not be called for the same
channel (ie: with the same clientHandle) at the same time.

4 Debugging Options

Debugging options are provided for troubleshooting and analyzing the DLMS frames sent and received by the
client. To enable debugging options, a function as follows is used.
void diagcallback (IntPtr clientHandle,
byte layerId,
byte diagType,
IntPtr pMsg,
uint msgLen,
ushort ChannelNo)

OEM should write their own code inside this function to print or log the diagnostic message. The string pMsg will
have the message. Variable clientHandle contains the handle returned by the initClient() function, layerId
contains the source id of the message, ie whether the message is from physical layer or application layer,
diagType shows whether it is an information message, error message or a communication frame.There is a
sample implementation of this function which prints the data-link and application layer frames to the output
device. However a callback to this function is be passed to SCL via registerDiagCallback() function with
definition as follows
void registerDiagCallback(DiagCallback callbackPointer)

The argument callbackPointer is the pointer to the diagcallback function defined by the user.

5 Running on Linux (+Windows)

The DLMS Client Dot Net version is designed to run on both windows and Linux platform. To build the libraries to
to run on LINUX (Same project ill run on windows), user has to uncomment the LINUX_SUPPORT macro in the
DLMSClient.cs file. Replace the WinSecurity\Linux_DotNet\security.cs in the WinDLMSClientApp folder.

To generate shared object library to run in LINUX, Execute the make file using the command “make dotnet”
from LINUXDLMSCLIENT folder. Run the compilesecuritylibdotnet.sh script in the LinuxAsymSecurity folder
to generate the asymmetric security shared object library. Run the compilesecuritylibdotnet.sh script in the
LinuxSecurity folder to generate symmetric security shared object library.

The Same C# application and wrapper DLL build for LINUX platform can run for Windows operating system, The
name of DLL need to change to use it in Widows OS. Required DLL names are given below.

• DLMSSecurity.dll

Confidential
92
DLMS/COSEM Client SCL User Manual Version 3.15.1

• AsymmDLMSSecurity.dll

• DLMSClient.dll

The corresponding projects are configured with “LINUX” build configuration to generate DLL with
required names.

Confidential
93
DLMS/COSEM Client SCL User Manual Version 3.15.1

6 Appendix A
6.1 Return Codes in SCL

6.1.1 Generic return codes



0x0000 => Success

0x1101 => Generic/ uncategorized failure

0x1102 => Response timeout

0xFFFF => Client user input error

6.1.2 Library generated HDLC specific return codes



0x1103 => Received HDLC frame with wrong sequence number

0x1104 => Received unknown hdlc frame

0x1105 => Received HDLC Unnumbered acknowledgement

0x1107 => Received HDLC Receive Not ready

0x1108 => Received HDLC Information frame

0x110a => Received Information size more than Cosem buffer

0x110b => Received frame has wrong LLC header

0x1111 => User provided HDLC address wrong

0x11fd => Waiting HDLC Window(Frame)

6.1.3 Library generated COSEM specific return codes

0x120c => Received COSEM APDU failed due to encode error

0x120d => Received xDLMS response failed due to wrong invoke id

0x120e => Received xDLMS response due to unknown result field

Confidential
94
DLMS/COSEM Client SCL User Manual Version 3.15.1

0x120f => COSEM Short name response error

0x1210 => COSEM received wrong block number

0x1212 => COSEM HLS error due to wrong key length

0x1213 => COSEM HLS authentication error

0x1214 => COSEM interface class unsupported in Client

0x12fe => Waiting COSEM Application layer block PDU

0x12c8 => COSEM APDU failed while encoding/decoding length


0x13XX=> Exception Response. XX byte represents nature of error sent by server. The first four bits
(Starting from MSB) represent service error while the last four bits represent the state error. Possible values for
the state and service errors are as follows:

state-error:

service-not-allowed (1),

• service-unknown (2)

service-error:

operation-not-possible (1),

service-not-supported (2),

other-reason (3)

6.1.4 Server generated return codes

0x00XX (upper byte = 0x00, lower byte XX = error code returned by DLMS Server – see below –
excerpt taken from DLMS UA Green book)

Confidential
95
DLMS/COSEM Client SCL User Manual Version 3.15.1

Confidential
96
DLMS/COSEM Client SCL User Manual Version 3.15.1

7 Appendix B: Interoperability Details of DLMS Client SCL


Data Link Layer

Maximum Window Size supported : 7

HDLC Addressing Scheme supported : T 1 byte T 2 byte T 4 byte

Support for IEC 62056-21 Mode E : T Yes

Communication Profiles : T HDLC T TCP/IP T UDP T GATEWAY


Application Layer

Authentication Mechanisms : T Lowest Level


T Low Level
T High Level Mechanism ID 2
T High Level Mechanism ID 3
T High Level Mechanism ID 4
T High Level Mechanism ID 5
T High Level Mechanism ID 6
T High Level Mechanism ID 7

Referencing scheme : T Long Name T Short Name

Conformance Block : T General ciphering


T General block transfer
T Read
T Write
T Priority Management Support
T Block Transfer with GET
T Block Transfer with SET
T Block Transfer with READ
T Block Transfer with WRITE
T Block Transfer with Action
T Multiple References
T Parametrized Access
T GET
T SET
T Selective Access
T Event Notification
T Action
T Data Notification

: T LN with no Ciphering
Application contexts T SN with no Ciphering
T LN with Ciphering
T SN with Ciphering

T Suite 0
Security Suites T Suite 1

Confidential
97
DLMS/COSEM Client SCL User Manual Version 3.15.1

T Suite 2

DLMS Objects Supported by the Source Code Library

Interface Class DLMS Object Source code Support


1 Data T Version 0
3 Register T Version 0
4 Extended register T Version 0
5 Demand register T Version 0
6 Register activation T Version 0
7 Profile generic T Version 0 T Version 1
8 Clock T Version 0
9 Script table T Version 0
10 Schedule T Version 0
11 Special days table T Version 0
12 Association SN T Version 0 T Version 1 T Version 2
15 Association LN T Version 0 T Version 1 T Version 2 T Version 3
17 SAP assignment T Version 0
18 Image transfer T Version 0
19 IEC local port setup T Version 0 T Version 1
20 Activity calendar T Version 0
21 Register monitor T Version 0
22 Single action schedule T Version 0
23 IEC HDLC setup T Version 0 T Version 1
25 M-Bus slave port setup T Version 0
26 Utility tables T Version 0
27 Modem configuration T Version 0
28 Auto answer T Version 0
29 Auto connect T Version 0 T Version 1
40 Push Setup T Version 0 T Version 1 T Version 2
41 TCP-UDP setup T Version 0
42 IPv4 setup T Version 0
43 Ethernet setup T Version 0
44 PPP setup T Version 0

Confidential
98
DLMS/COSEM Client SCL User Manual Version 3.15.1

Interface Class DLMS Object Source code Support


45 GPRS modem setup T Version 0
46 SMTP setup T Version 0
47 GSM Diagnostic T Version 0
48 IpV6 Setup T Version 0
55 S-FSK IEC 61334-4-32 LLC T Version 0
setup
57 ISO/IEC 8802-2 LLC Type 1 T Version 0
setup
58 ISO/IEC 8802-2 LLC Type 2 T Version 0
setup
59 ISO/IEC 8802-2 LLC Type 3 T Version 0
setup
61 Register table T Version 0
62 Compact Data T Version 0
64 Security setup T Version 0 T Version 1
65 Parameter monitor T Version 0
67 Sensor manager T Version 0
68 Arbitrator T Version 0
70 Disconnect control T Version 0
71 Limiter T Version 0
72 M-Bus client T Version 0
73 Wireless Mode Q channel T Version 0
74 M-Bus master port setup T Version 0
80 LLC SSCS setup T Version 0
81 PRIME NB OFDM PLC T Version 0
Physical layer counters
82 PRIME NB OFDM PLC MAC T Version 0
setup
83 PRIME NB OFDM PLC MAC T Version 0
functional parameters
84 PRIME NB OFDM PLC MAC T Version 0
counters
85 PRIME NB OFDM PLC MAC T Version 0
network administration data
86 PRIME NB OFDM PLC T Version 0
Applications identification
90 G3-PLC MAC layer counters T Version 1
91 G3-PLC MAC setup T Version 1

Confidential
99
DLMS/COSEM Client SCL User Manual Version 3.15.1

Interface Class DLMS Object Source code Support


92 G3-PLC 6LoWPAN adaptation T Version 1
layer setup
100 NTP setup T Version 0
111 Account T Version 0
112 Credit T Version 0
113 Charge T Version 0
115 Token Gateway T Version 0
122 Function control objects T Version 0
124 Communication port T Version 0
protection objects
126 SCHC-LPWAN setup T Version 0
127 SCHC-LPWAN diagnostic T Version 0
128 LoRaWAN setup T Version 0
129 LoRaWAN diagnostic T Version 0
151 LTE monitoring T Version 0
9000 Extended Data T Version 0
9001 / 105 Zigbee Tunnel Setup T Version 0
9100 CoTS T Version 0
9200 ZigBee DR & LC Cluster T Version 0
9500 Block Tariff Configuration T Version 0
9901 / 101 ZigBee SAS Start-up T Version 0
9902 / 102 ZigBee SAS Join T Version 0
9903 / 103 ZigBee SE TC Control T Version 0
9904 / 104 ZigBee SAS Fragmentation T Version 0
8192 Rate Plan T Version 0

Confidential
100
DLMS/COSEM Client SCL User Manual Version 3.15.1

Alphabetical Index
ACTION_UNION_CS.............................................................................................................................84
Call Sequence........................................................................................................................................89
Client Library Functions.........................................................................................................................10
Debugging Options................................................................................................................................90
DLMS_UNION_CS................................................................................................................................82
Implementation......................................................................................................................................10
Introduction..............................................................................................................................................9
Key Features............................................................................................................................................9
Multichannel Operation..........................................................................................................................90
Overview................................................................................................................................................10
Overview of The Protocol Stack...............................................................................................................9
Return Codes in SCL.............................................................................................................................92
Sample Implementations.........................................................................................................................9
Security Implementation........................................................................................................................85
Structures and Unions...........................................................................................................................82

Confidential
101

You might also like