You are on page 1of 116

DLMS/COSEM Client SCL

User Manual

www.kalkitech.com

Version 3.15.1
20th Dec 2022
Copyright Notice

© 2014 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 support-svs@kalkitech.in


DLMS/COSEM Client Source Code Library 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 Implementation
Procedure procedure

Chapter 3 Special functions This chapter provides the information for the special
procedures supported.

Chapter 4 Registering This chapter provides the instructions to use and register
diagnostic call back diagnostic call back functions.
functions
Chapter 5 Structures and Unions This chapter describes the major structures and unions used.
Chapter 6 Unsolicited data This chapter provides the instructions to use unsolicited data
communication communication.
Chapter 7 Multichannel Operation This chapter describes about the multichannel operations.
Chapter 8 Image transfer This chapter describes the image transfer operation supported
bu library.
Chapter 9 Debugging Options This chapter provides instructions for debugging
Chapter 10 Appendix A

Chapter 11 Appendix B

Chapter 12 Appendix C

Table 1: Organization of the document

Confidential 3
DLMS/COSEM Client Source Code Library 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
1. First Step
1. Second Step

Table 2: Document Conventions

Confidential 4
DLMS/COSEM Client Source Code Library 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
IEC International Electrotechnical Commission
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 Source Code Library User Manual Version 3.15.1

1 Introduction ..................................................................................................................................... 9
1.1 Overview of The Protocol Stack ................................................................................................ 9
1.1.1 DLMS Client SCL package .............................................................................................. 10
1.1.2 Sample Implementations ................................................................................................... 10
1.1.3 Key Features ..................................................................................................................... 10
2 Implementation Procedure ............................................................................................................11
1.2 Overview ...................................................................................................................................11
3 Client Library – Basic Functions................................................................................................. 12
1.3 initClient ................................................................................................................................... 12
1.4 closeClient ................................................................................................................................ 14
1.5 initPort ...................................................................................................................................... 14
1.6 closePort ................................................................................................................................... 16
1.7 modeEInit ................................................................................................................................. 16
1.8 SetParamsHDLC ...................................................................................................................... 17
1.9 sendSNRM ............................................................................................................................... 20
1.10 sendDISC .............................................................................................................................. 20
1.11 SetParamsCosemWrapper ........................................................................................................ 21
1.12 SetParamsAARQ .................................................................................................................. 22
1.13 sendAARQ ............................................................................................................................ 26
1.14 setParamsPreEstablishedAssociation ................................................................................... 28
1.15 UseDedicatedCiphering ........................................................................................................ 31
1.16 SendRLRQ ............................................................................................................................ 31
1.17 getData .................................................................................................................................. 33
1.18 cleanupMemory .................................................................................................................... 36
1.19 setData .................................................................................................................................. 36
1.20 CleanUpMemoryForSet ........................................................................................................ 39
1.21 executeAction ....................................................................................................................... 39
1.22 cleanupActionMemory ......................................................................................................... 41
1.23 setGatewayParams ................................................................................................................ 42
1.24 Typical call sequence ............................................................................................................ 43
4 Asynchronous APIs ....................................................................................................................... 46
1.25 CosemEncodeAXDR ............................................................................................................ 46
1.26 encodeAARQrequest ............................................................................................................ 50
1.27 encodeRLRQrequest ............................................................................................................. 55
1.28 challengeProcessing .............................................................................................................. 59

Confidential 6
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.29 CleanUpEncodedAXDR ....................................................................................................... 61


1.30 CosemDecodeAXDR ............................................................................................................ 61
1.31 CleanupDecodedAXDR ....................................................................................................... 65
1.32 cosemDecodeCompactFrameData ........................................................................................ 65
1.33 cleanDecodedCompactFrameData ....................................................................................... 66
1.34 encodeComProfileParams..................................................................................................... 67
1.35 cleanUpEncodedComHeader ................................................................................................ 67
1.36 decodeComProfileParams..................................................................................................... 68
1.37 cleanUpDecodedComHeader ............................................................................................... 69
1.38 EncodeHDLCrequest ............................................................................................................ 69
1.39 DecodeHDLCrequest ............................................................................................................ 72
1.40 cleanUpEncodedHDLC ........................................................................................................ 74
1.41 cleanUpEncodedHDLC ........................................................................................................ 75
1.42 cleanUpDecodedHDLC ........................................................................................................ 75
1.43 Call Sequence ....................................................................................................................... 75
5 Special functions............................................................................................................................ 76
1.44 getSystemTitleFromPushNotification .................................................................................. 76
1.45 Set Frame Counter ................................................................................................................ 76
1.46 getAssociationParameters ..................................................................................................... 77
1.47 updateHdlcAdvancedSettings ............................................................................................... 77
1.48 updateSerialAdvancedSettings ............................................................................................. 77
1.49 sendPacket ............................................................................................................................ 78
1.50 cleanUpMemoryforsendpacket ............................................................................................. 79
6 Registering diagnostic call back functions .................................................................................. 79
1.51 registerErrCallback ............................................................................................................... 79
1.52 RegisterDiagCallback ........................................................................................................... 79
1.53 registerSecurityCallbacks ..................................................................................................... 80
1.54 registerCertCallback ............................................................................................................. 90
1.55 registerWrapperAppDataCallback ........................................................................................ 91
1.56 registerPLCAppDataCallback .............................................................................................. 91
7 Structures and Unions .................................................................................................................. 93
1.57 DLMS_UNION .................................................................................................................... 93
1.58 ACTION_UNION ................................................................................................................ 96
8 Unsolicited data communication.................................................................................................. 98
1.59 Registering call back functions ............................................................................................. 98
1.59.1 Event call backs ................................................................................................................ 98

Confidential 7
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.59.2 Push call backs .................................................................................................................. 99


1.60 initIncomingPort ................................................................................................................... 99
1.61 setParamsUnsolicitedCommunication .................................................................................. 99
1.62 plafInitIncomingPort........................................................................................................... 100
1.63 Retrieving events ................................................................................................................ 100
1.64 cleanPushData..................................................................................................................... 101
1.65 cleanEventData ................................................................................................................... 101
9 Security Implementation ............................................................................................................ 101
1.66 Encrypt/Decrypt .................................................................................................................. 101
1.67 Generate Hash ..................................................................................................................... 102
1.68 Digital Signature ................................................................................................................. 103
1.69 Using Security in Client SCL ............................................................................................. 104
10 Multichannel Operation ............................................................................................................. 105
11 Image transfer ............................................................................................................................. 106
12 Debugging options ....................................................................................................................... 107
13 Appendix A – Client SCL API return codes ............................................................................. 108
1.70 Generic return codes ........................................................................................................... 108
1.71 Library generated HDLC specific return codes .................................................................. 108
1.72 Library generated COSEM specific return codes ............................................................... 108
1.73 Server generated return codes ............................................................................................. 109
14 Appendix B – DLMS Conformance block ................................................................................. 111
15 Appendix C: Interoperability Details of DLMS Client SCL....................................................112

Confidential 8
DLMS/COSEM Client Source Code Library 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 IEC 62056
DLMS/COSEM protocol stack to enable interested parties to create DLMS Client Applications to
read/write DLMS enabled meters and devices.
The protocol source is written in ANSI-C and can be built onto most platforms as-is without any
changes. Even then there is a change required to adapt for a particular platform, the effort will be
minimal and can be implemented in the platform interface only without altering other areas of stack.

The stack is based on the following specifications.

IEC DLMS UA
▪ IEC 62056-21 Mode E : Direct Local Data ▪ Blue Book : COSEM interface classes
Exchange and OBIS identification system
▪ IEC-62056-42: Physical Layer ▪ Green book : DLMS/COSEM
▪ IEC-62056-46: HDLC Datalink Layer Architecture and Protocols
▪ IEC 62056-47 COSEM Transport Layers • Yellow book is DLMS server
for IPv4 networks conformance test plan and hence not
▪ IEC-62056-53: COSEM Application Layer applicable for client
▪ IEC-62056-61: OBIS (OBject
Identification System)
▪ IEC-62056-62: Interface Classes

Confidential 9
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.1.1 DLMS Client SCL package

1.1.2 Sample Implementations


The SCL also ships with Windows and Linux sample implementations of the full SCL. This sample
project also implements the platform interface, providing Windows/Linux-specific implementations of
the millisecond-timer, COM port routines and TCP/UDP socket routines. User can build this sample
implementations 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.1.3 Key Features

• Platform independent with sample implementation for Windows(C and C#) and Linux(
C)
• Supports following communication profiles.
• Direct HDLC (over Serial port)
• IEC 62056-21 Mode E with HDLC
• TCP
• UDP
• HDLC over TCP
• HDLC over UDP
• Gateway profile
• Support Event notification and data PUSH
• Support Lowest, Low and High level authentication(mode 2,3,4,5,6 and 7)
• Support Data transport security – authentication and encryption

Confidential 10
DLMS/COSEM Client Source Code Library 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.

1.2 Overview
The SCL functions provide means to open and initialize a serial port or create IP socket(TCP/UDP) in
server mode(inbound connection) or client mode(outbound connection) , establish an HDLC
connection (for connecting to HDLC based DLMS Servers), establish an Application Association, and
then functions to get/read(with or without selective access), set/write, /execute action for object
attributes / methods in the connected DLMS server (meter).The client application can then call
functions to release application association(in case of IP based communication) or disconnect(for
HDLC based communication) from the meter, close the communication port.

The file plaf.c may be implemented to suite your platform requirements. The sample Windows/Linux
implementations may be used to understand what is required in each function. Type definitions done in
the file kdefs.h can be edited (specifically the definitions of the primitive types) to match the data
types available in your platform. The default definitions should suffice for most implementations.

Confidential 11
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

3 Client Library – Basic Functions


The following functions can be called for communicating with the server.

1.3 initClient
This function is used to initialize an instance of DLMS Client as the first step while using the library.
On each initClient(), library will create a Client instance and return its handle to Client user. Client user
shall pass this “hanlde” in all subsequent APIs that are called. Multiple client instance might be
required if Client user wants to communicate with several DLMS servers concurrently. In such
requirements user should call initClient() multiple times.

void *initClient(KDEFS_ULONG respTimeout,


KDEFS_USHORT frmTimeout,
KDEFS_USHORT linkBufSz,
KDEFS_ULONG cosemBufSz,
KDEFS_UCHAR commProfile,
KDEFS_UCHAR cipheringSupport
KDEFS_USHORT ChannelNo);

Argument

respTimeout Response timeout used by the client, in milliseconds.


This is the maximum time that the Client is to wait
after sending a request without receiving a response
before declaring that the request has timed-out. User
shall set this value judiciously depending on server
characteristics and channel/network characteristics.

Example; 30000

FrmTimeout 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.

Example: 5000

LinkBufSz HDLC/ IP wrapper buffer size. This is the maximum


number of bytes which needs to be buffered in link

Confidential 12
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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

CosemBufSz COSEM buffer size, This is the size of the COSEM


Application Layer buffers that hold the data when
performing a Get/Read, Set/Write, Action operation.
This should be a large value to hold the largest
possible attribute value that may be read/written from
the meter. Certain array-type attributes (for example,
the Buffer attribute of a Profile object) may contain
several entries and in such cases the buffer should be
sized appropriately to hold the entire response.

Example: 1000000

commProfile This is an enumeration type indicating choice for communication


profile. Choices for communication profile are as follows :
◦ 1 => Direct HDLC over serial
◦ 2 => Mode-E HDLC over serial
◦ 3 => TCP
◦ 4 = UDP.
◦ 7 => Direct HDLC over TCP
◦ 8 => Direct HDLC over UDP
Enumeration to indicate if ciphering will be used for
communication with the server using the client instance being
cipheringSupport initialized. Possible values are

