DLMS Client UserManual
DLMS Client UserManual
User Manual
www.kalkitech.com
Version 3.15.1
20th Dec 2022
Copyright Notice
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
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
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
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
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
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
Confidential 7
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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.
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
• 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
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.
Argument
Example; 30000
Example: 5000
Confidential 12
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Example: 1024
Example: 1000000
Confidential 13
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Returns
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
connWaitTimeout
0 - 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
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
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
Confidential 18
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
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.
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.
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.
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.
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
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
}SECURITY_PARAM;
•2 authenticated request,
•3 encrypted request,
•5 authenticated response,
•6 encrypted response,
Confidential 27
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
Argument
clientHandle Handle returned by initClient()
serverSystemTitle
String of length 8.
Confidential 29
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
}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
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.
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
}SECURITY_PARAM;
•2 authenticated request,
•3 encrypted request,
•5 authenticated response,
•6 encrypted response,
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.
Argument
clientHandle Handle returned by initClient()
GetRequestList COSEM_ATTR_METH_DESC_LIST structure
containing list of cosem attribute descriptors
Confidential 33
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 34
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 35
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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().
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.
Argument
clientHandle Handle returned by initClient()
SetDataInfo List of cosem attribute descriptors and data to set
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
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.
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()
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.
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
Confidential 40
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
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).
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
Confidential 43
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
initClient()
initPort()
setParamsHDLC()
sendSNRM()
setParamsAARQ()
sendAARQ()
getData() / setData() / executeAction()
cleanupMemory() / cleanUpMemoryForSet()
/ cleanupActionMemory()
sendDisc()
closePort()
closeClient()
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).
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
Confidential 48
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 49
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
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.
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.
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,
•2 authenticated request,
•3 encrypted 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
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
Confidential 57
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
encryption/decryption.
•2 authenticated request,
•3 encrypted request,
•5 authenticated response,
•6 encrypted response,
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
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
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.
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().
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
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
Confidential 62
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 63
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
}ENCODED_AXDR;
COSEM_ATTR_METH_DESC *cosemAttrMethDesc
=> list of COSEM_ATTR_METH_DESC each
containing one cosem attribute descriptor
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().
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)
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
VARVALUE ServiceSpecificData;
ServiceSpecificData =
(VARVALUE*)pushPtr-
>varvalue[0].value_p;
1.33 cleanDecodedCompactFrameData
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).
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
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.
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.
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.
Confidential 71
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
Confidential 73
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
1.40 cleanUpEncodedHDLC
The function used to release the memory allocated by the encodeHDLCrequest() function.
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.
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.
Argument
ENCODED_PRIMARY_APDU * Pointer returned by the cleanUpDecodedHDLC()
Return
Result SUCCESS or FAILURE.
Confidential 75
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
5 Special functions
1.44 getSystemTitleFromPushNotification
This function is used to get system title from a Data notification APDU.
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
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.
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.
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
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.
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
1.50 cleanUpMemoryforsendpacket
This function used to release the memory allocated by sendPacket() function.
Argument
encodedapdu Data return by sendPacket ()
Return
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
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
Arguments
encryptFunPtr Encryption callback function pointer
decryptFunPtr - Decryption callback function pointer
hashFunPtr - Hashing callback function pointer
Confidential 81
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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)
Confidential 82
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
HASH_CALLBACK defined as :
typedef void (*HASH_CALLBACK) ( KDEFS_UCHAR hashMethod,
KDEFS_UCHAR *plainText_p,
KDEFS_USHORT ptLen,
KDEFS_UCHAR *cipherText_p);
Parameters
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
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
Parameters
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
Parameters
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.
Parameters
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
Parameters
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.
Confidential 87
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Parameters
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 :
Parameters
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
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
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()
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
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
Confidential 92
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
{
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;
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.
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
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
• Receive data from TCP socket and write into stack wrapper input buffer
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);
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);
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().
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.
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
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.
DLMS_GLOBALS *dlmsInstance);
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
After using push data received via Push call back function, user shall call cleanPushData() to free
dynamically allocated memory
1.65 cleanEventData
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);
Confidential 101
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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)
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
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
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.
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.
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.
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)
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
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
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
Confidential 111
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
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
Confidential 114
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 115
DLMS/COSEM Client Source Code Library User Manual Version 3.15.1
Confidential 116