Top Banner
FFFISCom/Euroradio/C V2.0.0 User Guide
26
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: FFFIScom Euroradio C UserGuide 2 0 0

FFFISCom/Euroradio/C V2.0.0 UserGuide

Page 2: FFFIScom Euroradio C UserGuide 2 0 0

FFFISCom/Euroradio/C V2.0.0 User Guide

Page 3: FFFIScom Euroradio C UserGuide 2 0 0
Page 4: FFFIScom Euroradio C UserGuide 2 0 0

Table of Contents1. Introduction ....................................................................................... 1

1.1. What this document is... ............................................................. 11.2. What this document is not... ........................................................ 1

2. Installation ........................................................................................ 22.1. Installation procedure ................................................................ 2

3. The basic concepts .............................................................................. 33.1. A pure library ........................................................................... 33.2. Library Architecture .................................................................. 33.2.1. Decomposing the functionality of the application layer .................. 43.3. Configuration structures ............................................................. 43.4. Networks ................................................................................. 53.5. Safety connections .................................................................... 53.6. Handling the physical layer ......................................................... 63.7. Application layer messages encoding/decoding ............................... 63.8. Timing .................................................................................... 63.9. Threading ................................................................................ 73.10. Error-detecting codes ............................................................... 73.10.1. Object Protection Implementation ............................................ 73.10.2. Object Protection Levels ........................................................ 83.10.3. Object Protection recomendation ............................................. 8

4. The source files .................................................................................. 94.1. The header files to include .......................................................... 94.2. The functions to provide ............................................................. 94.2.1. Trace Function ....................................................................... 94.2.2. Assertion Failed function ......................................................... 94.3. Compiling the library ............................................................... 114.3.1. Protection Level ................................................................... 124.3.2. Traces ................................................................................ 124.3.3. DES Provider ...................................................................... 13

5. Typical usage ................................................................................... 145.1. SFM Application .................................................................... 145.1.1. SFM Initialization ................................................................ 145.1.2. SFM Main Loop ................................................................... 145.2. CFM Application .................................................................... 185.2.1. CFM Initialization ................................................................ 185.2.2. CFM Main Loop .................................................................. 185.3. Error handling ........................................................................ 195.4. Using the application layer codecs .............................................. 195.4.1. Reading application messages ................................................. 205.4.2. Writing application messages .................................................. 205.5. Sizing the library .................................................................... 20

6. How to... ......................................................................................... 216.1. Use my own DES function instead of the one provided with the library.................................................................................................. 21

iv

Page 5: FFFIScom Euroradio C UserGuide 2 0 0

List of Tables3.1. ...................................................................................................... 8

v

Page 6: FFFIScom Euroradio C UserGuide 2 0 0

1For more information about the tool user for source code documentation, visit http://www.stack.nl/~dimitri/doxygen/

Chapter 1. Introduction1.1. What this document is...

This document describes the FFFFIScom/Euroradio library V2.0, its underlying concepts and im-portant properties. It does:

• Explain the properties that are relevant for a developer who considers using the library: its rela-tionship to threading, timing considerations, interfaces to hardware, etc.

• Explain the mapping between the subsets 037 and 026 concepts and their representation in thelibrary

• Provide a complete explanation of the protocol one must follow to use the library, the meaningof the important parameters, and the sequence in which the various functions must be called.

1.2. What this document is not...On the other hand, this document is also restricted in a number of ways:

• It is not a tutorial about the subsets 037 and 026. At least a basic knowledge of these standardsand their practical implications is assumed.

• It is not a tutorial about C either: the language, its constructs, their semantics and idiomatic uses(such as header files, conditional compilation, etc.) are considered as prerequisite knowledge touse this document proficiently.

• It is a user guide as opposed to a source navigation document: its aim is to explain how one canuse the library proficiently, not to provide a detailed description of the internals.

• It is not an exhaustive descriptive document on the API and its underlying data types, which arebetter and more accurately explained in the HTML API documentation derived from the imple-mentation, accessible by pointing a webbrowser at$INSTALLDIR/doc/html/index.html. Would this documentation contradict the currentdocument in any way, the former is to consider more relevant, as it is generated automaticallyfrom annotations to the source code1, and hence, is to be considered a better description of itsactual behaviour.

1

Page 7: FFFIScom Euroradio C UserGuide 2 0 0

Chapter 2. Installation2.1. Installation procedure

The library comes in the form of a single .tgz file, which must be expanded in an ad hoc directory. Itcontains two subdirectories:

• src contains the source code

• doc contains the documentation, that is, this document and an api_html subdirectory whichcontains the documentation from the source code

The src directory contains three subdirectories of its own:

• src/sfm contains the library source code for the SFM module

• src/cfm contains the library source code for the CFM module

• src/scl contains the library source code for the tests integrating SFM and CFM modules

Each of these directories contain, in turn, three subdirectories:

• lib/ which contains the C source files (*.c) and header files (*.h)

• test/ which contains the source code of the test infrastructure (*.c and *.h)

