Skip to content

Detailed Description

Connection

COM port connector on MIO04:

COM port connector

Pin functionality as viewed from MIO04:

Pin Symbol Description
1 RS485_TX+ RS485 positive transmit line
2 RS232_TXD RS232 transmit line
3 RS232_RXD RS232 receive line
4 RS485_RX+ RS485 positive receive line
5 GND Ground (isolated from other interfaces)
6 RS485_TX- RS485 negative transmit line
7 RS232_CTS RS232 clear to send
8 RS232_RTS RS232 request to send
9 RS485_RX- RS485 negative receive line

Typical Connection Examples

COM port connection

Info

Whether you use RS232 or RS485 is defined solely by the hardware wiring. Hardware flow control and half-/full-duplex operation must be configured in software.

Info

For RS485/RS422 half-duplex operation, connect the COM port RX pins with the corresponding TX pins externally.

Info

In RS485/RS422 mode, add termination resistors to the end of the line. The termination must be 120 ohms at each end of the cable.

COM Port Functionality via REST API

The COM ports of the MIO04 can be accessed via a REST API. The REST API provides endpoints for configuration and data exchange.

See section Device Parameters for details on how to configure the COM ports via the REST API. Parameters only need to be configured once; they are stored persistently in non-volatile memory and retained when the device is powered off or restarted. After a parameter change, a reboot is required to activate the new setting.

Data Exchange via WebSocket

Payload data can be sent and received via a WebSocket connection. Each COM port provides two WebSocket endpoints:

Endpoint Description
/api/v1/{com-port}/ws Transparent bridge: WebSocket messages are written to the COM port as-is, without flow control.
/api/v1/{com-port}/ws-v2 Bridge with a small framing protocol and flow control, for gap-free streaming without data loss (see Flow-Controlled Streaming (ws-v2)). Available since firmware 1.1.0.

{com-port} is either com1 or com2, e.g. wss://<device-ip>/api/v1/com1/ws.

The WebSocket connection uses the same authentication and TLS settings as the REST API.

WebSocket Exchange

Connection Handling

The following rules apply to both endpoints:

  • Only one client can be connected to a COM port at a time, either on /ws or on /ws-v2. A second client is rejected with HTTP status 409 Conflict (error code ws-0001), before the WebSocket is opened.
  • If the authentication fails, the client is rejected with HTTP status 401 Unauthorized after a delay of 3 seconds.
  • A plain HTTP GET without WebSocket upgrade headers is rejected with HTTP status 400 Bad Request (error code ws-0002).
  • Keepalive: if the client has not sent anything for 5 seconds, the device sends a WebSocket PING. A client that sends no frame (data or PONG) for 20 seconds is disconnected. This frees the COM port if the client vanished without closing the connection (e.g. cable pulled, host crashed). Clients must answer PINGs with a PONG, as required by RFC 6455. Most WebSocket libraries do this automatically.
  • A client that does not take data from the device for 2 seconds is disconnected.

Send Data (ws)

Data written to the WebSocket is sent to the UART transmit buffer without any conversions.

  • Use binary frames to avoid implicit character encoding conversions.
  • Use a maximum frame size of 2048 bytes. Larger frames cannot be handled by the firmware and will cause the connection to be closed.

The transmit buffer has a size of 8192 bytes. If the buffer is full, additional data will be dropped until there is space in the buffer again. Dropped bytes are counted in the metric send_bytes_dropped_total. There is no flow control, so sending data faster than the COM port can handle will cause data loss. Use the /ws-v2 endpoint if you need flow control.

Receive Data

Data received from the COM port is forwarded to the WebSocket client as binary messages. There are no implicit character encoding conversions. Message boundaries are not preserved; the data may be split into messages differently than it was sent by the remote device. Data received while no client is connected is discarded.

Data is lost if the client cannot receive the data fast enough, e.g. because the client is busy with processing previous data or because of network issues. Lost data is counted in the metrics rx_buffer_full_total and rx_fifo_overflow_total.

Flow-Controlled Streaming (ws-v2)

The /ws-v2 endpoint adds flow control from the host to the COM port. Use it to stream large amounts of data to the COM port without gaps and without data loss, e.g. a firmware image to a device that aborts its update when the serial stream pauses.

All messages are binary WebSocket frames, one message per frame (no fragmentation). Multi-byte fields are little-endian.

Message Layout Direction Description
TX 0x01 seq:u16 data[0..2048] Host → device Data to send on the COM port. seq is chosen by the host and echoed by the device.
TX_DONE 0x02 seq:u16 Device → host The data of TX seq is in the transmit buffer. The host may send the next TX.
RX 0x03 data[1..2048] Device → host Data received from the COM port.
ERROR 0x04 seq:u16 code:u8 Device → host TX seq was not (completely) processed.

