Skip to content

kmtronic_usb_relay

This project is a Python package for controlling KMTronics USB relay boards. It provides a simple interfaces to interact with the relays, allowing you to turn them on and off programmatically.

It also includes a GUI and FastApi implementation for easy control of the relays.

usage

kmtronic_usb_relay_gui

python -m src.kmtronic_usb_relay.four_channel_relay_gui

kmtronic_usb_relay_gui

kmtronic_usb_relay_api

python -m src.kmtronic_usb_relay.four_channel_relay_api

kmtronic_usb_relay_api

source manual


RelayController(com_port, switch_delay=1.0, serial_utils=None, auto_connect=True)

Controller for KMTronic 4-Channel USB Relay devices.

Example

with RelayController("COM4") as relay: relay.turn_on(1) relay.turn_off(2) print(relay.statuses)

Initialize the RelayController.

Parameters:

Name Type Description Default
com_port str

The COM port to which the relay board is connected (e.g., 'COM4').

required
switch_delay float

Delay in seconds after switching a relay (default: 1.0).

1.0
serial_utils Optional[SerialComUtils]

Custom SerialComUtils instance for testing/mocking.

None
auto_connect bool

Automatically open connection on init (default: True).

True

is_connected property

Check if the relay controller is connected to the COM port.

Returns:

Name Type Description
bool bool

True if connected, False otherwise.

statuses property

Get the status of all relays as a dictionary.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Dictionary mapping relay names (e.g., 'R1') to their status ('ON' or 'OFF').

__enter__()

Enter the runtime context related to this object.

Returns:

Name Type Description
RelayController RelayController

The connected relay controller instance.

__exit__(exc_type, exc_val, exc_tb)

Exit the runtime context and close the serial connection.

Parameters:

Name Type Description Default
exc_type Optional[type]

Exception type.

required
exc_val Optional[BaseException]

Exception value.

required
exc_tb Optional[object]

Exception traceback.

required

close()

Close the serial connection to the relay board.

This method is safe to call multiple times.

connect()

Open the serial connection to the relay board.

Raises:

Type Description
Exception

If the connection cannot be established.

get_statuses()

Query and return the status of all relays.

Returns:

Type Description
Dict[str, str]

Dict[str, str]: Dictionary mapping relay names (e.g., 'R1') to their status ('ON' or 'OFF').

Dict[str, str]

Returns an empty dict if communication fails.

turn_off(relay_number)

Turn OFF the specified relay.

Parameters:

Name Type Description Default
relay_number int

Relay number to turn OFF (1-4).

required

Raises:

Type Description
ValueError

If relay_number is out of range.

Exception

If sending the command fails.

turn_on(relay_number)

Turn ON the specified relay.

Parameters:

Name Type Description Default
relay_number int

Relay number to turn ON (1-4).

required

Raises:

Type Description
ValueError

If relay_number is out of range.

Exception

If sending the command fails.

RelayControllerApi(com_port='COM4', controller=None)

User-friendly wrapper to run the FastAPI server for KMTronic USB Relay.

Example

api = RelayControllerApi("COM4") api.run()

Initialize the API server wrapper.

Parameters:

Name Type Description Default
com_port str

Serial port for the relay board (e.g., "COM4" or "/dev/ttyUSB0").

'COM4'
controller Optional[RelayController]

Optional RelayController instance for testing/mocking.

None

run(host='127.0.0.1', port=8000, reload=False)

Start the FastAPI server using uvicorn.

Parameters:

Name Type Description Default
host str

Hostname or IP address to bind the server.

'127.0.0.1'
port int

Port number to bind the server.

8000
reload bool

Enable auto-reload (for development).

False

create_app(com_port, controller=None)

Create and configure a FastAPI app for the KMTronic 4-Channel USB Relay.

Parameters:

Name Type Description Default
com_port str

Serial port for the relay board.

required
controller Optional[RelayController]

Optional RelayController instance (for testing/mocking).

None

Returns:

Type Description
FastAPI

Configured FastAPI app.

get_app()

Get a FastAPI app instance for ASGI servers (e.g., uvicorn). Uses the KMTRONIC_COM_PORT environment variable or defaults to 'COM4'.

main()

Command-line entry point to run the API server.

Usage

python -m src.kmtronic_usb_relay.four_channel_relay_api [COM_PORT] [--host HOST] [--port PORT] [--reload]

select_com_port()

Helper to select a COM port interactively if not provided. Returns the selected COM port or None if not available.

RelayControllerGui(com_port='', controller=None, relay_names=None)

User-friendly GUI for KMTronic USB 4-channel relay module. Provides an interface to connect, control, and monitor relays.

Initialize the RelayControllerGui.

