KSerial is a Kotlin-based, coroutine-friendly library built on top of JSSC (Java Simple Serial Connector) for efficient serial communication. Designed to handle robust data exchanges through features like auto-reconnect, configurable retries, and coroutine-based non-blocking IO, KSerial is ideal for applications requiring reliable serial communication over varied network conditions.
- Automatic Reconnection: Keeps the connection alive with retry mechanisms.
- Flexible Configuration: Highly customizable, allowing tailored data handling.
- Coroutine-Friendly: Optimized for non-blocking IO with Kotlin coroutines.
- Support for String and Hex Data: Handles multiple data formats with ease.
Option | Type | Default Value | Description |
---|---|---|---|
Port Name | String |
Required | Serial port to connect (e.g., "COM3" ). |
Baud Rate | Int |
115200 | Data transmission speed (bps). |
Data Bits | Int |
8 | Number of data bits. Options: 5, 6, 7, 8. |
Stop Bits | Int |
1 | Number of stop bits. Options: 1, 1.5, 2. |
Parity | Int |
SerialPort.PARITY_NONE |
Parity mode. Options: NONE, EVEN, ODD, MARK, SPACE. |
Retry Delay | Long (ms) |
3000 | Time delay between retries. |
Read Delay | Long (ms) |
100 | Delay after writing to read data. |
Auto Reconnect | Boolean |
false |
Reconnects on disconnect if enabled. |
Max Failure Count | Int |
3 | Max retry attempts before reset. |
Logger | (String) -> Unit |
{ println(it) } |
Custom logger for internal messaging. |
- Description: Initiates the builder pattern to configure a new
KSerial
instance. - Parameters:
port
: The serial port to connect.logger
: A lambda function for logging messages.
- Usage:
val serial = KSerial.builder("COM3") { message -> println(message) }.build()
- Description: Sets the baud rate for the serial communication.
- Parameters:
rate
: The baud rate (bps).
- Usage:
serial.baudRate(9600)
- Description: Configures the number of data bits.
- Parameters:
bits
: Number of data bits (5, 6, 7, 8).
- Usage:
serial.dataBits(8)
- Description: Sets the number of stop bits.
- Parameters:
bits
: Number of stop bits (1, 1.5, 2).
- Usage:
serial.stopBits(1)
- Description: Configures the parity mode.
- Parameters:
parity
: Options includePARITY_NONE
,PARITY_EVEN
,PARITY_ODD
, etc.
- Usage:
serial.parity(SerialPort.PARITY_EVEN)
- Description: Sets the time delay between reconnection attempts.
- Parameters:
delay
: Time in milliseconds.
- Usage:
serial.retryDelay(2000L)
- Description: Configures the delay after writing before reading data.
- Parameters:
delay
: Delay time in milliseconds.
- Usage:
serial.readDelay(150L)
- Description: Enables automatic reconnection on disconnect.
- Usage:
serial.enableAutoReconnect()
- Description: Sets the maximum number of reconnection attempts before giving up.
- Parameters:
count
: Max failure count.
- Usage:
serial.maxFailureCount(5)
- Description: Opens the serial port and starts listening for incoming data.
- Usage:
serial.start()
- Description: Sends a string of data through the serial port.
- Parameters:
data
: The string data to send.
- Usage:
serial.write("Hello, World!")
- Description: Sends a byte array (hex) through the serial port.
- Parameters:
data
: The byte array to send.
- Usage:
serial.write(byteArrayOf(0x01, 0x02, 0x03))
- Description: Reads data from the serial port and returns it as a string.
- Returns: The received string.
- Usage:
val response = serial.readString()
- Description: Reads raw bytes from the serial port.
- Returns: The received byte array.
- Usage:
val responseBytes = serial.readBytes()
- Description: Checks if the serial port is currently connected.
- Returns:
true
if connected, otherwisefalse
. - Usage:
if (serial.isConnected()) { println("Port is connected.") }
- Description: Closes the serial port connection.
- Usage:
serial.close()
Here's a complete example demonstrating how to set up and use the KSerial
library to send and receive data:
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.launch
fun main() = runBlocking {
// Create a KSerial instance with desired configuration
val serial = KSerial.builder("COM3") { message -> println("Log: $message") }
.baudRate(9600)
.dataBits(8)
.stopBits(1)
.parity(SerialPort.PARITY_NONE)
.enableAutoReconnect()
.maxFailureCount(5)
.build()
// Start the serial connection
serial.start()
// Sending data as a string
serial.write("Hello Device!")
// Reading response from the device
val response = serial.readString()
println("Received: $response")
// Sending data as hex
serial.write(byteArrayOf(0x01, 0x02, 0x03))
// Closing the serial connection
serial.close()
}
In this example, the program configures a serial connection to "COM3"
, sends a string message to a connected device, reads the response, and also sends a byte array in hexadecimal format. The connection will automatically attempt to reconnect if disconnected.
We welcome contributions to improve KSerial! Here's how you can help:
- Fork and Clone: Fork the repo and create a new branch for your feature or bug fix.
- Write Tests: Ensure changes are backed by unit tests, and existing tests are passing.
- Create a Pull Request: Submit your changes for review, with details on the improvements made.
For large contributions, please open an issue for discussion.
With this setup, developers gain powerful, reliable serial communication, making KSerial a perfect fit for real-time embedded systems, IoT applications, and beyond.