0 => ciphering will not be used


1 => ciphering shall be used

NOTE: This argument only serve for library in decision making


whether buffer for ciphering/deciphering is to be allocated or not.
It does not have any influence on whether ciphering or
deciphering is to be used on APDUs exchanged in actual
Application Association. 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 13
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

This is any ushort value given by user application that can be


optionally used by application in future to distinguish the client
channelNo handle(especially in case of push/event receipt)

Returns

Void * Pointer i.e. the newly created DLMS Handle if the


function succeeds

NULL Function failed

1.4 closeClient
For closing the DLMS Client.This is an optional API and need to be called only when Client user wish
to destroy a client instance( created during initClient() ).
void closeClient(void *clientHandle)

Argument
clientHandle Handle returned by initClient()
Return

1.5 initPort
This function initializes and opens a communication port. It shall be noted that this same function is
used to initialize communication interface of all communication profiles
KDEFS_USHORT initPort(void *clientHandle,
KDEFS_UCHAR *clientIpAddr_p,
KDEFS_UCHAR *serverIpAddr_p,
KDEFS_USHORT serverPort,
KDEFS_UCHAR *port_p,
KDEFS_ULONG baud,
KDEFS_UCHAR parity,
KDEFS_UCHAR enableUnsolicitedService,
KDEFS_USHORT max_no_of_conn_retries,
KDEFS_ULONG retry_delay,
KDEFS_ULONG connWaitTimeout);

Confidential 14
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Argument
clientHandle Handle returned by initClient()
clientIpAddr_p Required only for IP based communication
profile. IP address of client as string (e.g.
“127.0.0.1”).
If communication profile selected in
initClient() is 1(Direct HDLC) or 2(Mode E),
then this field is not relevant(don’t care)
serverIpAddr_p Required only for IP based communication
profile. IP address of server as string (e.g.
“127.0.0.1”).
If communication profile selected in
initClient() is 1(Direct HDLC) or 2(Mode E),
then this field is not relevant(don’t care)
server_port Required only for IP based communication
profile. UDP/TCP port of server.
Example: 4059
port_p [ Only for serial ] The serial port name as a
string(char string, e.g. “”//./COM1” ).
For IP based communication profiles, value of
this argument is discarded by library.
Baud [ Only for serial ] The baud rate for
communication.(integer, e.g. 9600 )
For IP based communication profiles, value of
this argument is discarded by library.
parity [ Only for serial ] Specifies the parity scheme
to be used, 0-4 = no, odd, even, mark, space
Example: 0
For IP based communication profiles, value of
this argument is discarded by library.
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 automatic reconnection

Confidential 15
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 in milliseconds.

connWaitTimeout
0 - blocking mode,

>0 - time in ms for select() timeout in non


blocking mode

used in IP profile

Returns
0x0000 Success
Non zero indicates error. See Appendix A for detailed
list of error codes

1.6 closePort
For closing the communication port which was opened by initPort().
KDEFS_USHORT closePort(void *clientHandle);

Argument
clientHandle Handle returned by initClient()
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

1.7 modeEInit
This function performs the mode E (IEC 62056-21) handshaking before switching to COSEM/ HDLC.
Note:- This API is optional and need to be called only for mode E handshake(as per IEC 62056-21)
which may be supported in local port(optical) of meters.

Confidential 16
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

KDEFS_USHORT modeEInit(void *clientHandle,


KDEFS_UCHAR *devAddr,
KDEFS_UCHAR *XXX,
KDEFS_UCHAR *Ident);

Argument
clientHandle Handle returned by initClient()
devAddr Device address as string (optional field,
manufacturer specific, 32 characters
maximum)
XXX String (Manufacturer’s identification
comprising of three upper case letters)
Ident String (Identification, manufacturer
specific, 16 printable characters maximum
except for “/” and “!”)
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

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

For HDLC based communication – user shall set HDLC parameters before proceeding to HDLC
connection establishment or any Application layer functions

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()

Confidential 17
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

KDEFS_USHORT setParamsHDLC(void *clientHandle,


KDEFS_UCHAR addressSize,
KDEFS_UCHAR clntID,
KDEFS_USHORT serverID,
KDEFS_USHORT devAddr,
KDEFS_UCHAR windowRx,
KDEFS_UCHAR windowTx,
KDEFS_USHORT infoFieldLenRx,
KDEFS_USHORT infoFieldLenTx);

Argument
clientHandle Handle returned by initClient()
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
provide at least one Public-Access
association. Other Client IDs supported shall

Confidential 18
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
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

Confidential 19
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Return
0x0000 Success
Non zero indicates error. See Appendix A for detailed
list of error codes

1.9 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.

KDEFS_USHORT sendSNRM (void *clientHandle,


KDEFS_BOOL negoParams);

Argument
clientHandle Handle returned by initClient()
Enumeration indicating if HDLC
negoParams parameters(Maximum Information size
transmit and receive, maximum window
size transmit and receive) shall be
negotiated with server. Possible values are
0 => No negotiation
1 => Negotiate

Example: 0
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

1.10 sendDISC
This function can be used to send the HDLC disconnect frame to server to disconnect a previously
Confidential 20
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

established HDLC connection. Sending DISC frame will also cause to release Application Association.

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

KDEFS_USHORT sendDISC(void *clientHandle);

Argument
clientHandle Handle returned by initClient()
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

1.11 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.
For IP based communication – user shall set Cosem Wrapper parameters before
proceeding to Application layer functions

NOTE: For users who are familiar with previous versions(versions prior to 3.3.0) of DLMS Client
stack, it shall be noted that in previous version of Client stack DLMS Application(wrapper) address
was set in initPort() function which has now been moved to setParamsCosemWrapper() funciton.

KDEFS_USHORT setParamsCosemWrapper(void *clientHandle,


KDEFS_USHORT wClientAddr,
KDEFS_USHORT wServerAddr);

Argument
clientHandle Handle returned by initClient()
WclientAddr Client wrapper port number(Client
Address)
wServerAddr Server wrapper port number(Server
Logical Device Address)
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

Confidential 21
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.12 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.

For both HDLC and IP based communication – user shall set AARQ parameters before proceeding to
Application layer functions

NOTE: For users who are familiar with previous versions(versions prior to 3.3.0) of DLMS Client
stack, it shall be noted that sendAARQ() function has been split into two functions : setParamsAARQ()
and sendAARQ()
KDEFS_USHORT setParamsAARQ(void *clientHandle,
KDEFS_UCHAR appCtxt,
KDEFS_UCHAR authMech,
KDEFS_UCHAR *authenticationKey_p,
KDEFS_UCHAR *encryptionKey_p,
KDEFS_UCHAR *dedEncKey_p,
KDEFS_UCHAR *globalbroadcastkey,
KDEFS_UCHAR *PrivKey,
KDEFS_UCHAR *pubKeyServer,
KDEFS_UCHAR security policy,
KDEFS_UCHAR securitySuite,
KDEFS_ULONG authTagLen,
KDEFS_UCHAR *clientSystemTitle_p,
KDEFS_UCHAR *passwrd_p,
KDEFS_UCHAR passwrdLen,
KDEFS_USHORT maxApduSizeRecv,
KDEFS_ULONG conformance,
KDEFS_UCHAR generalGlobalCipher,
KDEFS_UCHAR curUserId);

Confidential 22
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Argument
clientHandle Handle returned by initClient()
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.
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_p 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_p 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.
dedEncKey_p 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 client and several
servers.
PrivKey Private key that used for signature generation.
Pass NULL if signature generation not

Confidential 23
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

required.
pubKeyServer Public key of server that client is expected to
communicate. Pass NULL if not
required/unknown. It can be passed later state
on callback functions.
securityPolicy 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 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

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
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.
passwd_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 6: 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
passwdLen Length(number of bytes) of the password

Confidential 24
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
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)
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
generalGlobalCiphering Enumeration indicating the kind of ciphering
used for Action service during HLS

0 for service specific global ciphering