Parameters:

Name Type Description Default
com_port str

Default COM port to select.

''
controller Optional[RelayController]

Optional pre-initialized RelayController.

None
relay_names Optional[List[str]]

Optional list of relay names for labeling buttons.

None

__del__()

Destructor to ensure resources are released when the object is deleted.

close()

Close the GUI and release resources. Closes the relay controller connection and destroys the main window.

refresh_ports()

Refresh the list of available serial ports and update the port selection combobox. Enables or disables the connect button based on port availability.

run()

Start the GUI main loop. Call this method to launch the application.

main()

Entry point for running the GUI as a standalone application.

SerialComUtils(baudrate=9600, bytesize=serial.EIGHTBITS, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, timeout=2.5)

User-friendly utility class for serial COM port communication.

This class provides methods for discovering available serial ports, connecting/disconnecting to a port, and sending/receiving data. It also supports context management for safe resource handling.

Initialize SerialComUtils with serial parameters.

Parameters:

Name Type Description Default
baudrate int

Serial baudrate (default: 9600).

9600
bytesize int

Number of data bits (default: serial.EIGHTBITS).

EIGHTBITS
stopbits int

Number of stop bits (default: serial.STOPBITS_ONE).

STOPBITS_ONE
parity str

Parity setting (default: serial.PARITY_NONE).

PARITY_NONE
timeout float

Read timeout in seconds, or None for blocking mode (default: 2.5).

2.5

is_connected property

Check if the serial connection is open.

Returns:

Name Type Description
bool bool

True if connected, False otherwise.

__enter__()

Enter the runtime context related to this object.

Returns:

Name Type Description
SerialComUtils SerialComUtils

The instance itself.

__exit__(exc_type, exc_val, exc_tb)

Exit the runtime context and close the serial connection.

Parameters:

Name Type Description Default
exc_type Optional[type]

Exception type.

required
exc_val Optional[BaseException]

Exception value.

required
exc_tb Optional[object]

Exception traceback.

required

__repr__()

Return a string representation of the SerialComUtils instance.

Returns:

Name Type Description
str str

Human-readable summary of the current configuration and port.

close_connection()

Close the connection to the COM port.

Returns:

Name Type Description
bool bool

True if disconnected or already closed, False if error occurred.

connect(port)

Open a connection to a COM port with the configured parameters.

Parameters:

Name Type Description Default
port str

Device name of the port (e.g., 'COM3').

required

Returns:

Name Type Description
bool bool

True if connection was successful, False otherwise.

disconnect()

Alias for close_connection. Closes the serial connection.

Returns:

Name Type Description
bool bool

True if disconnected or already closed, False if error occurred.

format_port_detail(port_info) staticmethod

Format a port info dictionary as a readable string.

Parameters:

Name Type Description Default
port_info dict

Dictionary with keys 'device', 'description', 'hwid'.

required

Returns:

Name Type Description
str str

Formatted string describing the port.

get_busy_ports() staticmethod

Attempt to list COM ports that are currently in use (best effort).

Returns:

Type Description
List[str]

List[str]: List of port device names that are in use.

get_connection_params()

Get the current serial connection parameters.

Returns:

Name Type Description
dict Dict[str, Any]

Dictionary containing baudrate, bytesize, stopbits, parity, and timeout.

get_port_details() staticmethod

Get details of all available COM ports.

Returns:

Type Description
List[Dict[str, Any]]

List[dict]: Each dict contains: - device (str): COM port number (e.g., 'COM1') - description (str): Port description - hwid (str): Hardware ID

get_port_names() staticmethod

List all available COM port device names.

Returns:

Type Description
List[str]

List[str]: List of device names (e.g., ['COM1', 'COM2']).

log_port_details(port_name=None) staticmethod

Log details of all COM ports or a specific port if port_name is given.

Parameters:

Name Type Description Default
port_name str

Device name of the port (e.g., 'COM3').

None

open_connection(port)

Alias for connect. Opens a connection to the specified port.

Parameters:

Name Type Description Default
port str

Device name of the port.

required

Returns:

Name Type Description
bool bool

True if connection was successful, False otherwise.

receive(size=1, as_int_list=False)

Receive data from the serial port.

Parameters:

Name Type Description Default
size int

Number of bytes to read (default: 1).

1
as_int_list bool

If True, return a list of ints instead of bytes.

False

Returns:

Type Description
Optional[Union[bytes, List[int]]]

bytes or List[int] or None: Received data, or None if not connected.

send(data)

Send data to the serial port.

Parameters:

Name Type Description Default
data bytes

Bytes to send.

required

Returns:

Name Type Description
bool bool

True if sent, False if not connected.