• example/ which contains an example application

2

Page 8: FFFIScom Euroradio C UserGuide 2 0 0

1Throughout this document, DCE is used as a generic synonym for Modem or ISDN card, or any device used to perform phone communica-tions used as physical transport for Euroradio communications.

Chapter 3. The basic concepts3.1. A pure library

This library implements UNISIG Subset-037 and chapters 7 and 8 of UNISIG subset-026 (hereafterreferred to as the standard) so that a developer can write applications that communicate with otherSubset-037 compliant equipements without having to care for all the low-level technicalities de-scribed in the standards. The entire issue of communication is addressed by a number of high-levelfunctions only.

The library provides ultimate flexibility, by being self-contained. It does not call any standard lib-rary function, and furthermore, it does not perform explicit calls to a timing function, nor to hard-ware access functions to actually send and receive data on the transmission medium.

The library also isolates safety-related functionality from non-safety-related functionality by provid-ing two completely independent modules: the SFM (Safe Functional Module) and CFM(Communication Functional Module). These modules support completely asynchronous communic-ation, to support both single-process and distributed architectures.

Basically, it is the user's code's responsibility to:

• Provide the library with application-level outgoing data that must be sent on the safety connec-tions

• Notify the library often enough to allow time-related functions (timeouts, etc.) to perform appro-priately. Please note that this implies that the current time must be provided by the user as para-meter to a number of the functions of the public API.

• Reliably transfer messages between the CFM and the SFM modules.

• Read the data coming from the DCE1 (Data Communication Equipment, for example a GSM-RModem), by means of interrupt function, polling or any other mechanism supported by his hard-ware and supporting computing platform, and provide the raw data to the library. For more de-tails about DCE, see http://en.wikipedia.org/wiki/Data_circuit-terminating_equipment.

• Query the library for any incoming message that has been identified as user-data

• Receive DCE connection and disconnection orders from the library and inform the library ofconnection/disconnection status of the DCE.

• Send the outgoing data on the DCE when, as a result of one of the actions listed above, there isoutgoing data to be sent.

3.2. Library ArchitectureThe FFFIScom/Euroradio library is divided in two independent units

• The Euroradio layer, defined in UNISIG Subset-037. This layer is splitted in two independentmodules:

• The SFM (Safe Functional Module). This module isolates the Safety functionalities specifiedin the Subset-037

3

Page 9: FFFIScom Euroradio C UserGuide 2 0 0

• The CFM (Communication Functional Module), that implements the following protocol lay-ers:

• X.224 (Transport layer)

• T.70 (Network Layer)

• HDLC (Data Link Layer)

• Coordination function

• The Application layer defined in UNISIG Subset-026 chapters 7 and 8

The Euroradio layer deals with the safe transmission of sequences of bytes; the latter with the rep-resentation of meaningful data out of such sequences of bytes.

The FFFIScom library supports these two independent units without any coupling: application pro-grammers can use it to send proprietary trafic on a Euroradio connection without being restricted toERTMS application messages as user data.

More specifically, this means that it is perfectly possible to use Euroradio to send information of atotally different nature from what the ERTMS application layer recognizes, and conversely, the ap-plication layer could be used to decode traffic that has been sent through entirely different means.

Since these two parts of the library are entirely decoupled, the related deliverables will be decoupledaccordingly: test, documentation, etc.

These layers are easy to track down in the code: every item related to the Euroradio protocol sub-layers has a "ER37", "__ER__" or "Er37" prefix attached to it, followed by the sub-layer name. andquite predictably, every item attached to the application layer has a "ER_APP", "ER__APP__" or"ER_App" prefix attached to it.

3.2.1. Decomposing the functionality of the applicationlayer

The application layer - referred to as the codecs - is responsible for coding, namely, taking applica-tion-level data structure and turning them into sequences of bytes according to the standard, and de-coding, namely, taking a sequence of bytes, and turning it into an application-level data structure.

It is intuitively clear that decoding involves a form of validation: of all the possible sequences ofbytes, of all lengths and contents, only a tiny fraction is valid for decoding.

What is less clear, is the fact that the application layer of this library will distinguish between twoforms of validity checks to be performed:

• It will first ensure that messages are structurally correct, in the sense that it can interpret the en-tire sequence of bytes and explode it into messages, etc.

• It will then ensure that atomic - non-composite - values are valid, that is, they lie between thecorresponding validity bounds defined in the standard.

The two levels of validations are separate, implemented as separate functions, so that the decodingprocess does not stop when an invalid value has been found, thereby allowing for more fine-grainedcontrol on the process.

3.3. Configuration structures

The basic concepts

4

Page 10: FFFIScom Euroradio C UserGuide 2 0 0

The library defines the following configuration structures:

• ER37_SFM_Network_Parameters, containing HDLC-related configuration variables.

• ER_Safety_Connection_Config_Struct, containing Safety-related configuration vari-ables.

When provided to a function, arguments of the configuration structures are copied into the networkand/or connection if required. In other words, after having been passed as parameter, the configura-tion structures can be changed, discarded if stored as a local variable, etc. without altering the sub-sequent behaviour of the networks and connections that have been initialized before.