ERROR codes:

Code Name Meaning
1 BUSY TX received before the TX_DONE of the previous TX. The TX is discarded.
2 INVALID Message too short, unknown message type, text frame or fragmented frame. seq is 0.
3 TOO_LARGE Reserved, currently not sent.
4 UART_ERROR Writing to the COM port failed.

Rules:

  • Flow control is stop-and-wait: at most one TX may be outstanding per COM port. Send the next TX after you received the TX_DONE of the previous one.
  • TX_DONE means that the data is in the transmit buffer of the device, not that it has been sent on the wire.
  • An empty TX (no data) is answered with TX_DONE.
  • The connection stays open after an ERROR. A frame larger than 2051 bytes (3 bytes header + 2048 data bytes) closes the connection.
  • If the client disconnects while a TX is written to the transmit buffer, the rest of that TX is discarded. Data already in the transmit buffer is still sent.

The transmit buffer holds 8192 bytes. As long as the host sends the next TX immediately after the TX_DONE, the buffer bridges the network round trip and the COM port sends without gaps. The metric tx_idle_starts_total counts the TX messages that started while the COM port transmitter was idle, i.e. the stream had a gap. For a gap-free stream it increases by exactly 1 (the first TX).

Note

For gap-free streaming, avoid other HTTPS activity on the device while streaming (REST API calls, new connections, failed logins), because one HTTPS server handles the REST API and the WebSockets of both COM ports. A wired Ethernet connection is recommended; with WLAN, delays in the network can cause gaps at high baud rates.

Example: send a file over COM1 with ws-v2 (Python, websockets library). Connection settings as in the Quick Start Guide.

import asyncio
import base64
import ssl
import struct
import sys

from websockets.asyncio.client import connect

URL = 'wss://192.168.24.213/api/v1/com1/ws-v2'
USERNAME = 'io4edge'
PASSWORD = 'core_io4edge'
CHUNK = 2048


async def main(path: str) -> None:
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE  # only for testing, see Quick Start Guide
    token = base64.b64encode(f'{USERNAME}:{PASSWORD}'.encode()).decode()
    data = open(path, 'rb').read()

    async with connect(URL, ssl=ctx, additional_headers={'Authorization': f'Basic {token}'}) as ws:
        seq = 0
        for off in range(0, len(data), CHUNK):
            await ws.send(struct.pack('<BH', 0x01, seq) + data[off:off + CHUNK])
            while True:
                msg = await ws.recv()
                if msg[0] == 0x03:  # RX: data received from the COM port
                    continue
                kind, ack_seq = struct.unpack_from('<BH', msg)
                if kind == 0x04:
                    raise RuntimeError(f'TX {ack_seq} failed with error code {msg[3]}')
                if kind == 0x02 and ack_seq == seq:
                    break
            seq = (seq + 1) & 0xFFFF
        print(f'sent {len(data)} bytes')


asyncio.run(main(sys.argv[1]))

Half Duplex Mode

Half-duplex mode can be enabled via the halfduplex parameter. In half-duplex mode, the COM port can only transmit or receive data at a time. The firmware automatically activates the sender during transmission.

Note that sent data is looped back to the receive buffer, so the client will receive the data it has sent. This means that the client needs to keep track of the sent data if it needs to correlate it with received data.

Limitations

The COM port support of the MIO04 has the following limitations:

  • No flow control on UART (RTS/CTS or XON/XOFF).
  • Only one client can be connected to a COM port at a time (on /ws or /ws-v2). If a second client tries to connect, the connection will be rejected.
  • Maximum baud rate is 500000 baud, the limit of the RS485 transceivers.
  • The HTTPS server of the device has only 2 sockets. If both are in use (e.g. two open WebSockets), a new connection (e.g. a REST API call) closes the least recently used connection, which can be an open WebSocket.

Device Management

The device provides an HTTPS REST interface for device management and configuration. See REST API for details.

The major features are:

  • Firmware update
  • Firmware version information
  • Hardware inventory information
  • Configuration of device parameters
  • Device restart
  • Factory reset
  • Download of the core dump of the last firmware crash (GET /coredump), for analysis by Ci4Rail
  • Factory defaults for the REST API password and the TLS certificate/key (/factory/... endpoints). They are used as long as no user password or certificate is set, and are restored by a factory reset.

The REST API is protected by HTTP basic authentication. The default password should be changed by the user.

The HTTPS server comes with a self-signed certificate. For production use, it is recommended to replace it with a certificate signed by a trusted CA. This can be done via the REST API.

