Main Content

Create a Transport Layer for TCP/IP or Serial External Mode Communication

This section helps you to connect your custom target by using external mode using your own low-level communications layer. The topics include:

  • An overview of the design and operation of external mode

  • A description of external mode source files

  • Guidelines for modifying the external mode source files and building an executable to handle the tasks of the default ext_comm MEX-file

This section assumes that you are familiar with the execution of Simulink® Coder™ programs, and with the basic operation of external mode.

Design of External Mode

External mode communication between the Simulink engine and a target system is based on a client/server architecture. The client (the Simulink engine) transmits messages requesting the server (target) to accept parameter changes or to upload signal data. The server responds by executing the request.

A low-level transport layer handles physical transmission of messages. Both the Simulink engine and the model code are independent of this layer. Both the transport layer and code directly interfacing to the transport layer are isolated in separate modules that format, transmit, and receive messages and data packets.

This design makes it possible for different targets to use different transport layers. The GRT, ERT, and RSim targets support host/target communication by using TCP/IP and RS-232 (serial) communication. The Simulink Desktop Real-Time™ target supports shared memory communication. The Wind River® Systems Tornado® target supports TCP/IP only.

The Simulink Coder product provides full source code for both the client and server-side external mode modules, as used by the GRT, ERT, Rapid Simulation, and Tornado targets, and the Simulink Desktop Real-Time and Simulink Real-Time™ products. The main client-side module is ext_comm.c. The main server-side module is ext_svr.c.

These two modules call the specified transport layer through the following source files.

Built-In Transport Layer Implementations

Protocol

Client or Server?

Source Files

TCP/IP

Client (host)

 

Server (target)

Serial

Client (host)

 

Server (target)

For serial communication, the modules ext_serial_transport.c and rtiostream_serial.c implement the client-side transport functions and the modules ext_svr_serial_transport.c and rtiostream_serial.c implement the corresponding server-side functions. For TCP/IP communication, the modules rtiostream_interface.c and rtiostream_tcpip.c implement both client-side and server-side functions. You can edit copies of these files (but do not modify the originals). You can support external mode using your own low-level communications layer by creating similar files using the following templates:

  • Client (host) side: matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c (TCP/IP) or matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c (serial)

  • Server (target) side: matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c (TCP/IP) or matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c (serial)

The rtiostream_interface.c file is an interface between the external mode protocol and an rtiostream communications channel. For more details on implementing and testing an rtiostream communications channel, see:

Implement your rtiostream communications channel by using the documented interface to avoid having to make changes to the file rtiostream_interface.c or other external mode related files.

Note

Do not modify working source files. Use the templates provided in the /custom or /rtiostream folder as starting points, guided by the comments within them.

You need only provide code that implements low-level communications. You need not be concerned with issues such as data conversions between host and target, or with the formatting of messages. The Simulink Coder software handles these functions.

On the client (Simulink engine) side, communications are handled by ext_comm (for TCP/IP) and ext_serial_win32_comm (for serial) MEX-files.

On the server (target) side, external mode modules are linked into the target executable. This takes place automatically at code generation time if you select External mode and is based on the Transport layer option that you specify. The modules, called from the main program and the model execution engine, are independent of the generated model code.

The general procedure for implementing your own client-side low-level transport protocol is as follows:

  1. Edit the template rtiostream_tcpip.c to replace low-level communication calls with your own communication calls.

  2. Generate a MEX-file executable for your custom transport.

  3. Register your new transport layer with the Simulink software, so that the transport can be selected for a model using the Interface pane of the Configuration Parameters dialog box.

For more details, see Create a Custom Client (Host) Transport Protocol.

The general procedure for implementing your own server-side low-level transport protocol is as follows:

  1. Edit the template rtiostream_tcpip.c to replace low-level communication calls with your own communication calls. Typically this involves writing or integrating device drivers for your target hardware.

  2. Modify template makefiles to support the new transport.

For more details, see Create a Custom Server (Target) Transport Protocol.

External Mode Communications Overview

This section gives a high-level overview of how a Simulink Coder generated program communicates with Simulink external mode. This description is based on the TCP/IP version of external mode that ships with the Simulink Coder product.

For communication to take place, both the server (target) program and the Simulink software must be executing. This does not mean that the model code in the server system must be executing. The server can be waiting for the Simulink engine to issue a command to start model execution.