The meaning and recommended value of each configuration variable can be found in the HTMLAPI documentation, in the sections covering the two structures.

3.4. NetworksThe Euroradio protocol stack is made of 4 independent sub-layers piled up in the following order:

• Safety

• X.224 (Transport layer)

• T.70 (Network layer)

• HDLC (Data Link layer)

The FFFIScom/Euroradio library splits this protocol stack in two parts:

• The SFM module, containing all Safety-related functionality and acting as a controller for theCFM module.

• The CFM module, containing the three bottom layers in charge of transport, network, data linklayers and the coordination function.

The non-safety components of the protocol stack are represented by the Network abstraction.

A Network represents a communication channel between two Euroradio-connected systems. For ex-ample, an EVC connected to a single RBC needs one Network. This network can support one phys-ical connection channel (For example, a GSM-R connection), but several Safety connections(SeeSection 3.5, “Safety connections”)

As each Network instance is related to a single physical communication channel, a train having twoGSM-R modems, and wanting to establish Euroradio safety connections to two different RBCs musthave two distinct Network instances. Safety connections created on different Network instances willbe totally independent.

As the SFM modules acts as a controller for the CFM module, its public API exposes functionalitiesto initialize, connect, disconnect and dispose Networks. Typical usage is explained in details inChapter 5, Typical usage

3.5. Safety connectionsThe safety connection abstraction represents a Euroradio safety connection.

It contains the ncessary information to establish a safety connection and to exchange user data:

The basic concepts

5

Page 11: FFFIScom Euroradio C UserGuide 2 0 0

• Low Priority User Data with safety MAC procedure

• High Priority User Data without safety procedure

The relationship between Networks and Safety connections is a one-to-many relationship: one net-work can contain several Safety Connections. Typical usage is explained in details in Chapter 5,Typical usage

3.6. Handling the physical layerAPI functions are provided to handle all events related to the physical layer. These encompass thefollowing;

• Receiving DCE connection or disconnection order from the library(ER37_Modem_Event_Connect_Req, ER37_Modem_Event_Connect_Ind,ER37_Modem_Event_Disconnect_Req)

• Receiving data to be sent on the DCE from the library(ER37_Modem_Event_Data_To_Modem)

• Inform the library about connection/disconnection status of the DCE(ER37_Modem_Event_Disconnect_Ind, ER37_Modem_Event_Connect_Con)

• Inform the library about data coming from the DCE

(ER37_Modem_Event_Data_From_Modem)

Using the following functions, the user can, for each network separately, receive or provide theabove mentioned events to the library:

• ER37_CFM_Network_Get_Event(...)

• ER37_CFM_Network_Put_Event(...)

The sequence in which these functions must be invoked with specific events is detailed in Chapter 5,Typical usage.

When informing the library of incoming data using ER37_CFM_Network_Put_Event(...),the user is free to pass any number of bytes up to the size of the bottom layer FIFO size. See Sec-tion 5.5, “Sizing the library” for more information about library sizing issues.

3.7. Application layer messages encoding/de-coding

The library provides functions to perform all tasks related to Subset-026 messages , packets andvariables reading, writing and validation. For each application message and packet, the library de-clares a structure. Typical application message encoding/decoding is explained the section Sec-tion 5.4, “Using the application layer codecs”.

3.8. TimingThe library has no internal clock, nor does it access an external clock behind the scenes. The onlysource for timing information it will ever use is the Now parameter declared in most public functionsexcept for the application layer which only provides time-insensitive coding and decoding services.

The basic concepts

6

Page 12: FFFIScom Euroradio C UserGuide 2 0 0

The Now parameter is a 32-bit unsiged integer, representing the amount of miliseconds elapsed sincethe start of the system using the library.

It is the user's responsibility to ensure that the time value given to the library is monotonously in-creasing and accurate. Monotously increasing means that the time values must increase or stay thesame, they cannot decrease (With the exception of the 32-bit overflow).

It is also the user's responsibility to ensure the library is called often enough to guarantee that alltime-related behaviour is correct (timeouts, etc.)

3.9. ThreadingThe library is stateless in the sense that all the information it maintains across function calls arestored in the ER37_SFM_Object and ER37_CFM_Object structures.

However, as these objects hold data related to library state handling and inter-module communica-tion, multi-thread usage is discouraged, as it could provoke serious concurrency problems.

3.10. Error-detecting codesThe FFFFIScom/Euroradio library is extremely robust, and makes very conservative use of the facil-ities provided by the C language in order to reduce the risk of software failure as much as possible.However, this does not prevent the library from being potentially vulnerable to third party codelinked into the same application, and hence, the same address space.

In order to address this issue, the libray provides error detecting code that protects the library objectsagainst:

• Using objects that where not properly initialized.

• Using objects that are not library objects.

• Using objects that have been modified outside any library function

The protected objects are:

• ER37_CFM_Object

• ER37_IMC_Object