1 for General Global ciphering with no
system title (System title legth = 0)
2 for General Global ciphering with system
title (System title legth = 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.
Example: 0
curUserId Specify the ID for current user information to
encode in AARQ request.
Example: 0
Return

Confidential 25
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

0x0000 Success
Non zero indicates error. See Appendix A for detailed
list of error codes
1.13 sendAARQ
This function is used to establish an application association which connects the COSEM layers of the
client and server. If Client Server communication is using HDLC as communication profile, then this
function shall be called only after ensuring a valid HDLC connection(i.e. by calling sendSNRM() ).
The parameters of the Association must match the settings in the meter for the Association that was
identified setParamsHDLC function (in case of HDLC communication profile) or
setParamsCosemWrapper function(in case of IP based profile) by the client and server IDs.

The ACSE protocol version which is an optional parameter in AARQ is not sent in AARQ by library.
The DLMS Version number used is 6 by library.
KDEFS_USHORT sendAARQ(void *clientHandle,
KDEFS_UCHAR supportUserIdEncoding,
SECURITY_PARAM securityParam,
KDEFS_UCHAR *clientChallenge,
KDEFS_UCHAR clientChallengeLen,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR dedicatedKeyPresent,
KDEFS_USHORT maxAPDUSizeSend,
KDEFS_UCHAR priority);

NOTE: Before calling sendAARQ() user should set Application layer parameters using following functions
For IP communication profile:-
setParamsCosemWrapper()
setParamsAARQ()
For HDLC communication profile:-
setParamsHDLC()
setParamsAARQ()

Argument
clientHandle Handle returned by initClient()
supportUserIdEncoding Enumeration to indicate if user id is to be encoded in
AARQ
• 0 => user id not encoded
• 1 => user id encoded
securityParam NOTE: this is required only in case of
encryption/decryption.

Confidential 26
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 used.

Confidential 27
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
clientChallenge Client challenge
clientChallengeLen Length of the client challenge
serviceClass Possible values are
0 - To send unconfirmed AARQ.
1 - To send confirmed AARQ.
This information shall be encoded in response-
allowed 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(see 2.2.13).
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
0x0000 Success
Non zero indicates error. See Appendix A for detailed list of
error codes

1.14 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 28
DLMS/COSEM Client Source Code Library 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()

KDEFS_USHORT setParamsPreEstablishedAssociation(void *clientHandle,


KDEFS_UCHAR *serverSystemTitle,
KDEFS_UCHAR serverSystemTitleLen,
KDEFS_ULONG conformance,
KDEFS_USHORT maxApduSizeSend,
SECURITY_PARAM SecurityParam);

Argument
clientHandle Handle returned by initClient()
serverSystemTitle
String of length 8.

This is the default server system title used


to 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
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

Confidential 29
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

value of 0x001818 indicates Get, Set,


Block Transfer with Get and Block
Transfer with Set functions.
Example: 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 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;
Used to define the ciphering type and
initial value of frame counter to use in the
association.
Meaning of each bit of cipheringType 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,
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

Confidential 30
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

or TRUE, it indicates compression is


enabled.
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

1.15 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.

KDEFS_USHORT useDedicatedCiphering (void *clientHandle,


KDEFS_UCHAR dedicatedSupport)

Argument
clientHandle Handle returned by initClient()
dedicatedSupport By setting “dedicatedKeySupport” argument to
KDEFS_TRUE, stack will use dedicated key
ciphering.
By setting “dedicatedKeySupport” argument to
KDEFS_FALSE, stack will use global key
ciphering.

1.16 SendRLRQ
Release an already established application association. This function shall not be called in pre-
established association.
Note:- This function is required for IP based communication profile.
KDEFS_USHORT sendRLRQ(void *clientHandle,
KDEFS_UCHAR reason,
SECURITY_PARAM securityParam,
KDEFS_UCHAR serviceClass);

Argument
clientHandle Handle returned by initClient()
reason reason for release

Confidential 31
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

securityParam NOTE: this is required only in case of


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

Confidential 32
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
serviceClass Possible values are
0 - To send unconfirmed AARQ.
1 - To send confirmed AARQ.
This information shall be encoded in response-
allowed field of InitiateRequest.

1.17 getData
This function can be used to get values from DLMS Server. The function returns the pointer 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 returned pointer contains a structure with result and array of
DLMS_UNION structures. Each DLMS_UNION contain the result/data of cosem object attribute
which was referred in request. 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.

COSEMDATA *getData(void *clientHandle,


COSEM_ATTR_METH_DESC_LIST *GetRequestList,
KDEFS_UCHAR priority,
KDEFS_UCHAR invokeId,
SECURITY_PARAM securityParam);

Argument
clientHandle Handle returned by initClient()
GetRequestList COSEM_ATTR_METH_DESC_LIST structure
containing list of cosem attribute descriptors

typedef struct CosemAttrMethDescList


{
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

Confidential 33
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
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

Confidential 34
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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

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.
Return
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 resultvariable 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

Confidential 35
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

appropriate sub-structure according to


the interface class requested.

• Result code non zero => error. See


Appendix A for more details of error
code.

1.18 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. Client user can call this function irrespective of the result(Success/Failure) returned in
getData().

void cleanupMemory(void *clientHandle);

Argument
clientHandle Handle returned by initClient()
Return

1.19 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 structure variable. Its address has to be passed through this function.
The user of the library is expected to allocate and fill SETDATAINFO structure with list of cosem
attribute descriptors and list of DLMS_UNIONs. After the call completes the user is also expected to
cleanup and release the memory used. The client library does not clean-up SETDATAINFO.

RESULTINFO* setData(void *clientHandle,


SETDATAINFO *setDataInfo,
KDEFS_UCHAR priority,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR invokeId,
SECURITY_PARAM securityParam);

Argument
clientHandle Handle returned by initClient()
SetDataInfo List of cosem attribute descriptors and data to set

typedef struct SetDataInfo


{

Confidential 36
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

COSEM_ATTR_METH_DESC_LIST
cosemAttrDescrList;
DLMS_UNION *setCosemData;
}SETDATAINFO;

COSEM_ATTR_METH_DESC_LIST structure
containing list of cosem attribute descriptors

typedef struct CosemAttrMethDescList


{
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.
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
{

Confidential 37
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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

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.
Return
0x0000 List of results in the same sequence as cosem
attribute descriptors filled in request

typedef struct ResultInfo


{
KDEFS_ULONG numDescriptors;

Confidential 38
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

KDEFS_USHORT *dataResult;
KDEFS_USHORT genResult;
}RESULTINFO;
Non zero indicates error. See Appendix A for detailed list
of error codes

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

void cleanUpMemoryForSet(void *clientHandle);

Argument
clientHandle Handle returned by initClient()
Return

1.21 executeAction
RESULTINFO* executeAction(void *clientHandle,
COSEM_METH_DESC_LIST *actionReqList,
KDEFS_UCHAR priority,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR invokeId,
SECURITY_PARAM securityParam);

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 structure can
be found in ICStructs.h file.

Argument
clientHandle Handle returned by initClient()
actionReqList List of cosem method descriptors and data for action.

typedef struct CosemMethDescList


{
KDEFS_ULONG numDescriptors;
COSEM_METH_DESC *cosemMethDesc;
KDEFS_UCHAR useWithList;
ACTION_UNION *actionData_p;

Confidential 39
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

}COSEM_METH_DESC_LIST;

COSEM_ATTR_METH_DESC_LIST structure
containing list of cosem method descriptors

typedef struct CosemAttrMethDescList


{
KDEFS_ULONG numDescriptors;
COSEM_METH_DESC *cosemMethDesc;
KDEFS_UCHAR useWithList;
ACTION_UNION *actionData_p;
}COSEM_ATTR_METH_DESC_LIST;

useWithList shall be set to 0 if action normal or withlist is


to be used

useWithList shall be set to 1 if action with list(multiple


reference) 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;

NOTE: The response result and 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 = 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

Confidential 40
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
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
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.
Return
resultInfo List of results in the same sequence as cosem attribute
descriptors filled in request

typedef struct ResultInfo


{
KDEFS_ULONG numDescriptors;
KDEFS_USHORT *dataResult;
KDEFS_USHORT genResult;
}RESULTINFO;

1.22 cleanupActionMemory
Clean memory allocated to store action result for each cosem attribute descriptor. User shall call this
function after every executeAction().

Confidential 41
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

void cleanupActionMemory(void *clientHandle);

Argument
clientHandle Handle returned by initClient()
Return

1.23 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).

KDEFS_USHORT setGatewayParams(void *clientHandle,


KDEFS_UCHAR NetworkId,
KDEFS_UCHAR PhyAddrLen,
KDEFS_UCHAR* PhyAddr,
KDEFS_UCHAR srcPhyAddrLen,
KDEFS_UCHAR* srcPhyAddr)

Argument
clientHandle Handle returned by initClient()
NetworkId 1 byte network ID to be used in GW Header
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
in gateway header. This argument will be used while

Confidential 42
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

decoding gateway header. Size of this string shall be same


as specified in “srcPhyAddrLen” argument.
Return
0x0000 if the function succeeds; else nonzero if the function failed

1.24 Typical call sequence


Typical call sequence is shown below. It shall be noted that this sequence may be changed by user
depending on communication requirement.

Confidential 43
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

HDLC Communication profile

initClient()
initPort()
setParamsHDLC()
sendSNRM()
setParamsAARQ()
sendAARQ()
getData() / setData() / executeAction()
cleanupMemory() / cleanUpMemoryForSet()
/ cleanupActionMemory()
sendDisc()
closePort()
closeClient()

IP Communication profile (explicitly associated Application Association)

initClient()
initPort()
setParamsCosemWrapper()
setParamsAARQ()
sendAARQ()
getData() / setData() / executeAction()
cleanupMemory() / cleanUpMemoryForSet() /
cleanupActionMemory()
sendRLRQ()
closePort()
closeClient()
IP Communication profile(Pre-established Association)

initClient()
initPort()
setParamsCosemWrapper()
setParamsAARQ()
setParamsPreEstablishedAssociation()
getData() / setData() / executeAction()
cleanupMemory() / cleanUpMemoryForSet() /
cleanupActionMemory()
closePort()
closeClient()

Confidential 44
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

NOTE:-
• Data communication services viz getdata(), setData(), executeAction() can be called any
number of times within Application association established(by sendAARQ() function).
• 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.

Confidential 45
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

4 Asynchronous APIs
This section refer to APIs which can be used by application when it want to make use of DLMS library
in asynchronous manner. In this mode library would not be performing the actual packet transmit or
receive and thereby will not be blocking the application.
Broadly describing, in this mode of operation, application can request library to do
• prepare APDU(APDUs like AARQ, Get Request, Set Request, Action Request). The APDU
prepared by library would be given back and application shall take responsibility of establishing
lower layer connection and then sending of the prepared APDU to the correct meter.
• Application can receive the packets from meter and then pass it to library to decode
APDU(APDUs like AARE, Get Response, Set Response, Action Response, Data
notification/Event notification request).

1.25 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).

PREPARED_APDU * cosemEncodeAXDR(SECURITY_PARAM securityParam,


KDEFS_UCHAR appCtxt,
KDEFS_UCHAR SecuritySuite,
KDEFS_UCHAR *clientSystemTitle_p,
KDEFS_UCHAR *ServerSystemTitle_p,
KDEFS_UCHAR *authenticationKey_p,
KDEFS_UCHAR *encryptionKey_p,
KDEFS_UCHAR *broadcastenckey,
KDEFS_ULONG authTagLen,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR priority,
KDEFS_UCHAR invokeId,
KDEFS_USHORT maxApduSizeSend,
KDEFS_UCHAR useGenGloCiph,
KDEFS_UCHAR useGlobalCiph,
KDEFS_UCHAR service,
KDEFS_ULONG cosemBufSize,
GENERAL_ATTR_METH_DESC_LIST *generalAttrMethDescList,
KDEFS_UCHAR *privateKey,
KDEFS_USHORT channelNo,
KDEFS_UCHAR enableLLCHeader);

Confidential 46
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Argument
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
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
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.
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

Confidential 47
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 ServAuthentication key used in protection
encryptionKey_p Encryption key used in protection. This shall be global
encryption key if useGlobalCiph = 1 or dedicated key
if useGlobalCiph = 0.
broadcastenckey Broadcast encryption key used to secure broadcast
communication between a client and several servers.
authTagLen Length of GMAC Authentication tag of APDUs used
within Application Association
Possible values are
• 12
• 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 the generated request
APDU exceeds this value the APDU will be returned
in multiple blocks.
Example: 512
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

Confidential 48
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

◦ 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 GeneralAttrMethDescList


{
KDEFS_ULONG numDescriptors;
GENERAL_ATTR_METH_DESC
*generalAttrMethDesc;
KDEFS_UCHAR useWithList;
}GENERAL_ATTR_METH_DESC_LIST;

typedef struct GenAttrMethDesc


{
OBISCODE * obis_p;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
KDEFS_USHORT base;
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 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 PrivateKey used for signing the APDU for Suite != 0
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)

Confidential 49
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
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;

1.26 encodeAARQrequest
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 50
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

PREPARED_APDU * encodeAARQrequest(KDEFS_UCHAR appContext,


KDEFS_UCHAR authMech,
KDEFS_UCHAR *authenticationKey,
KDEFS_UCHAR *encryptionKey,
KDEFS_UCHAR *dedEncryKey,
KDEFS_UCHAR *globalbroadcastkey,
KDEFS_UCHAR secPolicy,
KDEFS_UCHAR securitySuite,
KDEFS_UCHAR authTagLen,
KDEFS_UCHAR *clientSystemTitle,
KDEFS_UCHAR *passwd,
KDEFS_UCHAR passwdLen,
KDEFS_USHORT maxApduSize,
KDEFS_UCHAR userId,
KDEFS_UCHAR supportUserIdEncoding,
SECURITY_PARAM secrtyParam,
KDEFS_UCHAR *clientChallenge,
KDEFS_UCHAR clientChallengeLen,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR useGlobalCipher,
KDEFS_UCHAR isdedicatedCipher,
KDEFS_ULONG conformance,
KDEFS_ULONG cosemBufSize,
KDEFS_UCHAR *privateKey,
KDEFS_USHORT channelNo,
KDEFS_UCHAR enableLLCHeader)

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,

Confidential 51
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
dedEncryKey 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 client and several 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

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

Confidential 52
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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. This should be a string of length 8.
This key is used for generating Initialization Vector
used in ciphering.
Passwd 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 6: 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
passwdLen Length(number of bytes) of the password filled.
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)
userId Specify the ID for current user information to encode
in AARQ request.
Example: 0
supportUserIdEncoding Enumeration to indicate if user id is to be encoded in
AARQ
0 => user id not encoded
1 => user id encoded
secrtyParam NOTE: this is required only in case of
encryption/decryption.

typedef struct FrameCounter


{
KDEFS_UCHAR userCfg;
KDEFS_ULONG frameCounterToUse;
}FRAME_COUNTER_CFG;

typedef struct SecurityParam

Confidential 53
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

{
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
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.
clientChallenge Client challenge
clientChallengeLen Length of the client challenge
useGlobalCipher Set 1 to Enable General Global Ciphering
isdedicatedCipher Set 1 to Enable dedicated key encoding
Conformance Proposed conformance to use in AARQ

Confidential 54
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 PrivateKey used for signing the APDU for Suite != 0
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)
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
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;

1.27 encodeRLRQrequest
This function is used if user want library to prepare a RLRQ 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).
PREPARED_APDU *encodeRLRQrequest(KDEFS_UCHAR appContext,
KDEFS_UCHAR authMech,
KDEFS_UCHAR *authenticationKey,
KDEFS_UCHAR *encryptionKey,
KDEFS_UCHAR *dedicatedKey,
KDEFS_UCHAR *globalbroadcastkey,
KDEFS_UCHAR secPolicy,

Confidential 55
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

KDEFS_UCHAR secSuite,
KDEFS_UCHAR authTagLen,
KDEFS_UCHAR *clientSystemTitle,
KDEFS_UCHAR *ServerSystemTitle_p,
KDEFS_USHORT maxApduSize,
SECURITY_PARAM secrtyParam,
KDEFS_ULONG conformance,
KDEFS_UCHAR reason,
KDEFS_UCHAR dedKeyFlag,
KDEFS_ULONG cosemBufSize,
KDEFS_UCHAR serviceClass,
KDEFS_UCHAR *privateKey,
KDEFS_USHORT channelNo,
KDEFS_UCHAR enableLLCHeader)

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.