The client and server communicate by using bidirectional sockets carrying packets. Packets consist either of messages (commands, parameter downloads, and responses) or data (signal uploads).

If the target application was invoked with the -w command-line option, the program enters a wait state until it receives a message from the host. Otherwise, the program begins execution of the model. While the target application is in a wait state, the Simulink engine can download parameters to the target and configure data uploading.

When the user chooses the Connect to Target option from the Simulation menu, the host initiates a handshake by sending an EXT_CONNECT message. The server responds with information about itself. This information includes

  • Checksums. The host uses model checksums to determine that the target code is an exact representation of the current Simulink model.

  • Data format information. The host uses this information when formatting data to be downloaded, or interpreting data that has been uploaded.

At this point, host and server are connected. The server is either executing the model or in the wait state. (In the latter case, the user can begin model execution by selecting Start Real-Time Code from the Simulation menu.)

During model execution, the message server runs as a background task. This task receives and processes messages such as parameter downloads.

Data uploading comprises both foreground execution and background servicing of the signal packets. As the target computes model outputs, it also copies signal values into data upload buffers. This occurs as part of the task associated with each task identifier (tid). Therefore, data collection occurs in the foreground. Transmission of the collected data, however, occurs as a background task. The background task sends the data in the collection buffers to the Simulink engine by using data packets.

The host initiates most exchanges as messages. The target usually sends a response confirming that it has received and processed the message. Examples of messages and commands are:

  • Connection message / connection response

  • Start target simulation / start response

  • Parameter download / parameter download response

  • Arm trigger for data uploading / arm trigger response

  • Terminate target simulation / target shutdown response

Model execution terminates when the model reaches its final time, when the host sends a terminate command, or when a Stop Simulation block terminates execution. On termination, the server informs the host that model execution has stopped, and shuts down its socket. The host also shuts down its socket, and exits external mode.

External Mode Source Files

Client (Host) MEX-file Interface Source Files

The source files for the MEX-file interface component are located in the folder matlabroot/toolbox/coder/simulinkcoder_core/ext_mode/host (open), except as noted:

  • common/ext_comm.c

    This file is the core of external mode communication. It acts as a relay station between the target and the Simulink engine. ext_comm.c communicates to the Simulink engine by using a shared data structure, ExternalSim. It communicates to the target by using calls to the transport layer.

    Tasks carried out by ext_comm.c include establishment of a connection with the target, downloading of parameters, and termination of the connection with the target.

  • common/rtiostream_interface.c

    This file is an interface between the external mode protocol and an rtiostream communications channel. For more details on implementing an rtiostream communications channel, see Communications rtiostream API (Embedded Coder). Implement your rtiostream communications channel using the documented interface to avoid having to change the file rtiostream_interface.c or other external mode related files.

  • matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c

    This file implements required TCP/IP transport layer functions. The version of rtiostream_tcpip.c shipped with the Simulink Coder software uses TCP/IP functions including recv(), send(), and socket().

  • matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c

    This file implements required serial transport layer functions. The version of rtiostream_serial.c shipped with the Simulink Coder software uses serial functions including ReadFile(), WriteFile(), and CreateFile().

  • serial/ext_serial_transport.c

    This file implements required serial transport layer functions. ext_serial_transport.c includes ext_serial_utils.c, which is located in matlabroot/rtw/c/src/ext_mode/serial (open) and contains functions common to client and server sides.

  • common/ext_main.c

    This file is a MEX-file wrapper for external mode. ext_main.c interfaces to the Simulink engine by using the standard mexFunction call. (See the mexFunction reference page and Choosing a MATLAB API for Your Application for more information.) ext_main.c contains a function dispatcher, esGetAction, that sends requests from the Simulink engine to ext_comm.c.

  • common/ext_convert.c and ext_convert.h

    This file contains functions used for converting data from host to target formats (and vice versa). Functions include byte-swapping (big to little- endian), conversion from non-IEEE® floats to IEEE doubles, and other conversions. These functions are called both by ext_comm.c and directly by the Simulink engine (by using function pointers).

    Note

    You do not need to customize ext_convert to implement a custom transport layer. However, you might want to customize ext_convert for the intended target. For example, if the target represents the float data type in Texas Instruments™ format, ext_convert must be modified to perform a Texas Instruments to IEEE conversion.

  • common/extsim.h

    This file defines the ExternalSim data structure and access macros. This structure is used for communication between the Simulink engine and ext_comm.c.

  • common/extutil.h

    This file contains only conditionals for compilation of the assert macro.

  • common/ext_transport.h

    This file defines functions that must be implemented by the transport layer.

