Serial IO#

This protocol carries the messages over a serial port, for a microcontroller such as an Arduino.

Note

If a client library is available for your language, you do not need to implement this protocol.

Note

Streams and events are not supported over serial IO. The server accepts the stream and event RPCs, but their updates go out as fast as the game makes them and can fill its write buffer, as described under Buffering and Data Rates.

Configuring the Server#

To use this protocol, add a server in the server window and select Protobuf over SerialIO as its protocol. The window sets the serial port and its line settings: the baud rate, data bits, parity, stop bits and flow control. The baud rate defaults to 9600.

Flow Control#

The server uses no flow control by default. At high baud rates, a USB serial adapter can drop bytes when it receives them faster than its host reads them. Setting Flow control to RTS/CTS pauses each end’s sending while the other end is not ready.

RTS/CTS needs both ends set to it, and a cable that carries the RTS and CTS lines. A server set to RTS/CTS sends nothing while the client holds its RTS line low, or while its CTS line is unconnected. Many microcontroller boards wire only TX and RX, so they cannot use it.

The flow control is hardware only. XON/XOFF would stop the line on bytes that occur in the binary messages.

Framing#

The framing is the same as for TCP/IP. Each message is a Message, prefixed with its size in bytes, encoded as a varint.

Sessions#

Open the serial port, then send the connection handshake. The server serves one session on the port at a time.

A serial line has no connect or disconnect. A session ends with a disconnect, after which the server reads the next message as a connection_request. A connection_request sent during a session also starts a new one.

Resetting Clients#

A client that resets, such as an Arduino after a power cycle, can find the line in the state its earlier session left it in. The server ends a session whose message stalls for 3 seconds partway, and drops the partial message. The client specification states how a client resumes a line. See Connection.

A server with “Auto-accept new clients” turned off answers a connection request only once the player approves it. A client of such a server connects with no handshake timeout, so it recovers from a stale partial message only by a manual reset.

Buffering and Data Rates#

A serial port carries data far more slowly than the game produces it. At the default 9600 baud it carries roughly a thousand bytes per second. The server buffers up to a megabyte of data it receives, and 16 megabytes of data it sends:

  • Data received from the port waits in its buffer until the game reads it. A full buffer pauses reading from the port. With RTS/CTS, the client’s sending then pauses too, and no data is lost. Without it, the port’s own small buffer overflows and drops data.

  • Data written by the game waits in its buffer until the port has sent it. A single response larger than the buffer is still sent. The buffer fills when a client sends requests faster than it reads their responses. The server then drops the session and stops, and is started again from the server window.

To keep the write buffer from filling, read each response before sending the next request.

Example#

Note

This example shows the protocol, and omits much of the behavior a client library needs, such as handling errors and failed connections. A client library should implement the client specification in its entirety.

The following script connects to a server on the serial port /dev/ttyUSB0 with the name “Example”, calls KRPC.GetStatus and prints the server version. It then ends the session with a disconnect:

import serial
from google.protobuf.internal.decoder import _DecodeVarint
from google.protobuf.internal.encoder import _VarintEncoder

from krpc.schema import KRPC_pb2 as KRPC


def encode_varint(value):
    """Encode an int as a protobuf varint"""
    data = []
    _VarintEncoder()(data.append, value, False)
    return b"".join(data)


def decode_varint(data):
    """Decode a protobuf varint to an int"""
    return _DecodeVarint(data, 0)[0]


def decode_string(data):
    """Decode a string: its length as a varint, then its UTF-8 bytes"""
    size, position = _DecodeVarint(data, 0)
    return data[position : position + size].decode("utf-8")


def send_message(conn, msg):
    """Send a message, prefixed with its size, to a serial port"""
    data = msg.SerializeToString()
    size = encode_varint(len(data))
    conn.write(size + data)


def recv_message(conn):
    """Receive a Message, prefixed with its size, from a serial port"""
    # Receive the size of the message data
    data = b""
    while True:
        try:
            data += conn.read(1)
            size = decode_varint(data)
            break
        except IndexError:
            pass
    # Receive the message data
    data = conn.read(size)
    # Decode the message
    msg = KRPC.Message()
    msg.ParseFromString(data)
    return msg


# Open a connection to the serial port
conn = serial.Serial("/dev/ttyUSB0")

# Send a connection request
message = KRPC.Message()
message.connection_request.protocol_version = 2
message.connection_request.client_name = "Example"
send_message(conn, message)

# Receive the connection response
response = recv_message(conn).connection_response

# Check the connection was successful
if response.status != KRPC.ConnectionResponse.OK:
    raise RuntimeError("Connection failed: " + response.message)
if response.protocol_version != 2:
    raise RuntimeError("The server does not support protocol version 2")
print("Connected to the server")

# Invoke the KRPC.GetStatus RPC, in a request with the id 1
message = KRPC.Message()
message.request.id = 1
call = message.request.calls.add()
call.service = "KRPC"
call.procedure = "GetStatus"
send_message(conn, message)

# Receive the response, which carries the id of the request it answers
response = recv_message(conn).response
assert response.id == 1

# Check for an error in the response
if response.HasField("error"):
    raise RuntimeError("ERROR: " + str(response.error))

# Check for an error in the results
assert len(response.results) == 1
if response.results[0].HasField("error"):
    raise RuntimeError("ERROR: " + str(response.results[0].error))

# Decode the return value, a ServerStatus structure sent as a Tuple of its
# fields
status = KRPC.Tuple.FromString(response.results[0].value)

# Print out the server version, the first field
print(decode_string(status.items[0]))

# End the session with a disconnect, as a serial line has no close
disconnect = KRPC.Disconnect(reason=KRPC.Disconnect.CLOSED)
send_message(conn, KRPC.Message(disconnect=disconnect))
conn.close()