• SFM_Connection

• ER37_SFM_Network

• ER37_SFM_Object

3.10.1. Object Protection ImplementationA 32 bits integer (Beginning_Signature) is declared as the first field of the protected object.

A 32 bits integer (Ending_Signature) is declared further in the protected object.

The ending signature holds the CRC32 of all the object bytes between the beginning signature(inclusive) and the ending signature (exclusive).

When an object is created (for an example see the ER37_SFM_Initialize_Library function)the actual object initialisation is performed and then the CRC32 is computed and stored in the end-

The basic concepts

7

Page 13: FFFIScom Euroradio C UserGuide 2 0 0

ing signature. Later when any public function is called with the object as parameter, a newly CRC32is computed and compared to the stored one in the ending signature.

If the computed CRC32 does not match the stored one in the ending signature, the functions returnsan specific error code. User application should stop all processing since the object has been corrup-ted an safe processing is not guaranteed anymore.

If the computed and stored CRCs are equal, the following steps are performed:

1. The protection is removed y invalidating the ending signature (ending signature is bitwise neg-ated).

2. The specific code of the called function is performd.

3. A new protection couple is created: The beginning signature is incremented and a CRC32 iscomputed and stored in the ending signature.

3.10.2. Object Protection LevelsProtection is always enabled and cannot be disabled.

However the user has the possibility to choose from 3 different protections levels wich have differ-ent qualities and different impact on performances.

Table 3.1.

Protection Level Detects unitializedobjects

Detects invalid ob-jects

Detects memorycorruption

Computationaloverhead

Minimal yes yes no neglectable

Standard yes yes partial low

Extended yes yes full high

The first level ensures that objects passed to the library have been properly initialized. The computa-tional overhead is limited to compute a CRC32 on one 32 bits integer. However, this level does notdetect that the passed object has been corrupted.

The second level offers the same protection than the first one while adding the ability to detect thatsome of the internal variables inside the object have been changed outside of a library functioncall.The computational overhead is higher as the CRC32 is computed over more bytes.

The last level is of course fairly computationally intensive, since the library objects may containFIFO's wich may be fairly big. A safety connection compiled with a maximum of 2 messages willraise to more than 2000 bytes. Computing a CRC32 requires that the entire data structure is scannedtwice on every function call that deals with the object: once for protection verification, once for(re)protecting the object. The advantage is that any memory corruption is detected.

3.10.3. Object Protection recomendationWe recommend to use the Standard object protection level.

The basic concepts

8

Page 14: FFFIScom Euroradio C UserGuide 2 0 0

Chapter 4. The source files4.1. The header files to include

In an application which must interact with the library, depending on the module used (CFM orSFM), the following files must be included:

Files to include in the SFM application:

• er37_sfm_api.h contains the prototypes for the functions required to manage the library,network and safety connection objects.

• er_app.h contains the application-level codecs prototypes. If you wish to use the library forthe two lower layers only, using your own application messages rather than the standard subset-026 messages, you do not need to include this file.

Including any of these header files will result in including other header files. The two first are basic-ally all you need for a SFM application.

Files to include in the CFM application:

• er37_cfm_api.h: contains the prototypes for the functions required to manage the libraryand interact with the IMC and the modems.

4.2. The functions to provideThree functions must be implemented by the user and linked to his application.

1. The Trace function

2. The failed assertion function

3. The encryption key lookup function (SFM ONLY)

4.2.1. Trace FunctionIf the library traces are enabled (using the ER_ENABLE_TRACES define), the library provides ex-tended information of its internal states, incoming and outgoing messages.

This information is processed inside the er_trace module. This module calls an external function thatcan perform the actual output. Next code example shows an example ofER37_USER_Trace_Function function implementation.

void ER37_USER_Trace_Function (const erTIME Now , const erCHAR * Channel, const erCHAR * Format){

print (" %15s %8lu %s\n", Channel, Now, Format);}

4.2.2. Assertion Failed functionAssertions are computational conditions that must be true in any circumstances. Whatever the user

9

Page 15: FFFIScom Euroradio C UserGuide 2 0 0

ot network input may be, the library ensures that some vital internal variables have a safe value.

In order to ensure these internal states are valid, the code is populated with ER_Assert macros thatwill ensure that the given expression is true.

ER_Assert (pDst >= pConn->Assembler);ER_Assert (pDst < pConn->Assembler +

SIZEOF(pConn->Assembler) );

If the given expression is not true, a severe and irrecoverable error has occured. In that case, the lib-rary calls a user defined function, ER_Assertion_Failed, that is supposed to catch the errorand stop the user aplpication in a fail safe way.

The user defined function ER_Assertion_Failed may not return.

4.2.2.1. Simple implementation

The simplest ER_Asssertion_Failed implementation:

void ER_Assertion_Failed (const erCHAR * const File_Name,const erINT32 Line_Nr,const erCHAR * const Expression)

{printf ("ASSERTION FAILED %s (%d): %s\n",

File_Name,Line_Nr,Expression));