Server (Target) Source Files

These files are linked into the model.exe executable. They are located within matlabroot/rtw/c/src/ext_mode (open) except as noted.

  • common/ext_svr.c

    ext_svr.c is analogous to ext_comm.c on the host, but generally is responsible for more tasks. It acts as a relay station between the host and the generated code. Like ext_comm.c, ext_svr.c carries out tasks such as establishing and terminating connection with the host. ext_svr.c also contains the background task functions that either write downloaded parameters to the target model, or extract data from the target data buffers and send it back to the host.

  • common/rtiostream_interface.c

    This file is an interface between the external mode protocol and an rtiostream communications channel. For more details on implementing an rtiostream communications channel, see Communications rtiostream API (Embedded Coder). Implement your rtiostream communications channel by using the documented interface to avoid having to change the file rtiostream_interface.c or other external mode related files.

  • matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c

    This file implements required TCP/IP transport layer functions. The version of rtiostream_tcpip.c shipped with the Simulink Coder software uses TCP/IP functions including recv(), send(), and socket().

  • matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c

    This file implements required serial transport layer functions. The version of rtiostream_serial.c shipped with the software uses serial functions including ReadFile(), WriteFile(), and CreateFile().

  • matlabroot/toolbox/coder/rtiostream/src/rtiostream.h

    This file defines the rtIOStream* functions implemented in rtiostream_tcpip.c.

  • serial/ext_svr_serial_transport.c

    This file implements required serial transport layer functions. ext_svr_serial_transport.c includes serial/ext_serial_utils.c, which contains functions common to client and server sides.

  • common/updown.c

    updown.c handles the details of interacting with the target model. During parameter downloads, updown.c does the work of installing the new parameters into the model's parameter vector. For data uploading, updown.c contains the functions that extract data from the model's blockio vector and write the data to the upload buffers. updown.c provides services both to ext_svr.c and to the model code (for example, grt_main.c). It contains code that is called by using the background tasks of ext_svr.c as well as code that is called as part of the higher priority model execution.

  • matlabroot/rtw/c/src/dt_info.h (included by generated model build file model.h)

    These files contain data type transition information that allows access to multi-data type structures across different computer architectures. This information is used in data conversions between host and target formats.

  • common/updown_util.h

    This file contains only conditionals for compilation of the assert macro.

  • common/ext_svr_transport.h

    This file defines the Ext* functions that must be implemented by the server (target) transport layer.

Other Files in the Server Folder

  • common/ext_share.h

    Contains message code definitions and other definitions required by both the host and target modules.

  • serial/ext_serial_utils.c

    Contains functions and data structures for communication, MEX link, and generated code required by both the host and target modules of the transport layer for serial protocols.

  • The serial transport implementation includes the additional files

    • serial/ext_serial_pkt.c and ext_serial_pkt.h

    • serial/ext_serial_port.h

Implement a Custom Transport Layer

Requirements for Custom Transport Layers

  • By default, ext_svr.c and updown.c use malloc to allocate buffers in target memory for messages, data collection, and other purposes, although there is also an option to preallocate static memory. If your target uses another memory allocation scheme, you must modify these modules.

  • The target is assumed to support both int32_T and uint32_T data types.

Create a Custom Client (Host) Transport Protocol

To implement the client (host) side of your low-level transport protocol,

  1. Edit the template file matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c to replace low-level communication calls with your own communication calls.

    1. Copy and rename the file to rtiostream_name.c (replacing name with a name meaningful to you).

    2. Replace the functions rtIOStreamOpen, rtIOStreamClose, rtIOStreamSend, and rtIOStreamRecv with functions (of the same name) that call your low-level communication primitives. These functions are called from other external mode modules via rtiostream_interface.c. For more information, see Communications rtiostream API (Embedded Coder).

    3. Build your rtiostream implementation into a shared library that exports the rtIOStreamOpen, rtIOStreamClose, rtIOStreamRecv and rtIOStreamSend functions.

  2. Build the customized MEX-file executable using the MATLAB® mex function. See MATLAB Commands to Rebuild ext_comm and ext_serial_win32 MEX-Files for examples of mex invocations.

    Do not replace the existing ext_comm MEX-file if you want to preserve its functionality. Instead, use the -output option to name the new executable file, for example, my_ext_comm. For more information, see mex.

  3. Register your new client transport layer with the Simulink software, so that the transport can be selected for a model using the Interface pane of the Configuration Parameters dialog box. For details, see Register a Custom Client (Host) Transport Protocol.