Confidential 56
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
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 client and several 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 57
DLMS/COSEM Client Source Code Library 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 58
DLMS/COSEM Client Source Code Library 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 signing the APDU for Suite != 0
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)
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.
Return
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;

1.28 challengeProcessing
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

Confidential 59
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

machine where in library send the request to server by library itself).

KDEFS_USHORT challengeProcessing(KDEFS_UCHAR *plainText_p,


KDEFS_UCHAR len,
KDEFS_UCHAR *cipherText_p,
KDEFS_UCHAR authMech,
KDEFS_UCHAR *hlsKey,
KDEFS_UCHAR *cSysTitle,
KDEFS_UCHAR *sSysTitle,
KDEFS_UCHAR *encKey,
KDEFS_UCHAR *authKey,
KDEFS_ULONG frameCounter,
KDEFS_UCHAR SignatureVerify,
KDEFS_UCHAR securitySuite,
KDEFS_UCHAR *privateKey,
KDEFS_UCHAR *publicKey)

Argument
plainText_p The challenge string to process.
len Length of challenge
cipherText_p 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 HLS secret
cSysTitle Client system title
sSysTitle Server system title
encKey Encryption key
authKey Authentication key.
frameCounter Frame counter. Applicable only or authentication mechanism 5.

SignatureVerify Flag indicating whether HLS7 signature verification required/not


securitySuite Security Suite of the security object used for the Association.
privateKey Private key used in digital signature
publicKey Public key used in digital signature

Confidential 60
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Return
KDEFS_USHORT

1.29 CleanUpEncodedAXDR
This function must be called after the cosemEncodeAXDR(), encodeRLRQrequest() and
encodeAARQrequest() functions returned and CleanUpEncodedAXDR() is used by user.to free the
memory allocated by library during cosemEncodeAXDR() encodeRLRQrequest() and
encodeAARQrequest() functions. cosemEncodeAXDR() returns a PREPARED_APDU pointer that has
various elements allocated dynamically. Before calling another 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().

KDEFS_USHORT cleanUpEncodedAXDR(PREPARED_APDU * preparedAPDU);

Argument
PREPARED_APDU This is a pointer to a structure variable
which hold the encoded APDU (returned
by cosemEncodeAXDR() function).
Return
0x0000 Success
Non zero indicates error. See Appendix A for
detailed list of error codes

1.30 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).

Confidential 61
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

DECODED_PRIMARY_DATA * cosemDecodeAXDR(KDEFS_UCHAR securityPolicy,


KDEFS_UCHAR *serverSystemTitle_p,
KDEFS_UCHAR *authenticationKey_p,
KDEFS_UCHAR *encryptionKey_p,
KDEFS_UCHAR *broadcastenckey,
KDEFS_ULONG authTagLen,
KDEFS_ULONG cosemBufSize,
GENERAL_ATTR_METH_DESC_LIST * generalAttrMethDescList,
ENCODED_PRIMARY_APDU apduData,
KDEFS_UCHAR *clientSystemTitle_p,
SECURITY_PARAM securityParam,
KDEFS_UCHAR *publicKey,
KDEFS_USHORT channelNo,
KDEFS_UCHAR securitySuite,
KDEFS_UCHAR enableLLCHeader);

Argument
securityPolicy Meaning of each bit in Security policy 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
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

broadcastenckey Broadcast encryption key used to secure broadcast


communication between a client and several servers.
authTagLen Length of GMAC Authentication tag of APDUs used
within Application Association
Possible values are
12
8

Confidential 62
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 GeneralAttrMethDescList


{
KDEFS_ULONG numDescriptors;
GENERAL_ATTR_METH_DESC
*generalAttrMethDesc;
KDEFS_UCHAR useWithList;
}GENERAL_ATTR_METH_DESC_LIST;

typedef struct GenAttrMethDesc


{
OBISCODE * obis_p;
KDEFS_USHORT ic;
KDEFS_UCHAR icVersion;
KDEFS_UCHAR attrMethIndex;
KDEFS_USHORT base;
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 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;

Confidential 63
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

}ENCODED_AXDR;

clientSystemTitle_p 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.
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 frame counter is required.
PublicKey Public key for signature verification
ChannelNo This is any ushort value given by user application that
can
be optionally used by application to distinguish the client
handle.
Securitysuite Security Suite of the security object used for the
Association. It Specifies the security algorithms
Available.
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.
Return
DECODED_PRIMARY_DAT Structure with list of DLMS__UNION and Cosem
A* 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 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.

Confidential 64
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.31 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().

void cleanUpDecodeAXDR(DECODED_PRIMARY_DATA * decodedData);

Argument
decodedData pointer returned by cosemDecodeAXDR
function.

1.32 cosemDecodeCompactFrameData
Whenever user receive a compact frame(in Buffer of IC 62 inside DLMS_UNION in case of getData()
OR in PUSH_STR in case of Push ), user shall pass the compact frame received, service and list of all
compact frame ASN1 strings. Library will use template ID of received compact frame and search in
ASN1 list to find out appropriate ASN1. Then library will decode APDU using the selected ASN1 and
fill the decoded data in DLMS_UNION(In the “compactBufVarValue” element of COMPACT_DATA
structure in DLMS_UNION)

DLMS_UNION * cosemDecodeCompactFrameData(KDEFS_UCHAR service,


void * serviceSpecificData_p,
COMPACT_FRAME_ASN_LIST asnList
);

Argument
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)
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.
Note:- IPUSH_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

Confidential 65
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.

AsnList List of ASN1 structures (each structure


having template ID and ASN1 string)
Return
Null pointer unknown error
Non zero 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.

1.33 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().

void cleanDecodedCompactFrameData(DLMS_UNION * data_p);

Argument
decodedData pointer returned by
cosemDecodeCompactFrameData function.

Confidential 66
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.34 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).

COM_HDR_ENC_RESULT* encodeComProfileParams(KDEFS_UCHAR comProfile,


KDEFS_USHORT apduLen,
KDEFS_USHORT wPortClient,
KDEFS_USHORT wPortServer,
KDEFS_UCHAR netWorkID,
KDEFS_UCHAR phyAddLen,
KDEFS_UCHAR* phyAddr)

Argument
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.
Return
0x0000 if the function succeeds; else nonzero if the function failed

1.35 cleanUpEncodedComHeader
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

Confidential 67
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

encodeComProfileParams() will not more be available.

KDEFS_USHORTcleanUpEncodedComHeader(COM_HDR_ENC_RESULT * comHeaderInfo)

Argument
comHeaderInfo COM_HDR_ENC_RESULT structure pointer returned by
library in encodeComProfileParams()
Return
0x0000 if the function succeeds; else nonzero if the function failed

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

DECODE_HDR_DATA* decodeComProfileParams(COM_HDR_ENC_DATA comHdrData)

Argument
comHdrData COM_HDR_ENC_DATA 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
Return
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

Confidential 68
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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;

Once this function returns with result=success, then user might have to further call decodexxx
functions.

1.37 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.

KDEFS_USHORT cleanUpDecodedComHeader(DECODE_HDR_DATA * comHeaderInfo)

Argument
comHeaderInfo DECODE_HDR_DATA structure pointer returned by
library in decodeComProfileParams()
Return
0x0000 if the function succeeds; else nonzero if the function failed

1.38 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 use to generate other HDLC frames like RR frame, SNRM, DISC etc.
ENCODED_PRIMARY_APDU * encodeHDLCrequest(KDEFS_UCHAR addressSize,
KDEFS_USHORT clntID,
KDEFS_USHORT serverID,
KDEFS_USHORT devAddr,
KDEFS_UCHAR windowRx,
KDEFS_UCHAR windowTx,
KDEFS_USHORT infoFieldLenRx,
KDEFS_USHORT infoFieldLenTx,
KDEFS_UCHAR serviceClass,
KDEFS_USHORT linkBufSz,
ENCODED_AXDR apduData,
KDEFS_UCHAR frameType,
KDEFS_UCHAR *rrr,
KDEFS_UCHAR *sss)

Confidential 69
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Argument
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 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 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

Confidential 70
DLMS/COSEM Client Source Code Library User Manual Version 3.15.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. 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.
Return
ENCODED_PRIMARY_APDU * Either NULL or a valid pointer. 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 EncodedPrimaryApdu


{
ENCODED_AXDR *cosemApdu;
KDEFS_USHORT blockCount;
} ENCODED_PRIMARY_APDU;

Confidential 71
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

typedef struct EncodedAXDR