You can directly use the REST API from your application or use the io4edge-cli command-line tool, which provides a convenient wrapper around the REST API. Releases are available at the io4edge-client-go GitHub repository.

Firmware Repository

You can find the latest firmware images at the MIO04 Public Firmware Repository.

Recovery Mode

If the firmware crashes repeatedly (6 fault resets such as panic, watchdog or CPU lockup within 10 minutes), the device starts in recovery mode:

  • The COM ports are not available. The /api/v1/{com-port}/... endpoints return 404, and the COM port metrics are missing.
  • The global REST API (e.g. firmware update, restart, factory reset, core dump download) stays available, so the device can still be serviced.
  • If the crashes started after a firmware update, the new firmware is not confirmed, so the next restart rolls back to the previous firmware.

A restart via the REST API (POST /restart) leaves recovery mode. Restarts via the REST API, the console or a firmware update don't count as fault resets.

Device Parameters

Device parameters are persistently stored in non-volatile memory. They are retained when the device is powered off or restarted. Parameters can be configured via the REST API.

The device has two classes of parameters: Global device parameters and COM specific parameters.

Global Device Parameters

Global device parameters are common to all Ci4Rail ModuSio devices.

They can be set over the network using the PUT /parameter/{parameter-name} REST API, or through the console, via the param set <parameter-name> <value> command.

Parameter Description Default Example
device-id Identifies the device in the network (e.g. via mDNS) (None) MIO04-1
static-ip static IP address, network mask and gateway. If not set, DHCP is used. (None) 192.168.11.11:255.255.255.0:192.168.11.1
wifi-ssid WiFi SSID to connect to (if not set, WiFi is disabled) (None) MyWiFiNetwork
wifi-pw WiFi password (if not set, WiFi is disabled) (None) MyWiFiPassword
wifi-low-rssi If set, device starts to scan for better APs if the signal strength drops below this value (unit: dBm) -100 -75

COM Specific Parameters

These are specific to the COM interfaces. They can be set as a ParameterSet or as single parameters.

Using ParameterSets has the advantage that all parameters are set atomically and you can upload a version number for that set. This makes it possible to keep track of configuration changes. The default version is "factory".

When manipulating single parameters, the version number is appended with a "(modified)" suffix.

Use the PUT /{com-port}/parameterset REST API to set a ParameterSet, or the PUT /{com-port}/parameter/{parameter-name} REST API to set single parameters. {com-port} can be either com1 or com2.

Via the console, only single parameters can be set, using the param {com-port}.{parameter-name} <value> command.

Parameter Description Default Example
baudrate Baud rate of the COM interface (300 to 500000) 9600 115200
databits Number of data bits per character (7 or 8) 8 7
stopbits Number of stop bits per character (1 or 2) 1 2
parity Parity of the COM interface (none, even, odd) none even
halfduplex Enable half-duplex operation (on, off) off on

Diagnostics

The device exposes metrics and log data for diagnostics and monitoring.

Device Metrics

The device provides metrics via the Prometheus API, delivering Prometheus text-based metrics. They can be directly consumed by a Prometheus server.

The metrics are available at https://<device-ip>:9100/metrics. They are protected by HTTP basic authentication with the same credentials as the REST API (user io4edge) and served with the same TLS certificate.

Note

Up to firmware 1.0.0, the metrics were served over plain HTTP without authentication. Since firmware 1.1.0, Prometheus scrape configurations must use HTTPS and basic authentication.

Example Prometheus scrape configuration:

scrape_configs:
  - job_name: mio04
    scheme: https
    basic_auth:
      username: io4edge
      password: <your password>
    tls_config:
      ca_file: <CA certificate of the device certificate>
    static_configs:
      - targets: ['<device-ip>:9100']

The metrics server accepts one connection at a time and supports TLS session resumption, so repeated scrapes don't need a full TLS handshake.

List of available metrics:

Metric Name Label Type Description
reset_count reason Counter Number of device resets, labeled by reset reason (see below)
free_heap_bytes Gauge Free heap memory in bytes
up_seconds Counter Uptime in seconds
bytes_received_from_host_total interface Counter Number of bytes received from host over WebSocket, total count
bytes_sent_to_host_total interface Counter Number of bytes sent to host over WebSocket, total count
uart_bytes_received_total interface Counter Number of bytes received from UART, total count
uart_bytes_sent_total interface Counter Number of bytes sent to UART, total count
send_bytes_dropped_total interface Counter Number of bytes from the host that were not sent to the UART (ws: transmit buffer full; ws-v2: client disconnected during a TX)
rx_buffer_full_total interface Counter Number of times the UART RX buffer was full, total count
rx_fifo_overflow_total interface Counter Number of times the UART RX FIFO overflowed, total count
rx_frame_error_total interface Counter Number of times a UART frame error occurred, total count
rx_parity_error_total interface Counter Number of times a UART parity error occurred, total count
tx_busy_rejects_total interface Counter Number of ws-v2 TX messages rejected with ERROR BUSY
tx_idle_starts_total interface Counter Number of ws-v2 TX messages that started while the UART transmitter was idle