Sample commands for rebuilding external mode MEX-files are listed in MATLAB Commands to Rebuild ext_comm and ext_serial_win32 MEX-Files.

MATLAB Commands to Rebuild ext_comm and ext_serial_win32 MEX-Files

The following table lists the commands for building the standard ext_comm and ext_serial_win32 modules on PC and UNIX® platforms.

Platform

Commands

Windows®, TCP/IP

cd (matlabroot)
mex toolbox/coder/simulinkcoder_core/ext_mode/host/common/ext_comm.c ...
toolbox/coder/simulinkcoder_core/ext_mode/host/common/ext_convert.c ...
toolbox/coder/simulinkcoder_core/ext_mode/host/common/rtiostream_interface.c ...
toolbox/coder/simulinkcoder_core/ext_mode/host/common/ext_util.c ...
-R2018a ...
-Itoolbox/coder/rtiostream/src ...
-Itoolbox/coder/rtiostream/src/utils_host ...
-Itoolbox/coder/simulinkcoder_core/ext_mode/host/common/include ...
-Irtw/c/src/ext_mode/common ...
-lmwrtiostreamutils -lmwsl_services ...
-DEXTMODE_TCPIP_TRANSPORT ...
-DSL_EXT_DLL -output my_ext_comm

Note

The rtiostream_interface.c function defines RTIOSTREAM_SHARED_LIB as libmwrtiostreamtcpip and dynamically loads the MathWorks TCP/IP rtiostream shared library. Modify this file if you need to load a different rtiostream shared library.

Linux®, TCP/IP

Use the Windows commands, with these changes:

  • Change -DSL_EXT_DLL to -DSL_EXT_SO.

  • Replace back slashes with forward slashes.

Mac, TCP/IP

Use the Windows commands, with these changes:

  • Change -DSL_EXT_DLL to -DSL_EXT_DYLIB.

  • Replace back slashes with forward slashes.

Windows, serial

cd (matlabroot)
mex toolbox\coder\simulinkcoder_core\ext_mode\host\common\ext_comm.c ...
toolbox\coder\simulinkcoder_core\ext_mode\host\common\ext_convert.c ...
toolbox\coder\simulinkcoder_core\ext_mode\host\serial\ext_serial_transport.c ...
toolbox\coder\simulinkcoder_core\ext_mode\host\serial\ext_serial_pkt.c ...
toolbox\coder\simulinkcoder_core\ext_mode\host\serial\rtiostream_serial_interface.c ...
toolbox\coder\simulinkcoder_core\ext_mode\host\common\ext_util.c ...
-R2018a ...
-Itoolbox\coder\rtiostream\src ...
-Itoolbox\coder\rtiostream\src\utils_host ...
-Itoolbox\coder\simulinkcoder_core\ext_mode\host\common ...
-Itoolbox\coder\simulinkcoder_core\ext_mode\host\common\include ...
-Irtw\c\src\ext_mode\common ...
-Irtw\c\src\ext_mode\serial ...
-lmwrtiostreamutils -lmwsl_services ...
-DEXTMODE_SERIAL_TRANSPORT -DSL_EXT_DLL ...
-output my_ext_serial_comm

Note

The rtiostream_interface.c function defines RTIOSTREAM_SHARED_LIB as libmwrtiostreamserial and dynamically loads the MathWorks serial rtiostream shared library. Modify this file if you need to load a different rtiostream shared library.

Linux, serial

Use the Windows commands, with these changes:

  • Change -DSL_EXT_DLL to -DSL_EXT_SO.

  • Replace back slashes with forward slashes.

Mac, serial

Use the Windows commands, with these changes:

  • Change -DSL_EXT_DLL to -DSL_EXT_DYLIB.

  • Replace back slashes with forward slashes.

Note

mex requires a compiler supported by the MATLAB API. See the mex reference page and Choosing a MATLAB API for Your Application for more information about the mex function.

Register a Custom Client (Host) Transport Protocol

To register a custom client transport protocol with the Simulink software, you must add an entry of the following form to an sl_customization.m file on the MATLAB path:

function sl_customization(cm)
  cm.ExtModeTransports.add('stf.tlc', 'transport', 'mexfile', 'Level1');
% -- end of sl_customization