{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

1.39 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.
ENCODED_PRIMARY_APDU * decodeHDLCrequest(ENCODED_PRIMARY_APDU apduData,
KDEFS_UCHAR addressSize,
KDEFS_USHORT clntID,
KDEFS_USHORT serverID,
KDEFS_USHORT devAddr,
KDEFS_UCHAR windowRx,
KDEFS_UCHAR windowTx,
KDEFS_USHORT infoFieldLenRx,
KDEFS_USHORT infoFieldLenTx,
KDEFS_ULONG cosemBufSize,
KDEFS_UCHAR *rrr,
KDEFS_UCHAR *sss)

Argument
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

Confidential 72
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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

Confidential 73
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Only valid for RR & T frame


Sss N( S ), Send sequence number of processed I frame.
Return
ENCODED_PRIMARY_APDU * 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.
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 EncodedPrimaryApdu
{
ENCODED_AXDR *cosemApdu;
KDEFS_USHORT blockCount;
} ENCODED_PRIMARY_APDU;

typedef struct EncodedAXDR


{
KDEFS_UCHAR *cosemDataBuf;
KDEFS_USHORT cosemDataLen;
}ENCODED_AXDR;

1.40 cleanUpEncodedHDLC
The function used to release the memory allocated by the encodeHDLCrequest() function.

KDEFS_USHORT cleanUpEncodedHDLC(ENCODED_PRIMARY_APDU * preparedAPDU)

Confidential 74
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Argument
ENCODED_PRIMARY_APDU * Pointer returned by the cleanUpEncodedHDLC()
Return
Result SUCCESS or FAILURE.

1.41 cleanUpEncodedHDLC
The function used to release the memory allocated by the encodeHDLCrequest() function.

KDEFS_USHORT cleanUpEncodedHDLC(ENCODED_PRIMARY_APDU * preparedAPDU)

Argument
ENCODED_PRIMARY_APDU * Pointer returned by the cleanUpEncodedHDLC()
Return
Result SUCCESS or FAILURE.
1.42 cleanUpDecodedHDLC
The function used to release the memory allocated by the decodeHDLCrequest() function.

KDEFS_USHORT cleanUpDecodedHDLC (ENCODED_PRIMARY_APDU * preparedAPDU)

Argument
ENCODED_PRIMARY_APDU * Pointer returned by the cleanUpDecodedHDLC()
Return
Result SUCCESS or FAILURE.

1.43 Call Sequence


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.

Confidential 75
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

7. EncodeHDLCrequest() to send DISC frame.


8. DecodeHDLCrequest() to decode UA response. Return NULL for DM frame.

5 Special functions
1.44 getSystemTitleFromPushNotification
This function is used to get system title from a Data notification APDU.

KDEFS_USHORT getSystemTitleFromPushNotification(KDEFS_UCHAR *APDU,


KDEFS_UCHAR *serverSystemTitle,
KDEFS_UCHAR
*serverSystemTitlePresent)

Argument
APDU Received APDU passed by application to library
serverSystemTitle Library will search for system title in received APDU and
update in this pointer
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.
Return
0x0000 if the function succeeds; else nonzero if the function failed

1.45 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.

void setFrameCouter(void *clientHandle,


KDEFS_ULONG frameCounterToUse);

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

Confidential 76
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.46 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.
ASSO_PARAMS *getAssociationParameters( void *ClientHandle);

Argument
clientHandle Handle returned by initClient()
Return

1.47 updateHdlcAdvancedSettings
This function is used to configure a delay between the sending of HDLC frames. This is an optional
function.

KDEFS_USHORT updateHdlcAdvancedSettings(void *clientHandle,


KDEFS_USHORT hdlcSendDelay);

Argument
clientHandle Handle returned by initClient()
hdlcSendDeley Delay between the frames in
milliseconds
Return
0x0000 Success

1.48 updateSerialAdvancedSettings
This is an optional function used to update the serial port advanced settings. This function is available
for windows platform only.

KDEFS_USHORT updateSerialAdvancedSettings(void *clientHandle,


SER_ADV_PORT_SETTINGS *portSettings);

Argument
clientHandle Handle returned by initClient()
portSettings Pointer to the structure containing the serial port

Confidential 77
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

parameters to be updated. Definition as follows


typedef struct SerAdvPortSettings
{
KDEFS_ULONG readIntervalTimeout; /*
Maximum time between read chars. */

KDEFS_ULONG readTotalTimeoutMultiplier;/*
Multiplier of characters. */

KDEFS_ULONG readTotalTimeoutConstant; /*
Constant in milliseconds. */

KDEFS_ULONG writeTotalTimeoutMultiplier;/*
Multiplier of characters. */

KDEFS_ULONG writeTotalTimeoutConstant;
/* Constant in milliseconds. */

}SER_ADV_PORT_SETTINGS;
Return
0x0000 Success
Non zero indicates error. See Appendix A for detailed list
of error codes
1.49 sendPacket
This function helps the application to send custom packets over existing connection (Only HDLC,
Mode-E, UDP and TCP are supported now). The function shall wait for the configured amount of time
for responses and return it back to application.

ENCODED_AXDR *sendpacket(void* clientHandle,


KDEFS_UCHAR* data,
KDEFS_USHORT datalen,
KDEFS_ULONG waitingduration,
KDEFS_USHORT resplen)

Argument
clientHandle Handle returned by initClient()
data Pointer to data.
datalen Length of data to be sent.
waitingduration Maximum duration to be wait for response. Value
0 make the function to return immediately after
sending data.

Confidential 78
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
Return
NULL Failure or No response data.
ENCODED_AXDR * A structure containing the pointer to data and
length of the data.

1.50 cleanUpMemoryforsendpacket
This function used to release the memory allocated by sendPacket() function.

void cleanUpMemoryforsendpacket(ENCODED_AXDR* encodedapdu);

Argument
encodedapdu Data return by sendPacket ()
Return

6 Registering diagnostic call back functions


1.51 registerErrCallback
Error Reporting Call back function is registered using API : registerErrCallback()
void registerErrCallback(ERROR_CALLBACK errCbk);

Proto-type of error reporting call back function ERROR_CALLBACK errorCallback is shown below
typedef void (*ERROR_CALLBACK) (void *clientHandle,
KDEFS_USHORT ErrorCode,
KDEFS_USHORT ChannelNo );

Arguments
clientHandle uniquely identifies the communication channel
ErrorCode Error code 1 : error notification from stack
ChannelNo number indicating the channel instance

Call back function will be called by library to indicate error condition. In the current version stack, the
function shall be invoked only for socket termination from server side.
1.52 RegisterDiagCallback
Diagnostic callback function is registered using API : registerDiagCallback().

Confidential 79
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

void registerDiagCallback(KDIAG_CALLBACK diagCbk);

void registerDiagCallback(KDIAG_CALLBACK diagCbk);

Proto-type of Diagnostic callback function KDIAG_CALLBACK kdiagCallback is shown below

typedef void (*KDIAG_CALLBACK) ( void *clientHandle,


KDEFS_UCHAR layerId,
KDEFS_UCHAR diagType,
const KDEFS_UCHAR *pMsg,
KDEFS_UINT msgLen,
KDEFS_USHORT ChannelNo);

Arguments
clientHandle uniquely identifies the communication channel
layerId identifies the layer that produces the diagnostic
message
diagType Identifies the type of message
pMsg reference to the message/ buffer
msgLen length of message/ buffer,
ChannelNo number indicating the channel instance

1.53 registerSecurityCallbacks
Register Security callback function is registered using API .Library shall use the registered
function to encrypt/decrypt, prepare hash values.

Confidential 80
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Void registerSecurityCallbacks(CRYPT_CALLBACK encryptFunPtr,


CRYPT_CALLBACK decryptFunPtr,
HASH_CALLBACK hashFunPtr,
SIGNGEN_CALLBACK sigGenFunPtr,
SIGNVER_CALLBACK sigVerFunPtr,
PARSE_CRT_CALLBACK parseCRTFunPtr,
DIG_KEY_PAIR_GEN_CALLBACK DigKeyPairFunPtr,
GET_CRT_CALLBACK getCRTFunPtr,
GEN_SHARED_KEY_CALLBACK
GenSharedKeyFunPtr,
KEY_DERIV_CALLBACK keyDerivFunPtr,
ASSYM_HASH_CALLBACK assymHashGenFunPtr,
GET_DIG_KEYS_CALLBACK getSignatureKeysFunPtr)

Void registerSecurityCallbacks(CRYPT_CALLBACK encryptFunPtr,


CRYPT_CALLBACK decryptFunPtr,
HASH_CALLBACK hashFunPtr,
SIGNGEN_CALLBACK sigGenFunPtr,
SIGNVER_CALLBACK sigVerFunPtr,
PARSE_CRT_CALLBACK parseCRTFunPtr,
DIG_KEY_PAIR_GEN_CALLBACK DigKeyPairFunPtr,
GET_CRT_CALLBACK getCRTFunPtr,
GEN_SHARED_KEY_CALLBACK
GenSharedKeyFunPtr,
KEY_DERIV_CALLBACK keyDerivFunPtr,
ASSYM_HASH_CALLBACK assymHashGenFunPtr,
GET_DIG_KEYS_CALLBACK getSignatureKeysFunPtr)

Arguments
encryptFunPtr Encryption callback function pointer
decryptFunPtr - Decryption callback function pointer
hashFunPtr - Hashing callback function pointer

sigGenFunPtr - Signature Generation callback function pointer


sigVerFunPtr - Signature Verification function pointer
parseCRTFunPtr - parseCertificate_CRT function callback function
pointer
digKeyPairFunPtr - Digital Key Pair generation callback function
pointer
getCRTFunPtr - getDigCertificateCRT function callback function
pointer
genSharedKeyFunPtr - GenerateSharedKey_SHA256 function callback
function pointer

Confidential 81
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

keyDerivFunPtr - KeyDerivationFunction function callback


function pointer
assymHashGenFunPtr - assymHashGenerate function callback function
pointer
getSignatureKeysFunPtr - get the digital signature key required using this
callback function pointer

CRYPT_CALLBACK defined as :
typedef void (*CRYPT_CALLBACK) ( KDEFS_UCHAR encMethod,
KDEFS_UCHAR *key,
KDEFS_USHORT keyLen,
KDEFS_UCHAR *plainText_p,
KDEFS_ULONG ptLen,
KDEFS_UCHAR *cipherText_p,
KDEFS_UCHAR *initialisationVector,
KDEFS_USHORT ivLen,
KDEFS_UCHAR *aad,
KDEFS_ULONG aadLen,
KDEFS_UCHAR *authTag,
KDEFS_ULONG authTagLen);
The function securityEncrypt encrypts the data for HLS Authentication and data transport security and
the function securityDecrypt performs the corresponding decryption.The variable definitions are as
follows:
Parameters
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 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

Confidential 82
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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 -The Length of authTagLen .

HASH_CALLBACK defined as :
typedef void (*HASH_CALLBACK) ( KDEFS_UCHAR hashMethod,
KDEFS_UCHAR *plainText_p,
KDEFS_USHORT ptLen,
KDEFS_UCHAR *cipherText_p);

The function securityHash 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

Parameters

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

Confidential 83
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

SIGNGEN_CALLBACK defined as :
typedef void unsigned int(*SIGNGEN_CALLBACK)(unsigned char *privateKey,
const unsigned char *plainText,
unsigned long ptLen,
unsigned long indexNotUsed,
unsigned char *sig,
unsigned long *sigLen,
unsigned char DER_Encoding,
unsigned char secSuite);

Parameters

privateKey The private key used for signing is held in


privateKey pointer

plaintext This function is used to generate digital


signature on the data pointed to by the
plainText pointer

ptLen length of plainText ptLen.,

indexNotUsed indexNotUsed indicate the index position


which shall not be considered for signature
generation

Sig The generated signature is held in

sigLen length of sig pointer in sigLen

DER_Encoding flag DER_Encoding is 1 if DER encoding is to


be used.
SecuritySuite of the security object used for
secSuite
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

SIGNVER_CALLBACK defined as :
typedef void (*SIGNVER_CALLBACK)( unsigned char *publicKey,
const unsigned char *plainText_p,
unsigned long ptLen,
unsigned long indexNotUsed,

Confidential 84
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

unsigned char *sig,


unsigned long slen,
unsigned char DER_Encoding,
unsigned char secSuite);

Parameters

privateKey The public key used for verification is held in


publicKey pointer

plaintext This function is used to generate digital


signature on the data pointed to by the
plainText pointer

ptLen length of plainText ptLen.,

indexNotUsed indexNotUsed indicate the index position


which shall not be considered for signature
generation

Sig The generated signature is held in

sigLen length of sig pointer in sigLen

DER_Encoding flag DER_Encoding is 1 if DER encoding is to


be used.

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

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. indexNotused indicate the index position
which shall not be considered while signature verification.

PARSE_CRT_CALLBACK defined as :
typedef void (*PARSE_CRT_CALLBACK)(const unsigned char *cert,
unsigned int certLen,
unsigned char *certificate_publicKey,
unsigned char *certificate_Signature,

Confidential 85
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

unsigned char *signLen


unsigned char secSuite);

Parameters

Cert input certificate, stored in cert pointer

certLen cert pointer length in certLen

certificate_publicKey returns the public key stored in the certificate


in certificate_publicKey

certificate_Signature the digital signature pointer

signLen length of certificate_Signature

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

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 in
certificate_publicKey pointer.

DIG_KEY_PAIR_GEN_CALLBACK defined as:


typedef void(*DIG_KEY_PAIR_GEN_CALLBACK)(unsigned char *privateKey,
unsigned char *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.

Parameters

privateKey Pointer of privateKey

publicKey Pointer of publicKey

GET_CRT_CALLBACK defined as :
typedef void(*GET_CRT_CALLBACK)(int *certBuf_Len_CRT,
unsigned char *Cert_Buf

Confidential 86
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

unsigned char *PrivateKey,


unsigned char *PublicKey,
unsigned char *PublicKey2,
unsigned char flag,
unsigned char *ServerSystemTitle,
unsigned char secSuite);

Parameters

certBuf_Len_CRT length of Cert_Buf pointer

Cert_Buf Cert_Buf pointer by the function

PrivateKey PrivateKey to generate digital certificate

PublicKey PublicKey to generate digital certificate

PublicKey2 not used in the current stack

flag not used in the current stack

ServerSystemTitle server system title

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

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.

GEN_SHARED_KEY_CALLBACK defined as:


typedef void(*GEN_SHARED_KEY_CALLBACK)(unsigned char *PrivateKeyServer,
unsigned char *PublicKeyClient,
unsigned char *result,
unsigned char *secSuite);

Confidential 87
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Parameters

PrivateKeyServer private key of the Server

PublicKeyClient public key of the client

result pointer to store result generated shared key

secSuite security suite used into the secSuite argument.

This function is used in the Key Agreement method (IC64 version 1, method 3) to generate a shared
key. The user 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.

KEY_DERIV_CALLBACK defined as :

typedef void(*KEY_DERIV_CALLBACK)(unsigned char *cntr,


unsigned char *sharedSecret,
unsigned char *algID,
unsigned char *SystitleClient,
unsigned char *SystitleServer,
unsigned char *DerivedKey,
unsigned char secSuite);

Parameters

cntr Counter based on suite

sharedSecret generated shared key

algID AlgoID based on suite

SystitleClient Client System title

SystitleServer server system title

DerivedKey Pointer to store the new key

secSuite security suite used into the secSuite argument.

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 recured to pass the generated

Confidential 88
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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.
ASSYM_HASH_CALLBACK defined as :
typedef void(*ASSYM_HASH_CALLBACK)(unsigned char hashMethod,
unsigned char *plainText_p,
unsigned char ptLen,
unsigned char *hash);

Parameters

hashMethod Hashing algorithm used (3 for MD5 and 4 for


SHA1, 6 for SHA256)

plainText_p pointer contains the plaintext

ptLen length of plaintext

hash Pointer to store the return 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.

GET_DIG_KEYS_CALLBACK defined as :
typedef void (*GET_DIG_KEYS_CALLBACK)(KDEFS_UCHAR *publicUkey,
KDEFS_UCHAR *privateUkey,
KDEFS_UCHAR *publicVkey,
KDEFS_UCHAR publicUkeyLen,
KDEFS_UCHAR privateUkeyLen,
KDEFS_UCHAR publicVkeyLen,
void *dlmsInstance,
KDEFS_UCHAR keyType,
KDEFS_UCHAR flag,
KDEFS_USHORT ChannelNo,
KDEFS_UCHAR secSuite,
KDEFS_UCHAR* SystitleServer);
Parameters
publicUkey Server Public key used for signature verification
privateUkey Client Private Key used for Signature Generation
publicVkey Client public key
publicUkeyLen Client Public key length
privateUkeyLen Client Private Key length
publicVkeyLen server public key length
dlmsInstance uniquely identifies the communication channel/ client Handle

Confidential 89
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

keyType 0 : Public Key of Server


1 : Private Key of Client
2 : Public Key of Client
flag 0 : GET operation
1 : SET operation
ChannelNo channelNo used to distinguish the client handle
secSuite
security suite used into the secSuite argument.
SystitleServer server system title

This function is used to pass the values of the public key of server, private key of client or the public
key
of the client to and from the stack depending upon the value of the flag and keyType. If flag = 0, the
user
is required to fill the required key into the specific pointer so that it can be used by the stack and flag =
1
requires the user to store the specific key indicated by the keyType from the pointer. KeyType = 0
indicates the public key of the server, the pointer associated is publicUkey and length will be in
publicUkeyLen. KeyType = 1 indicates the private key of the client, the pointer associated is
privateUkey
and length will be in publicVkeyLen. KeyType = 2 indicates the public key of the client, the pointer
associated is publicVkey and length will be in publicVkeyLen. ChannelNo is the number indicating the
channel instance.

1.54 registerCertCallback
Registers the getCertificate callback function: registerCertCallback()

void registerCertCallback(CERT_CALLBACK certCbk)

Proto-type of Register certificate callback function CERT_CALLBACK certCallback is shown below

typedef void (*CERT_CALLBACK) ( KDEFS_INT *certSignLen,


KDEFS_UCHAR *certBuffer,
KDEFS_UCHAR *privkey,
KDEFS_UCHAR *SystemTitle,
KDEFS_UCHAR SecuritySuite,
KDEFS_USHORT ChannelNo);

Parameters
certSignLen Certificate length
certBuffer Pointer to which certificate need to be copied
privkey Private key corresponding to certificate
SystemTitle server system title

Confidential 90
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
ChannelNo number indicating the channel instance

1.55 registerWrapperAppDataCallback

void registerWrapperAppDataCallback(APPLNDATA_CALLBACK applnCbk);

Registers the wrapper application callback function using API :


registerWrapperAppDataCallback(). The registered callback function will get invoked on
receiving any valid frames on wrapper layer.

Proto-type of Register wrapper application data callback function APPLNDATA_CALLBACK


applnDataWrapperCallback is shown below

typedef KDEFS_USHORT (*APPLNDATA_CALLBACK)


( KDEFS_UCHAR * applnDataBuf,
KDEFS_ULONG appDataLen,
void *clientHandle,
KDEFS_UCHAR wait,
KDEFS_USHORT recvPortClient,
KDEFS_USHORT recvWPortServer,
KDEFS_UCHAR result);

Parameters
applnDataBuf Buffer containing Application data
appDataLen Application data length
clientHandle Unique identifier of client instance
wait 1: not wait for response timeout
0 : waiting for response timeout
recvPortClient Received wrapper Client ID
recvWPortServer Received wrapper Server ID
result 0 indicate a valid DLMS packet, 1 indicate an invalid packet

1.56 registerPLCAppDataCallback
Registers the PLC application data callback function using API : registerPLCAppDataCallback()

Confidential 91
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

void registerPLCAppDataCallback(APPLNDATA_CALLBACK applnCbk);

Proto-type of Register PLCapplication data callback function APPLNDATA_CALLBACK


applnDataPLCCallback is shown below

Confidential 92
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

typedef KDEFS_USHORT (*APPLNDATA_CALLBACK)


( KDEFS_UCHAR * applnDataBuf,
KDEFS_ULONG appDataLen,
void *clientHandle,KDEFS_UCHAR wait,
KDEFS_USHORT recvPortClient,
KDEFS_USHORT recvWPortServer);

typedef KDEFS_USHORT (*APPLNDATA_CALLBACK)


( KDEFS_UCHAR * applnDataBuf,
KDEFS_ULONG appDataLen,
void *clientHandle,KDEFS_UCHAR wait,
KDEFS_USHORT recvPortClient,
KDEFS_USHORT recvWPortServer);

7 Structures and Unions


1.57 DLMS_UNION
The DLMS_UNION 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 ICStructs.h file for complete structure definitions.
In case of Set/Write the user-application must also handle the freeing of memory allocated to the
structure (In Get/Read, user should call the cleanupMemory() function in the library will do the
cleaning/free)

typedef struct DLMSClasses

{
KDEFS_USHORT result;
KDEFS_UCHAR service;
GENERIC_IC generic_Ic;
DATA data;
REGISTER registerIc;
EXTENDED_REGISTER extRegister;
DEMAND_REGISTER dmdRegister;
REGISTER_ACTIVATION regAct;
PROFILE profile;

Confidential 93
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

CLOCK clock;
SCRIPT_TABLE scriptTable;
SCHEDULE schedule;
SPEC_DAY_TABLE specDaysTable;
ACTIVITY_CALENDAR actCal;
REG_MONITOR regMonitor;
ASSOC_SN assocSN;
ASSOC_LN assocLN;
SAP_ASSIGNMENT sapAssign;
IMAGE_TRANSFER imageTransfer;
SINGLE_ACTION_SCHEDULE singleActionSchedule;
IEC_LOCAL_PORT iecLocal;
MBUS_SLAVEPORT_SETUP mbusSlavePortSetup;
UTILITY_TABLE utilityTable;
PSTN_MODEM_CONFIG pstnMC;
PSTN_AUTOANSWER pstnAutoAnswer;
AUTO_CONNECT autoConnect;
HDLC_SETUP hdlcSetup;

PUSH_SETUP pushSetup;
TCPUDP_SETUP tcpUdpSetup;
Ipv4_SETUP iPv4Setup;
Ipv6_SETUP ipv6Setup;
ETHERNET_SETUP ethernetSetup;
PPP_SETUP pppSetup;
GPRS_MODEM_SETUP gprsModemSetup;
SMTP_SETUP smtpSetup;
GSM_DIAG gsmDiag;
LLC432_SETUP llc432Setup;
LLC8022_2T1_SETUP llc8022T1Setup;
LLC8022_2T2_SETUP llc8022T2Setup;
LLC8022_2T3_SETUP llc8022T3Setup;
REGISTER_TABLE registerTable;
SECURITY_SETUP securitySetup;
COMPACT_DATA compactData;

Confidential 94
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

PARAMETER_MONITOR paramMonitor;
SENSOR_MANAGER sensorManager;
ARBITRATOR arbitratr
DISC_CONTROL discControl;
LIMITER limiter;
MBUS_CLIENT mbusClient;
WIRELESS_MODEQ_CHANNEL wirelessModeQChannel;
MBUS_MASTERPORT_SETUP mbusMasterPortSetup;
CL_432_SETUP cl432Setup;
PRIME_PLC_PHY_COUNTER primePLCPhyCounter;
PRIME_PLC_MAC_SETUP primePLCMACSetup;
PRIME_PLC_MAC_FUNC_PARAMS primePLCMACFuncParams;
PRIME_PLC_MAC_COUNTER primePLCMACCounter;
PRIME_PLC_MAC_NETWORK_ADMIN_DATA primePLCMACNwkAdminData;
PRIME_PLC_APPL_IDENT primePLCApplIdent;
G3_PLC_MAC_COUNTER g3PLCMacCounter;
G3_PLC_MAC_SETUP g3PLCMacSetup;
G3_PLC_ADAPT_SETUP g3PLCAdaptSetup;
NTP_SETUP ntpSetup;
ACCOUNT_OBJ accountObject;
CREDIT_OBJ creditObject;
CHARGE_OBJ chargeObject;
TOKEN_OBJ tokenObject;
#if (UK_SPECIFICATION_SUPPORT == KDEFS_TRUE)
EXTENDED_DATA extendedData;
CoTS_OBJECT coTsObject;
ZIGBEE_DRLC_CLUSTER_OBJECT zigbeeDRLCClusterObject;
BLOCK_TARIFF_CONFGTN_OBJECT blockTariffConfgtnObject;
#endif
ZIGBEE_SAS_JOIN_OBJECT zigbeeSASJoinObject;
ZIGBEE_SAS_FRAGMENTATION_OBJECT zigbeeSASFragmentationObject;
ZIGBEE_SETC_CONTROL_OBJECT zigbeeSETCControlObject;
ZIGBEETUNNEL_SETUP zigbeeTunnelSetup;
ZIGBEE_SAS_STARTUP_OBJECT zigbeeSASStartupObject;
RATE_PLAN ratePlan;

Confidential 95
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

}
DLMS_UNION;

It is suggested to read and understand cmdLineDisplayData() function in sample project (


LINIXDLMSCLIENT/ ClientApp.c or WinDLMSClient/WinDLMSClient.c ) to get a better idea
about DLMS_UNION structure and its usage

1.58 ACTION_UNION
The ACTION_UNION 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.

typedef struct ActionStruct


{
KDEFS_USHORT result;
GENERIC_IC_ACTION genericAction;
REG_ACTN regAct;
EXT_REG_ACTN extRegAct;
DMD_REG_ACT dmdRegAct;
REG_ACT_ACT regActivationAct;
PROF_ACTN profAct;
CLOCK_ACTN clockAct;
SCR_TAB_ACTN scrAct;
SCHEDULE_ACTN schedActn;
SPEC_DAY_TAB_ACTN spDayAct;
ACT_CAL_ACTN actCalAct;
ASSOC_LN_ACTN assocLNAct;
ASSOC_SN_ACTN assocSNAct;
SAP_ASSIGN_ACTN sapAct;
IPv4_SETUP_ACTN ipv4Act;
IPv6_SETUP_ACTN ipv6Act;
IMG_TX_ACTN imgTxAct;
REG_TABLE_ACTN regTableAct;
COMPACT_DATA_ACTN compactDataAct;
PSTN_AUTO_CONNECT_ACTN pstnAutoConnectAct;
PUSH_ACTN pushAct;
SENSOR_MANAGER_ACTN sensorManagerAct;
ARBITRATR_ACTN arbitratorAct

Confidential 96
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

DISC_CONTROL_ACTN discCntrlAct;
SECURITY_CONTROL_ACTN secControlAct;
PARAMETER_MONITOR_ACTN paramMonitorAct;
MBUS_CLIENT_ACTN mbusClientAct;
EXT_DATA_ACTN extDataAct;
CL432SETUP_ACTN cl432SetupAct;
PRIMEPLC_PHY_LYR_CNTR_ACTN primePLCPhyLyrCntrAct;
PRIMEPLC_MAC_CNTR_ACTN primePLCMACCntrAct;
PRIMEPLC_NWK_ADMIN_DATA_ACTN primePLCNwkAdminDataAct;
G3_PLC_MAC_COUNTER_ACTN g3PLCMacCounterAct;
G3_PLC_MAC_SETUP_ACTN g3PLCMacSetupAct;
NTP_SETUP_ACTN ntpSetupActn;
ACCOUNT_ACTN accountAct;
CREDIT_ACTN creditAct;
CHARGE_ACTN chargeAct;
TOKEN_ACTN tokenAct;
COTS_OBJ_ACTN coTsObjAct;
ZIGBEE_DRLC_CLUSTER_OBJECT_ACTN zigbeeDRLCClusterObjAct;
BLOCK_TARIFF_CONFG_OBJ_ACTN blockTariffConfgobjAct;
ZIGBEE_SETC_CONTROL_OBJECT_ACTN zigbeeSETCControlObjActn;
} ACTION_UNION;

Confidential 97
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

8 Unsolicited data communication

DLMS supports two kinds of unsolicited(or server initiated) data communication services – Event
notification and Push. DLMS Client library supports inbound connection and/or inbound receipt of
unsolicited data(coming as Event notification request or Data Notification request) from Server. DLMS
Client stack includes functions to handle the state transitions as well as to process the inbound data and
notify client user about Event or Push data. How ever there is equally significant role for user in terms
of initializing sockets(listening for connections), and shall take care of the following

• Accept inbound TCP connections

• On TCP connection accept, call stack function – initClient()

• Receive data from TCP socket and write into stack wrapper input buffer

• Call stack functions(wrapperProcess() and cosemProcess() ) to process received unsolicited


data

All the above functionality are illustrated in sample project(WinDLMSClient / LINUXDLMSCLIENT)


in eventComm_illustration() function. It is highly recommended to read and understand
eventComm_illustration() function and the threads started from this function. User may also
modify these code if found necessary.

APIs introduced for this purpose are explained below

1.59 Registering call back functions

1.59.1 Event call backs

Event call back function is registered using API : registerEventCallback(). On receipt of an event
notification APDU from server, Client stack will process received event and subsequently invoke
application callback function registered via registerEventCallback().
void registerEventCallback(EVENT_CALLBACK eventCbk);

Proto-type of call back function EVENT_CALLBACK eventCbk is shown below


typedef void (*EVENT_CALLBACK)( void *clientHandle,
KDEFS_USHORT wCport,
KDEFS_USHORT wSport,
KDEFS_USHORT ChannelNo);

Call back function 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 – how ever event information is not send in

Confidential 98
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

call back function. Client user-application shall retrieve events by calling API : getEvent()
EVENT_STR* getEvent( void *clientHandle,KDEFS_SHORT *len);

1.59.2 Push call backs

Data push call back function is registered using API : registerPushCallback(). On receipt of an Push
Data Notification APDU from server, Client stack will process received Data and subsequently invoke
application callback function registered via registerPsuCallback().

void registerPushCallback(PUSH_CALLBACK pushCbk);

Proto-type of call back function PUSH_CALLBACK eventCbk is shown below


typedef void (*PUSH_CALLBACK) ( PUSH_STR *pushData,
void *clientHandle,
KDEFS_USHORT wCport,
KDEFS_USHORT wSport,
KDEFS_USHORT ChannelNo);

Push call back function notifies user-application about receipt of push data as well as provide the data
received from server.
1.60 initIncomingPort
This is a stack function and user just need to call this on receipt of a TCP socket connection.

KDEFS_USHORT initIncomingPort(void *clientHandle,


void *Sock,
KDEFS_USHORT wClientAddr,
KDEFS_USHORT wServerAddr)

1.61 setParamsUnsolicitedCommunication
This function is used to initialize the parameters for unsolicited communication. This function shall be

Confidential 99
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

called to enable security features to data notification service.

KDEFS_USHORT setParamsUnsolicitedCommunication(void *clientHandle,


KDEFS_UCHAR * authenticationKey_p,
KDEFS_UCHAR * encryptionKey_p,
KDEFS_UCHAR * serverSystemTitle,
KDEFS_UCHAR * clientSystemTitle,
KDEFS_USHORT serverSystemTitleLen ,
KDEFS_ULONG authTagLen,
KDEFS_UCHAR appContext,
KDEFS_UCHAR securityPolicy,
KDEFS_UCHAR SecuritySuite,
KDEFS_UCHAR * pubKeyServer_p);

1.62 plafInitIncomingPort
Stack calls this function from initIncomingPort(). User need to implement this function. A sample
implementation is provided for Windows and Linux. Also Section 6.5 explains the sample
implementation of this function.

KDEFS_USHORT plafInitIncomingPort( void *Sock,

DLMS_GLOBALS *dlmsInstance);

• Sock – socket connected by TCP Server / local UDP socket


• ClientHandle – Client handle returned by initClient()

1.63 Retrieving events


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().

It is to be noted that this is required only for event and not required for push.
EVENT_STR* getEvent( void *clientHandle,KDEFS_SHORT *len);

Confidential 100
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

1.64 cleanPushData

void cleanPushData(PUSH_STR* push)

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

1.65 cleanEventData

void cleanEventData(EVENT_STR* eventData,KDEFS_USHORT len)

After using event data received via Event call back function, user shall call cleanEventData() to free
dynamically allocated memory
Once a TCP incoming connection is received, platform interface create two threads
( plafIncomingPortReadThread() and IncomingPortEventReadHandling() )and one
client instance(instantiated by calling initClient()). These resources will be free-d by
platform interface itself when it detects the TCP connection lost. Instead of this
mechanism it is also possible for Client user itself to free these resources by
calling closePort(see 1.6)

9 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.c file available in the sample
application folder.

1.66 Encrypt/Decrypt
unsigned char securityEncrypt(
unsigned char encMeth,
unsigned char *key,
unsigned short keyLen,
unsigned char *plainText_p,
unsigned short ptLen,
unsigned char *cipherText_p,
unsigned char *initialisationVector,
unsigned short ivLen,
unsigned char *aad,
unsigned short aadLen,
unsigned char *authTag
unsigned long authTagLen);

unsigned char securityDecrypt(


unsigned char encMeth,
unsigned char *key,
unsigned short keyLen,
unsigned char *plainText_p,
unsigned short ptLen,

Confidential 101
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

unsigned char *cipherText_p,


unsigned char *initialisationVector,
unsigned short ivLen,
unsigned char *aad,
unsigned short aadLen,
unsigned char *authTag
unsigned long authTagLen);

The function securityEncrypt encrypts the data for HLS Authentication and data transport security
and the function securityDecrypt 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 -The Length of authTagLen .

1.67 Generate Hash


unsigned char securityHash(
unsigned char hashMethod,
unsigned char *plainText_p,
unsigned char ptLen,
unsigned char *cipherText_p)

The function securityHash 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

Confidential 102
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

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
1.68 Digital Signature
The functions used to implement security suite 1 are as follows:
unsigned char signatureGeneration(unsigned char *privateKey,
const unsigned char *plainText,
unsigned long ptLen,
unsigned long indexNotUsed,
unsigned char *sig,
unsigned long *sigLen,
unsigned char DER_Encoding)
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.

unsigned int signatureVerification( unsigned char *publicKey,


const unsigned char *plainText_p,
unsigned long ptLen,
unsigned long indexNotUsed,
unsigned char *sig,
unsigned long slen,
unsigned char DER_Encoding)

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.

unsigned char parseCertificate_CRT(const unsigned char *cert,


unsigned int certLen,
unsigned char *certificate_publicKey,
unsigned char *certificate_Signature,
unsigned char *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.

unsigned char digitalSigKeyPairGen(unsigned char *privateKey,


unsigned char *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.

unsigned char getDigCertificateCRT(int *certBuf_Len_CRT,


unsigned char *Cert_Buf,
unsigned char *PrivateKey,
unsigned char *PublicKey,
unsigned char *PublicKey2,
unsigned char flag)
This function is used to obtain a digital certificate on passing the private key and public key in the PrivateKey

Confidential 103
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

and PublicKey pointers. The generated certificate is stored into the Cert_Buf pointer bythe function, with length
in the certBuf_Len_CRT pointer. The arguments PublicKey2 and flag are not used in the current stack.

unsigned char GenerateSharedKey_SHA256(unsigned char *PrivateKeyServer,


unsigned char *PublicKeyClient,
unsigned char *result,
unsigned char *Algo_ID,
unsigned char *Server_Sys,
unsigned char *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.

unsigned char KeyDerivationFunction(unsigned char *cntr,


unsigned char *sharedSecret,
unsigned char *algID,
unsigned char *SystitleClient,
unsigned char *SystitleServer,
unsigned char *DerivedKey,
unsigned char 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 argumemnt. The new
key to be used will be returned in the DerivedKey pointer.

unsigned char assymHashGenerate(unsigned char hashMethod,


unsigned char *plainText_p,
unsigned char ptLen,
unsigned char *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.

KDEFS_UCHAR getSignatureKeys(KDEFS_UCHAR *publicUkey,


KDEFS_UCHAR *privateUkey,
KDEFS_UCHAR *publicVkey,
KDEFS_UCHAR publicUkeyLen,
KDEFS_UCHAR privateUkeyLen,
KDEFS_UCHAR publicVkeyLen,
DLMS_GLOBALS *dlmsInstance,
KDEFS_UCHAR keyType,
KDEFS_UCHAR flag)
This function is used to pass the values of the public key of server, private key of client or the public key of the
client to and from the stack depending upon the value of the flag and keyType. If flag = 0, the user is required to
fill the required key into the specific pointer so that it can be used by the stack and flag = 1 requires the user to
store the specific key indicated by the keyType from the pointer. KeyType = 0 indicates the public key of the
server, the pointer associated is publicUkey and length will be in publicUkeyLen. KeyType = 1 indicates the
private key of the client, the pointer associated is privateUkey and length will be in publicVkeyLen. KeyType = 2
indicates the public key of the client, the pointer associated is publicVkey and length will be in publicVkeyLen.

1.69 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(CRYPT_CALLBACK encryptFunPtr,

Confidential 104
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

CRYPT_CALLBACK decryptFunPtr,
HASH_CALLBACK hashFunPtr,
SIGNGEN_CALLBACK sigGenFunPtr,
SIGNVER_CALLBACK sigVerFunPtr,
PARSE_CRT_CALLBACK parseCRTFunPtr,
DIG_KEY_PAIR_GEN_CALLBACK digKeyPairFunPtr,
GET_CRT_CALLBACK getCRTFunPtr,
GEN_SHARED_KEY256_CALLBACK
genSharedKey256FunPtr,
KEY_DERIV_CALLBACK keyDerivFunPtr,
ASSYM_HASH_CALLBACK assymHashGenFunPtr,
GET_DIG_KEYS_CALLBACK getSignatureKeysFunPtr)

The arguments encryptFunPtr, decryptFunPtr, hashFunPtr, sigGenFunPtr, sigVerFunPtr, parseCRTFunPtr,


digKeyPairFunPtr, getCRTFunPtr, genSharedKey256FunPtr, keyDerivFunPtr, assymHashGenFunPtr,
getSignatureKeysFunPtr are the pointers to the callback functions securityEncrypt, securityDecrypt,
securityHash, signatureGeneration, signatureVerification, parseCertificate_CRT, digitalSigKeyPairGen,
getDigCertificateCRT, KeyDerivationFunction, assymHashGenerate and getSignatureKeys respectively
defined by the user.

void registerCertCallback(CERT_CALLBACK certCbk)


The above callback function is used to get the certificate to be filled into the AARQ during HLS-7 mechanism.
This function returns a digital signature key pair and the certificate generated with that keypair. The stack stores
the key pair into its DLMS_GLOBALs instance and fills the returned certificate into the AARQ.
typedef void (*CERT_CALLBACK) ( KDEFS_INT *certSignLen,
KDEFS_UCHAR *certBuffer,
KDEFS_UCHAR *privkey,
KDEFS_UCHAR *pubKey,
DLMS_GLOBALS *dlmsInstance);

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.

10 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 (i.e. with the same clientHandle) at the same time. It is
recommended to use one clientHandle dedicatedly for one server and not reuse for another server
without closing the clientHandle.

Confidential 105
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

11 Image transfer
The Image Transfer IC models the mechanism for transferring binary files, called firmware images to
COSEM servers. An illustration is given with the code. The step following in image transfer procedure
is (The process till establishing association is not described here. Disconnecting the association
/connection is not in the scope of this section.)
Step 1: Get Image block size from server. User can skip this stage if the value is known. For HDLC
communication profiles, client determines the final image block size so that it doesn't exceed the
maximum information field size that can be send from the client. For other communication profiles this
value should not exceed negotiated maximum APDU send value. User can get the negotiated values of
current association by invoking “getAssociationParameters()”.
• Step 2: Initiate Image transfer by calling image_transfer_initiate method
• Step 3: Check if image_transfer_enabled attribute is true.
• Step 4: Confirm initiation by reading image_transfer_status attribute
• Step 5: Transfer Image blocks by calling image_block_transfer method
• Step 6: Check the completeness of each image by reading image_transferred_blocks_status
attribute or image_first_not_transferred_block_ number. Retransmit the failed blocks if
required.
• Step 7: Verify each image using image_verify method

Confidential 106
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

12 Debugging options
Debugging options are provided for troubleshooting and analyzing the DLMS frames sent and received
by the client. To enable the debugging, change the definition macro DIAGNOSTICS_SUPPORT as
KDEFS_TRUE in the file config.h. The function

void receiveDiagMsg(void *clientHandle,


unsigned char layerId,
unsigned char diagType,
const unsigned char *pMsg,
unsigned int msgLen)
is used. Customer 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, i.e. 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 can be
passed to SCL via registerDiagCallback() function with definition as follows

void registerDiagCallback(KDIAG_CALLBACK diagCbk)

The argument diagCbk is the pointer to the callback diagnostic function defined by the user.

Confidential 107
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

13 Appendix A – Client SCL API return codes


1.70 Generic return codes
0x0000 => Success
0x1101 => Generic/ uncategorized failure
0x1102 => Response timeout
0xFFFF => Client user input error

1.71 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
0x110c => Received COSEM APDU failed due to encode error
0x11C8 => COSEM APDU failed while encoding/decoding length. This also could be Unsupported
feature (This could refer to a key, attribute/method index in the request, communication profile, version
or value data in the packet.)
0x11fb => Waiting COSEM Event
0x11fe => Waiting COSEM Application layer block PDU
0x11f9 => Waiting for COSEM General Block Transfer
0x11fa => Waiting for COSEM Push Data

0x1164 => Library error


0x1165 =>Incorrect HLS Key Length
0x1166 => Error in authentication
0x1167 =>Error in Interface Class
0x1168 => Low LevelDisconnect
0x1169 => Event Thread exited

1.72 Library generated COSEM specific return codes


0x120d => Received xDLMS response failed due to wrong invoke id
0x120e => Received xDLMS response due to unknown result field
0x120f => COSEM Short name response error
0x1210 => COSEM received wrong block number
0x1211 => User provided HDLC address wrong
0x1212 => COSEM HLS error due to wrong key length
0x1213 => COSEM HLS authentication error
0x1214 => COSEM interface class unsupported in Client
0x12fc => indicates that the packet received was HDLC Unnumbered I frame
0x12fd => Waiting HDLC Window(Frame)
0x12ff => Waiting for an unnumbered frame

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:

Confidential 108
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

state-error:
service-not-allowed (1),
service-unknown (2)
service-error:
operation-not-possible (1),
service-not-supported (2),
other-reason (3)
1.73 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 109
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Confidential 110
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

14 Appendix B – DLMS Conformance block

Confidential 111
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

15 Appendix C: Interoperability Details of DLMS Client SCL


16
Data Link Layer

Maximum Window Size supported : 7

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

Support for IEC 62056-21 Mode E :  Yes

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


Application Layer

Authentication Mechanisms :  Lowest Level


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

Referencing scheme :  Long Name  Short Name

Conformance Block :  General ciphering


 General block transfer
 Read
 Write
 Unconfirmed Write
 Attribute 0 with SET
 Priority Management Support
 Attribute 0 with GET
 Block Transfer with GET
 Block Transfer with SET
 Block Transfer with READ
 Block Transfer with WRITE
 Block Transfer with Action
 Multiple References
 Information Report
 Parametrized Access
 GET
 SET
 Selective Access
 Event Notification
 Action
 Data Notification

Application contexts :  LN with no Ciphering


 SN with no Ciphering
LN with Ciphering
 SN with Ciphering

Security Suites  Suite 0


 Suite 1
 Suite 2

Confidential 112
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

17
18 DLMS Objects Supported by the Source Code Library
19
Interface Class DLMS Object Source code Support
1 Data  Version 0
3 Register  Version 0
4 Extended register  Version 0
5 Demand register  Version 0
6 Register activation  Version 0
7 Profile generic  Version 0  Version 1
8 Clock  Version 0
9 Script table  Version 0
10 Schedule  Version 0
11 Special days table  Version 0
12 Association SN  Version 0  Version 1  Version 2
15 Association LN  Version 0  Version 1  Version 2  Version 3
17 SAP assignment  Version 0
18 Image transfer  Version 0
19 IEC local port setup  Version 0  Version 1
20 Activity calendar  Version 0
21 Register monitor  Version 0
22 Single action schedule  Version 0
23 IEC HDLC setup  Version 0  Version 1
24 IEC twisted pair (1) setup  Version 0
25 M-Bus slave port setup  Version 0
26 Utility tables  Version 0
27 Modem configuration  Version 0  Version 1
28 Auto answer  Version 0
29 Auto connect  Version 0  Version 1
40 Push Setup  Version 0  Version 1  Version 2
41 TCP-UDP setup  Version 0
42 IPv4 setup  Version 0
43 Ethernet setup  Version 0
44 PPP setup  Version 0
45 GPRS modem setup  Version 0
46 SMTP setup  Version 0
47 GSM Diagnostic  Version 0

Confidential 113
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Interface Class DLMS Object Source code Support


48 IpV6 Setup  Version 0
50 S-FSK Phy&MAC  Version 0
51 S-FSK Active initiator  Version 0
52 S-FSK MAC synchronization  Version 0
timeouts
53 S-FSK MAC counters  Version 0
55 S-FSK IEC 61334-4-32 LLC setup  Version 0
56 S-FSK Reporting system list  Version 0
57 ISO/IEC 8802-2 LLC Type 1 setup  Version 0
58 ISO/IEC 8802-2 LLC Type 2 setup  Version 0
59 ISO/IEC 8802-2 LLC Type 3 setup  Version 0
61 Register table  Version 0
62 Compact Data  Version 0
63 Status mapping  Version 0
64 Security setup  Version 0  Version 1
65 Parameter monitor  Version 0
67 Sensor manager  Version 0
70 Disconnect control  Version 0
71 Limiter  Version 0
72 M-Bus client  Version 0
73 Wireless Mode Q channel  Version 0  Version 1
74 M-Bus master port setup  Version 0
80 LLC SSCS setup  Version 0
81 PRIME NB OFDM PLC Physical  Version 0
layer counters
82 PRIME NB OFDM PLC MAC setup  Version 0
83 PRIME NB OFDM PLC MAC  Version 0
functional parameters
84 PRIME NB OFDM PLC MAC  Version 0
counters
85 PRIME NB OFDM PLC MAC  Version 0
network administration data
86 PRIME NB OFDM PLC  Version 0
Applications identification
90 G3-PLC MAC layer counters  Version 0  Version 1
91 G3-PLC MAC setup  Version 0  Version 1
92 G3-PLC 6LoWPAN adaptation  Version 0  Version 1
layer setup
95 Wi-SUN setup  Version 0
96 Wi-SUN diagnostic  Version 0
97 RPL diagnostic  Version 0

Confidential 114
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Interface Class DLMS Object Source code Support


98 MPL diagnostic  Version 0
111 Account  Version 0
112 Credit  Version 0
113 Charge  Version 0
115 Token Gateway  Version 0
116 IEC 62055-41 Attributes  Version 0
122 Function control objects  Version 0
124 Communication port protection  Version 0
objects
126 SCHC-LPWAN setup  Version 0
127 SCHC-LPWAN diagnostic  Version 0
128 LoRaWAN setup  Version 0
129 LoRaWAN diagnostic  Version 0
151 LTE monitoring  Version 0  Version 1
9000 Extended Data  Version 0
9001 / 105 Zigbee Tunnel Setup  Version 0
9100 CoTS  Version 0
9200 ZigBee DR & LC Cluster  Version 0
9500 Block Tariff Configuration  Version 0
9901 / 101 ZigBee SAS Start-up  Version 0
9902 / 102 ZigBee SAS Join  Version 0
9903 / 103 ZigBee SE TC Control  Version 0
9904 / 104 ZigBee SAS Fragmentation  Version 0
8192 Rate Plan  Version 0

Confidential 115
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1

Confidential 116

You might also like