The label interface is com1 or com2.

The label reason of reset_count is one of the hardware reset reasons (poweron, external, software, panic, interruptwd, taskwd, wd, brownout, cpulockup, ...) or one of the application reset reasons:

Reason Description
firmware-update Restart after a firmware update
rest-command Restart via REST API (POST /restart)
factory-reset Restart after a factory reset
console-command Restart via console command
core-command Restart via io4edge core command

Log Data

Log data is available via TCP port 9998. The log data is in plain text format and can be viewed using netcat, e.g. nc <device-ip> 9998.

Example log data:

I (2382) reset_counters: Reset reason unknown count: 0
I (2382) reset_counters: Reset reason poweron count: 4
I (2382) reset_counters: Reset reason external count: 0

Each line begins with a log level indicator: I for info, W for warning, E for error. This is followed by a timestamp in milliseconds since boot, the module name, and the log message.

Note

The log data is not persistent, so it is lost when the device is powered off or restarted. It is recommended to use a log collector to store the log data persistently. Furthermore, the device can only buffer a few lines of log data; older log data is lost when the buffer is full.

LLDP

The MIO04 supports sending Link Layer Discovery Protocol (LLDP) frames for network topology discovery and management. Received LLDP frames are ignored.

LLDP is defined by IEEE 802.1AB. It is a vendor-neutral, Layer 2 neighbor discovery protocol that uses Ethernet multicast destination MAC 01:80:C2:00:00:0E and Ethertype 0x88CC. LLDP frames carry a sequence of TLVs (Type-Length-Value) describing the chassis, port, and system capabilities.

The LLDP Frame is sent every 30 seconds with the following content

  • Chassis ID: Ethernet MAC Address of the Device
  • Port: Fixed to eth0
  • TTL: 120 seconds (How long the neighbor shall treat the last info as valid)
  • System Name: Hardware Model, e.g. S103-MI004-01-00002
    • If no io4edge device-id is set: <Model>-<Serial>, e.g. S103-MI004-01-00002-a6c00f31-dc59-4a36-86e3-c8f7deb754b3
    • or device-id if it is set
  • System Description:
    • <Vendor> <Model> <Serial> <Firmware>, e.g. Ci4Rail S103-MIO04-01-00002 0fcb64c3-ff8b-4f6f-8708-f33c1f4d88c6 fw-mio04-01-restapi_0.3.0

System Application Conditions

The following conditions must be fulfilled by the user to ensure correct operation of the device:

  • [01] If no static IP is configured, the user must provide a DHCP server so that the device can obtain an IP address on boot.
  • [02] The user shall change the default REST API password during provisioning.
  • [03] The user shall configure a valid certificate for the REST API during provisioning, matching the device’s address.

Device Security

The device implements several security features to protect against unauthorized access and ensure data integrity.

Secure Boot and Flash Encryption

The device implements Secure Boot and Flash Encryption to protect the integrity and confidentiality of the firmware and configuration data.

This means:

  • Only firmware images signed by Ci4Rail can be booted
  • Firmware updates via the console are disabled; only firmware updates via REST API are possible
  • Anti-rollback: A firmware image with a lower secure version number than the currently installed version cannot be installed
  • The firmware and configuration data stored in flash memory are encrypted, so they cannot be read by an attacker with physical access to the device

REST API Security

The REST API is protected by HTTP basic authentication. The default password should be changed by the user (see System Application Conditions, [02]).

The same applies to the WebSocket endpoints and, since firmware 1.1.0, to the metrics interface.

Furthermore, the REST API uses HTTPS to encrypt the communication between the client and the server. The device comes with a self-signed certificate. For production use, it is recommended to replace it with a certificate signed by a trusted CA (see System Application Conditions, [03]).

Non-Secure Interfaces

Due to the nature of the protocols, the following interfaces are not secure.

  • Log interface: There is no authentication or encryption, so an attacker with network access can read the log data.

Open Source Declaration

This product includes open source software.

You must adhere to the license terms of the open source software. Each release in the Firmware Repository contains a licences.tar.gz file with the following contents:

  • OPEN_SOURCE_NOTICES.txt - statement of open source software used in this release
  • sbom.spdx - SPDX Software Bill of Materials (SBOM)
  • licences.tar.gz - archive containing the license texts of the open source software used in this release