where

  • stf.tlc is the name of the system target file for which the transport will be registered (for example, 'grt.tlc')

  • transport is the transport name to display in the Transport layer menu on the Interface pane of the Configuration Parameters dialog box (for example, 'mytcpip')

  • mexfile is the name of the transport's associated external interface MEX-file (for example, 'ext_mytcpip_comm')

You can specify multiple targets and/or transports with additional cm.ExtModeTransports.add lines, for example:

function sl_customization(cm)
  cm.ExtModeTransports.add('grt.tlc', 'mytcpip', 'ext_mytcpip_comm', 'Level1');
  cm.ExtModeTransports.add('ert.tlc', 'mytcpip', 'ext_mytcpip_comm', 'Level1');
% -- end of sl_customization

If you place the sl_customization.m file containing the transport registration information on the MATLAB path, your custom client transport protocol will be registered with each subsequent Simulink session. The name of the transport will appear in the Transport layer menu on the Interface pane of the Configuration Parameters dialog box. When you select the transport for your model, the name of the associated external interface MEX-file will appear in the noneditable MEX-file name field, as shown in the following figure.

Create a Custom Server (Target) Transport Protocol

The rtIOStream* function prototypes in matlabroot/toolbox/coder/rtiostream/src/rtiostream.h define the calling interface for both the server (target) and client (host) side transport layer functions.

  • The TCP/IP implementations are in matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c.

  • The serial implementations are in matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c.

Note

The Ext* function prototypes in matlabroot/rtw/c/src/ext_mode/common/ext_svr_transport.h are implemented in matlabroot/rtw/c/src/ext_mode/common/rtiostream_interface.c or matlabroot/rtw/c/src/ext_mode/serial/rtiostream_serial_interface.c. In most cases you will not need to modify rtiostream_interface.c or rtiostream_serial_interface.c for your custom TCP/IP or serial transport layer.

To implement the server (target) side of your low-level TCP/IP or serial transport protocol:

  1. Edit the template matlabroot/toolbox/coder/rtiostream/src/rtiostreamtcpip/rtiostream_tcpip.c or matlabroot/toolbox/coder/rtiostream/src/rtiostreamserial/rtiostream_serial.c to replace low-level communication calls with your own communication calls.

    1. Copy and rename the file to rtiostream_name.c (replacing name with a name meaningful to you).

    2. Replace the functions rtIOStreamOpen, rtIOStreamClose, rtIOStreamSend, and rtIOStreamRecv with functions (of the same name) that call your low-level communication drivers.

      You must implement the functions defined in rtiostream.h, and your implementations must conform to the prototypes defined in that file. Refer to the original rtiostream_tcpip.c or rtiostream_serial.c for guidance.

  2. Incorporate the external mode source files for your transport layer into the model build process. Use a build process mechanism such as a post code generation command or a before_make hook function to make the transport files available to the build process. For more information on the build process mechanisms, see Customize Post-Code-Generation Build Processing, Customize Build Process with STF_make_rtw_hook File, and Customize Build Process with sl_customization.m.

    For example:

    • Add the file created in the previous step to the build information:

      path/rtiostream_name.c
    • For TCP/IP, add the following file to the build information:

      matlabroot/rtw/c/src/ext_mode/common/rtiostream_interface.c
    • For serial, add the following files to the build information:

      matlabroot/rtw/c/src/ext_mode/serial/ext_serial_pkt.c
      matlabroot/rtw/c/src/ext_mode/serial/rtiostream_serial_interface.c
      matlabroot/rtw/c/src/ext_mode/serial/ext_svr_serial_transport.c

Note

For external mode, check that rtIOStreamRecv is not a blocking implementation. Otherwise, it might cause the external mode server to block until the host sends data through the comm layer.

Serial Receive Buffer Smaller than 64 Bytes

For serial communication, if the serial receive buffer of your target is smaller than 64 bytes:

  1. Update the following macro with the actual target buffer size:

    #define TARGET_SERIAL_RECEIVE_BUFFER_SIZE 64

    Implement the change in the following files:

    matlabroot/rtw/c/src/ext_mode/serial/ext_serial_utils.c
    matlabroot/toolbox/coder/simulinkcoder_core/ext_mode/host/serial/ext_serial_utils.c
  2. Run the command to rebuild the ext_serial_win32 MEX-file. See MATLAB Commands to Rebuild ext_comm and ext_serial_win32 MEX-Files.

Related Topics