exit (1);}

This implementation shall terminate the application and return to the host operating system, if any.

4.2.2.2. Example using setjmp/longjmp

One way to implement the ER_Assertion_Failed is the usage of the setjmp/longjmp function pairs.

The main application saves the environment (setjmp) before any library call is performed.

The ER_Assertion_Failed restores this environment (longjmp) in order to return to the calling ap-plication.

void ER_Assertion_Failed (const erCHAR * const File_Name,const erINT32 Line_Nr,const erCHAR * const Expression)

{/* we also should store this event in NVRAM */

printf ("ASSERTION FAILED %s (%d): %s\n",File_Name,Line_Nr,Expression));

/* return to the beginning of the application */longjmp (assert_jmp_buffer, 1);

}

#include <setjmp.h>

/* define a global setjmp/longjmp buffer */

The source files

10

Page 16: FFFIScom Euroradio C UserGuide 2 0 0

jmp_buff _assert_jmp_buffer;

void main (void){int res;

res = setjmp (assert_jmp_buffer);if (res == 0){

ER37_SFM_Initialize_Library(...);

/* here comes the application */}else{

/* We are returning from an ER_Assert that failed *//* Log the Error *//* Then, safely shutdown */

}}

4.3. Compiling the libraryThe library is written in pure C, using the widely available C89 standard.

The library is developped with the most restrictive compiler settings available at development time,specifically focused on avoiding any compiler warnings. Additional tools like Splint and Lint per-formed advanced verifications on the code.

The ER37 Library accepts some compilations options that allow the user to fit his particular needs.

Compilations options may be divided in two groups:

1. Optional features options : Assertions, Protection Level, DES provider.

2. Dimentional options: Number of networks, Number of Safety connections, number of SafetyLP messages, number of HP messages and number of IMC messages.

Options in the first group must be manually selected by the user. There is no default value.

Options in the second group have default values that the user may override. Default values are indic-ated in the API documentation for file er37_sizes.h.

Options in both groups may be specified in two different ways:

• As compiler directives (usually -D... flag on compiler's options)

• As C standard defines inside a user provided er37_user.h

In order to enable a user defined er37_user.h include file, a single compiler must be defined:

-DER_ENABLE_USER_INCLUDE

Compiling without er37_user.h.

gcc -DER_ENABLE_TRACES-DER_ENABLE_STANDARD_OBJECT_PROTECTION-DER_USE_LIBRARY_DES

The source files

11

Page 17: FFFIScom Euroradio C UserGuide 2 0 0

-DER37_MAX_KEYS_IN_DICTIONNARY=30UL-DER37_MAX_SAFETY_CONNECTIONS=10UL-DER37_MAX_SAFETY_MESSAGES=2UL-DER37_MAX_SAFETY_MESSAGES_HP=2UL-I.*.c

Compiling with er37_user.h

The user must create a er37_user.h file like this

#ifndef ER_USER_INCLUDE_H_#define ER_USER_INCLUDE_H_

#define ER_ENABLE_MINIMAL_OBJECT_PROTECTION#define ER_ENABLE_TRACES#define ER_USE_LIBRARY_DES#define ER37_MAX_SAFETY_NETWORKS 2UL#define ER37_MAX_SAFETY_CONNECTIONS 10UL#define ER37_MAX_SAFETY_MESSAGES 2UL#define ER37_MAX_SAFETY_MESSAGES_HP 2UL#define ER37_IMC_MAX_FIFO_SIZE 5UL

#endif

And compile the sources:

gcc -DER_ENABLE_USER_INCLUDE-I.*.c

4.3.1. Protection LevelOne, and exactly one of the following must be defined:

1. ER_MINIMAL_OBJECT_PROTECTION

2. ER_STANDARD_OBJECT_PROTECTION

3. ER_EXTENDED_OBJECT_PROTECTION

4.3.2. TracesOne, and exactly one, of the following must be defined:

1. ER_ENABLE_TRACES

2. ER_DISABLE_TRACES

If the first option is choosen, it is the responsability pro provide an external implementation for thefunction:

void ER37_USER_Trace_Function (erTIME Now,const erCHAR * const Channel,

The source files

12

Page 18: FFFIScom Euroradio C UserGuide 2 0 0

const erCHAR * const Format);

4.3.3. DES ProviderOne, and exactly one of the following must be defined:

1. ER_USE_LIBRARY_DES

2. ER_USE_USER_DES

If the second option is choosen, it is the responsability of the user to provide a valid implemebtationof these two functions:

void ER_DES_Crypt(const ER_DES_Coder_Struct * const pCoder,erBYTE * const in,erBYTE * const out);

void ER_DES_Key_Schedule(ER_DES_Coder_Struct * const pCoder,const erBYTE key[8],ER_DES_Operation_Enum mode);

The source files

13

Page 19: FFFIScom Euroradio C UserGuide 2 0 0

Chapter 5. Typical usageThis chapter lists the steps that your application program should follow in order to interact grace-fully with the library. The example application er37_example_main.c available in the HTMLdocumentation (and as source code) provide a complete and operation example of simple EVC andRBC applications using the library.

In the provided example, the communication between the CFM and SFM modules and between thetwo peer CFMs (the EVC CFM and the RBC CFM) are implemented on top of TCP/IP, in order toprovide a working performing real ansynchronous communication.

The following sections detail step-by-step the various API calls that the EVC and RBC applicationsmust perform, as well in the SFM as in the CFM module/host.

5.1. SFM ApplicationThis section details every API call needed in the application hosting the SFM module of the library.

The SFM application must perform the following sequence of tasks:

5.1.1. SFM InitializationThe first API call that the user must invoke is ER37_SFM_Initialize_Library. This must bedone prior to any other CFM function call.

Once initialization has been ordered, the SFM will send an IMC message to its peer CFM, and waitfor an IMC message from its peer CFM.

In order for the IMC messages to be exchanged, the user application must invoke ciclycally the fol-lowing functions:

• ER37_SFM_Get_IMC_Message

• ER37_SFM_Put_IMC_Message

• ER37_SFM_Process

• ER37_SFM_Get_Library_Status

Once these two messages have been exchanged, the SFM is ready to enter its main application loop.This is signalled by the user when the library status is ER37_LIB_State_OPERATIONAL.

In case of configuration or version differences between the CFM and SFM, the library status willbecome ER37_LIB_State_ERROR. In that situation, user code should go to safe state.

The example application module er37_example_sfm.c illustrates the CFM initialization pro-cedure in the function example_initialize_sfm_library.

5.1.2. SFM Main LoopOnce the SFM is succesfully initialized, it can enter its main application loop. Inside the applicationmain loop, different type of operations need to be performed:

1. Library status monitoring

2. IMC communication

14

Page 20: FFFIScom Euroradio C UserGuide 2 0 0

3. Network and Safety connections management

4. Sending and receiving Application messages

5. Receiving Safety indication reports

5.1.2.1. Library status monitoring

Inside the main SFM loop, the user code must call the functionER37_SFM_Get_Library_Status at regular intervals. If the status changes fromER37_LIB_State_OPERATIONAL, the user code must put the SFM application in a safe state.

The following reasons might cause a status transition from ER37_LIB_State_OPERATIONAL:

• An internal error in the SFM

• A memory corruption that has been detected

• An incompatible CFM (Different number of networks, different number of connections per net-work or different library version)

• An error in the CFM propagated in the SFM through the ICM

See for a practical example the function example_get_library_status iner37_example_fsm.c.

5.1.2.2. IMC communication

The user code has the responsibility for ensuring reliable ICM communication between the SFMand the CFM module.

This means that inside the main SFM application loop, the user code should provide the messagescoming from the CFM to the SFM using ER37_SFM_Put_IMC_Message, and provide the mes-sages targeted to the CFM using ER37_SFM_Get_IMC_Message.

See for a practical example the functions example_imc_to_tcpip and ex-ample_tcpip_to_imc in er37_example_fsm.c.

5.1.2.3. Network and Safety connections management

Network and Safety connections lifecyle involves several tasks: connection establishment, connec-tion status monitoring, connection release and connection re-use.

5.1.2.3.1. Connection establishment

In order to establish Safety connections to a Euroradio peer application, the user code must first ini-tialize and connect a Network.

As network initialization and connection impacts the CFM, these operations are asynchronous. Theyinvolve the following sequence of operations:

1. Network initialization using ER37_SFM_Initialize_Network.

2. Network initialization monitoring using ER37_SFM_Get_Network_Status

3. If the SFM is the connection initiator (I.e. the party which calls the other party), Network con-nection using ER37_SFM_Connect_Network. Network connection can only be performed aftersuccessful network initialization. Network connection is an optional step that can be performedautomatically by the the SFM when the user code initiates Safety connection establishment us-

Typical usage

15

Page 21: FFFIScom Euroradio C UserGuide 2 0 0

ing ER37_SFM_Connect_Connection.

4. If the SFM is the connection initiator, monitoring the Network connection status usingER37_SFM_Get_Network_Status, until it is ER37_SFM_Network_Status_CONNECTED.

Once a network is succesfully initialized, one or more Safety connections can be created in associ-ation with that network, using the following operations:

1. Connection initialization using ER37_SFM_Initialize_Connection.

2. Connection initialization monitoring using ER37_SFM_Get_Connection_Status

3. If the SFM is the connection initiator (I.e. the party which calls the other party), Connection es-tablishment using ER37_SFM_Connect_Connection. Connection establishment can only beperformed after successful connection initialization.

4. If the SFM is the connection receiver, the user code must monitor the status of the connectionuntil it is ER37_SFM_Connection_Status_ACCEPT_PENDING. This status means that a peerSafety connection has started Safety connection establishment procedure.

At that moment, the user code can check the incoming connection's ETCS ID and ETCS IDType using the ER37_SFM_Get_Safety_Connection_Properties function, and accept it usingthe ER37_SFM_Accept_Safety_Connection function.

5. If the SFM is the connection initiator, monitoring the Network connection status usingER37_SFM_Get_Network_Status, until it is ER37_SFM_Network_Status_CONNECTED.

See for a practical example the function example_main_loop in er37_example_fsm.c.

5.1.2.3.1.1. Connection Creation Checks

The following functional checks are performed when the user code initializes a new Safety connec-tion:

• If all connections are already initialized, the ER37_Connection_Create_NO_SPACE error codeis returned.

• All safety connections created on a same Network must have the same ETCS ID and ETCS IDtype values. They also must have a different Application Type value. If one of these two condi-tions is not not fullfilled, the ER37_Connection_Create(...) will returnER37_SFM_Initialize_Safety_Connection_INVALID_PARAMS

5.1.2.3.2. Connection status monitoring

The status of a connection must be monitored using the functionER37_SFM_Get_Safety_Connection_Status.

A transition from the ER37_SFM_Connection_Status_CONNECTED to theER37_SFM_Connection_Status_DISCONNECTING orER37_SFM_Connection_Status_DISCONNECTED state is the indication that one of the followingevents has occured:

1. The ER37_SFM_Disconnect_Safety_Connection function has been invoked.

2. The peer Safety connection has requested disconnection

3. An error in the CFM protocol layers has provoked transport connection disconnection

Typical usage

16

Page 22: FFFIScom Euroradio C UserGuide 2 0 0

In order for the user code to know what happened, the SFM publish several variables in theER37_SFM_Connection_Status_Struct:

• Outgoing_Disconnect_Reason

• Outgoing_Disconnect_SubReason

• Incoming_Disconnect_Reason

• Incoming_Disconnect_SubReason

5.1.2.3.3. Connection And Network Release

Prerequisite: you have a safety connection which is in connected state.

Once the user code wants to disconnect the connection, he can issue aER37_SFM_Disconnect_Safety_Connection call.

This call orders the safety connection to disconnect at the next ER37_SFM_Process call. It is im-portant to check the ER37_Connection_Disconnect(...) return value isER37_Connection_Disconnect_OK.

Otherwise, the disconnection order may not have been transmitted to the connection if the internalFIFO of the safety connection is full, indicated by aER37_SFM_Disconnect_Safety_Connection_FIFO_FULL return value.In that case, the user codeshould retry after processing the SFM.

Once the user has successfully ordered the disconnection, he should invokeER37_SFM_Process(...) until both Safety connection status and Transport connection statusare disconnected.

Inside the library, it means that the safety connection in the SFM and the associated X.224 connec-tion in the CFM have been disconnected.

At that moment, the network can be safely disconnected, using theER37_SFM_Disconnect_Network function, or be left open for Safety connections that might still bein connected status on this Network.

5.1.2.3.4. Connection And Network Recycling

Networks and connections can be reused after the connection and network have been disconnected.When the user code wants to re-use them, they must first be disposed using theER37_SFM_Dispose_Network and ER37_SFM_Dispose_Connection functions, then initializedagain like explained in the above procedure.

5.1.2.4. Sending and receiving Application messages

Sending and receiving application data can only be performed on successfully established Safetyconections, using the ER37_SFM_Send_Message, ER37_SFM_Send_HP_Message,ER37_SFM_Receive_Message and ER37_SFM_Receive_HP_Message functions.

The user is free to transport any kind of data using the high and low-priority data sending and re-ceiving services. It can use the Subset-026 application codecs provided with the library (See Sec-tion 5.4, “Using the application layer codecs”for a complete explanation), or decide to send any oth-er proprietary data.

The only limitation is the size of the data that can be sent in the high and low priority services.

TODO speak about FIFO fulls.

See for a practical example the function example_main_loop in er37_example_fsm.c.

Typical usage

17

Page 23: FFFIScom Euroradio C UserGuide 2 0 0

5.1.2.5. Receiving Safety indication reports

Aside of incoming application messages, the user code can also be notified on incorrect SafetyMAC occuring in incoming Safety messages, using the ER37_SFM_Receive_Report_Indicationfunction.

See for a practical example the function example_main_loop in er37_example_fsm.c.

5.2. CFM ApplicationThis section details every API call needed in the application hosting the CFM module of the library.

The CFM application must perform the following sequence of tasks:

5.2.1. CFM InitializationThe first API call that the user must invoke is ER37_CFM_Initialize_Library. This must bedone prior to any other CFM function call.

Once initialization has been ordered, the CFM will send an IMC message to its peer SFM, and waitfor an IMC message from its peer SFM.

In order for the IMC messages to be exchanged, the user application must invoke ciclycally the fol-lowing functions:

• ER37_CFM_Get_IMC_Message

• ER37_CFM_Put_IMC_Message

• ER37_CFM_Process

• ER37_CFM_Get_Library_Status

Once these two messages have been exchanged, the CFM is ready to enter its main application loop.This is signalled by the user when the library status is ER37_LIB_State_OPERATIONAL.

In case of configuration or version differences between the CFM and SFM, the library status willbecome ER37_LIB_State_ERROR. In that situation, user code should go to safe state.

The example application module er37_example_cfm.c illustrates the CFM initialization pro-cedure in the function example_initialize_cfm_library.

5.2.2. CFM Main LoopOnce CFM initialization is completed, the CFM can enter its application main loop. The applicationmain loop is similar to the CFM initialization loop, with the additional management of events to andfrom the modems.

The user application must invoke ciclycally the following functions:

• ER37_CFM_Get_IMC_Message

• ER37_CFM_Put_IMC_Message

• ER37_CFM_Get_Modem_Event

• ER37_CFM_Put_Modem_Event

Typical usage

18

Page 24: FFFIScom Euroradio C UserGuide 2 0 0

1See http://www.splint.org/ for more details

• ER37_CFM_Process

• ER37_CFM_Get_Library_Status

The user code should keep performing the CFM Main loop until the library status isER37_LIB_State_ERROR or when its host application is terminated.

The example application module er37_example_cfm.c illustrates the CFM initialization pro-cedure in the function example_main_loop

5.2.2.1. Modem FIFO Full handling

Three types of events coming from the DCE (For example, GSM-R Modem or ISDN connection)must be provided to the relevant network using the ER37_CFM_Put_Modem_Event fucntion:

• DCE connection successfully established: ER37_Modem_Event_Connect_Con

• DCE connection indication: ER37_Modem_Event_Connect_Ind

• DCE disconnection: ER37_Modem_Event_Disconnect_Ind

• Incoming data: ER37_Modem_Event_Data_From_Modem

The function ER37_CFM_Put_Modem_Event(...) can return aER37_CFM_Put_Modem_Event_FIFO_FULL error in case the library internal data structuresfor that network are full.

In the case of a ER37_Modem_Event_Data_From_Modem, some of the bytes passed to thePut_Bytes call can already be processed by the HDLC layer, but the are discarded because theHDLC incoming FIFO is full.

The user should discard the passed bytes, Process(...) the CFM again and keep passing in-coming bytes to the network. The HDLC protocol layer will automatically re-assemble and requiremissing frames from the HDLC connection peer.

In the case of a ER37_Network_Put_Event_Fifo_Full error after passing aER37_Modem_Event_Disconnect_Ind, the user should Process(...) the CFM againand keep passing the event to the network, until successful.

5.3. Error handlingEach function of the SFM and CFM API has a unique return type, modelled as an enumeration.

Having one different enumeration for each function call ensures that the user code, if using quality-assurance tools (like splint for instance), processes all possible return codes for each function1.

One question arises when processing these return codes is: what is the meaning of each one, andwhat should the user code do in case of a non-OK return code? Put the application in a safe state?Try again until success?

No universal answer can be given to that question. The reader is advised to look in the HTML APIdocumentation, which contain suggested user action for each value of each API return code enumer-ation.

5.4. Using the application layer codecs

Typical usage

19

Page 25: FFFIScom Euroradio C UserGuide 2 0 0

The application message encoders and decoders, also known as codecs, provide high-level functionsand strcutures for every Subset-026 application message and packet.

5.4.1. Reading application messagesTo read an application message from a sequence of bytes, one should use the functionER_APP_Read(...). This function will fill in a ER_APP_Packet_Union structure that con-tains the decoded message. The Header.Type field of the decoded message structure contains thetype of the decoded message. This type can be any of the ER_APP_Packet_Enum elements.UNISIG Subset-026 messages can contain variables and/or packets. In order to read the packetscontained in the message, the user can check, for each packet to the message structure, the Typefield. If this field is different than ER_APP_Packet_None, this signals that the packet is con-tained in the message.

NOTE: in the UNISIG Subset-026 specifications, a distinction is made between messages and pack-ets, message containing variables and packets. In the library, both concepts are merged in packets.

5.4.2. Writing application messagesTo write an application message, the user must first initialize the ER_APP_Packet_Union struc-ture, by using the specialized initialization function for the desired message type. For example, if theuser wishes to write a new MA Request message, the function to use ifER_Init_APP_MA_Request(...).

After message initialization, the user can fill the various message variables, and initialize and spe-cify the included packets.

Once the message is completely specified, it can be encoded into a byte sequence using the special-ized writer function according to the message type: ER_Write_APP_MA_Request(...).

5.5. Sizing the libraryThe user can define several variables that will specify the size of SFM and CFM components,thereby impacting the memory usage.

These variables are explained in detail in the HTML API documentation, in the er37_sizes.hfile. An explanation and the default value is provided for each variable.

Typical usage

20

Page 26: FFFIScom Euroradio C UserGuide 2 0 0

Chapter 6. How to...6.1. Use my own DES function instead of theone provided with the library

This can be provided by redefining the ER_CALCULATE_DES andER_CALCULATE_DES_INVERTED macros in er_user.h to call you own function rather thanthe default behaviour. This is the only header file in the library which is meant to be altered directlyby the user to tune the library's behaviour to environment-specific constraints.

21