Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

29 Commits

Folders and files

Repository files navigation

com-port-api

A C library for reading from Windows COM ports using overlapped I/O and event-driven waiting. Provides two usage models: direct COM port access (comport) for single-consumer programs, and a shared daemon (comstream) for multiple local applications that need the same stream.

WARNING: Work in Progress - Actively being developed. Expect incomplete features and breaking changes.

About

com-port-api wraps the Windows serial port API so that a C program can read from a COM port reliably without busy-waiting.

It ships two libraries:

  • libcomport.a - direct COM port access. Your program opens the port, reads bytes, done. Simple, no daemon. Use this if only one program needs the port at a time.
  • libcomstream.a - client for a shared daemon. Your program connects to comstreamd.exe over a named pipe. Use this if multiple programs need the same data simultaneously.

Internally both use:

  • Overlapped (async) I/O with an event handle. No polling, ~0% idle CPU.
  • WaitCommEvent / EV_RXCHAR so reads only fire when data actually arrives.
  • ClearCommError recovery for line errors (overrun, framing, parity).

The comstream daemon also uses:

  • A 1 MB ring buffer so a slow client can fall behind without stalling the serial reader (oldest bytes are overwritten).
  • Named pipes (\\.\pipe\comstream) for local multi-client fan-out.

Which Library Do I Want?

If your program... Use
Is the only thing reading the COM port comport
Wants simple, direct access with no extra process comport
Runs alongside other programs that need the same data comstream
Wants to survive when no consumer is attached comstream

You can use both in the same repo. They share the same underlying serial code (serial.c).

Status

  • Overlapped I/O driven by EV_RXCHAR
  • Ring buffer module with per-client cursors
  • Daemon that reads a COM port and serves a named pipe
  • Client library (libcomstream.a) for the daemon
  • Direct-access library (libcomport.a)
  • Clean shutdown on Ctrl+C
  • Multi-client fan-out
  • Slow-client detection / drop policy
  • Serial reconnect logic

Project Structure

com-port-api
├── inc/
│   ├── comport.h       # Direct COM port API (libcomport)
│   ├── serial.h        # Internal serial port API
│   ├── comstream.h     # Daemon client API (libcomstream)
│   └── ringbuf.h       # Ring buffer API
├── src/
│   ├── comport.c       # comport implementation
│   ├── comport_example.c  # demo consumer using libcomport
│   ├── serial.c        # serial port implementation
│   ├── main.c          # readcom.exe  - standalone serial reader
│   ├── comstream.c     # comstream implementation
│   ├── example_consumer.c  # demo consumer using libcomstream
│   ├── ringbuf.c       # ring buffer implementation
│   ├── daemon.c        # comstreamd.exe - COM to pipe server
│   ├── client.c        # client.exe    - pipe to stdout
│   └── ringtest.c      # ringtest.exe  - ring buffer tests
├── Makefile
├── libcomport.a        # Direct-access library
├── libcomstream.a      # Daemon client library
├── readcom.exe         # Standalone serial reader
├── comstreamd.exe      # Daemon (COM to pipe)
├── client.exe          # Named-pipe client
├── example.exe         # comstream demo
├── comport_example.exe # comport demo
├── ringtest.exe        # Ring buffer tests
└── README.md

Getting Started

Requirements

  • A C compiler (GCC/MinGW recommended on Windows, tested with w64devkit)
  • make
  • Windows (uses windows.h, WaitCommEvent, CreateNamedPipe, etc.)

Build

make

This produces both libraries and the demo executables.

Usage - Direct COM Port (comport)

This is the recommended path if your program is the only consumer.

Minimal example

#include "comport.h"
#include <stdio.h>

int main(void) {
    comport_t *c = comport_open("COM3", 115200);
    if (!c) return 1;

    unsigned char buf[256];
    while (1) {
        int n = comport_read(c, buf, sizeof(buf), 1000);
        if (n < 0) break;       /* port lost */
        if (n == 0) continue;   /* timeout */

        /* do something with buf[0..n-1] */
        fwrite(buf, 1, n, stdout);
    }

    comport_close(c);
    return 0;
}

The API

comport_t *comport_open(const char *port, unsigned baud);
int        comport_read(comport_t *c, void *buf, size_t len, unsigned timeout_ms);
int        comport_write(comport_t *c, const void *buf, size_t len);
void       comport_close(comport_t *c);
const char *comport_name(const comport_t *c);

comport_read returns:

  • > 0 bytes copied
  • 0 timeout, no data
  • < 0 port lost or unrecoverable error

Pass COMPORT_WAIT_INFINITE as the timeout to block until data arrives.

Linking from another project

gcc -I D:\VS_Code\com-port-api\inc my-app.c ^
    D:\VS_Code\com-port-api\libcomport.a -lkernel32 -o my-app.exe

Or in a Makefile:

CFLAGS  += -I D:/VS_Code/com-port-api/inc
LDFLAGS += D:/VS_Code/com-port-api/libcomport.a

Constraint

While your program holds the port open, no other program can open it. Windows serial ports are exclusive. If you need shared access, use comstream instead.

Usage - Shared Daemon (comstream)

If multiple programs need the same stream, run comstreamd.exe and have each consumer use libcomstream.a.

Terminal 1 - start the daemon

./comstreamd.exe COM3 115200

You should see:

[daemon] serial open on COM3 @ 115200
[daemon] waiting for client...

Terminal 2 - connect a consumer

#include "comstream.h"
#include <stdio.h>

int main(void) {
    comstream_t *cs = comstream_open(COMSTREAM_DEFAULT_PIPE, 5000);
    if (!cs) return 1;

    unsigned char buf[256];
    while (1) {
        int n = comstream_read(cs, buf, sizeof(buf), 1000);
        if (n < 0) break;
        if (n == 0) continue;
        fwrite(buf, 1, n, stdout);
    }

    comstream_close(cs);
    return 0;
}

Start as many consumers as you want. They all receive the same stream.

The API

comstream_t *comstream_open(const char *pipe_name, unsigned wait_ms);
int          comstream_read(comstream_t *cs, void *buf, size_t len, unsigned timeout_ms);
void         comstream_close(comstream_t *cs);
const char  *comstream_pipe_name(const comstream_t *cs);

comstream_read returns the same values as comport_read. Pass COMSTREAM_WAIT_INFINITE to block forever.

Full Example - Real-time Visualizer

This is the intended use case for comport: a program that opens a COM port, reads incoming data, and renders it live. The pattern below is what a plotting or dashboard app looks like.

/* visualizer.c - reads COM port and feeds a render loop */
#include "comport.h"

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define FRAME_SIZE   8        /* bytes per sample, adjust to your protocol */
#define MAX_SAMPLES  1024     /* ring of samples waiting to be drawn */

typedef struct {
    unsigned char bytes[FRAME_SIZE];
} sample_t;

static volatile LONG g_running = 1;
static BOOL WINAPI on_ctrl(DWORD type) {
    (void)type;
    InterlockedExchange(&g_running, 0);
    return TRUE;
}

/* In a real program this would be your plot / GUI / whatever.
 * For this example we just print the newest sample. */
static void render_sample(const sample_t *s) {
    printf("sample:");
    for (int i = 0; i < FRAME_SIZE; i++) printf(" %02X", s->bytes[i]);
    printf("\n");
}

int main(int argc, char **argv) {
    const char *port = (argc > 1) ? argv[1] : "COM3";
    unsigned    baud = (argc > 2) ? (unsigned)strtoul(argv[2], NULL, 10) : 115200;

    SetConsoleCtrlHandler(on_ctrl, TRUE);

    comport_t *c = comport_open(port, baud);
    if (!c) {
        fprintf(stderr, "Could not open %s\n", port);
        return 1;
    }
    printf("Opened %s at %u baud. Ctrl+C to quit.\n", comport_name(c), baud);

    unsigned char raw[512];
    unsigned char partial[FRAME_SIZE];
    size_t        partial_len = 0;
    unsigned long total_frames = 0;

    while (InterlockedCompareExchange(&g_running, 1, 1)) {
        int n = comport_read(c, raw, sizeof(raw), 1000);
        if (n < 0) {
            fprintf(stderr, "Port lost.\n");
            break;
        }
        if (n == 0) continue;

        /* Reassemble frames: append bytes to the partial buffer, and
         * whenever we have FRAME_SIZE bytes, emit a sample. */
        for (int i = 0; i < n; i++) {
            partial[partial_len++] = raw[i];

            if (partial_len == FRAME_SIZE) {
                sample_t s;
                memcpy(s.bytes, partial, FRAME_SIZE);
                partial_len = 0;

                render_sample(&s);
                total_frames++;
            }
        }
    }

    comport_close(c);
    printf("Done. %lu frames processed.\n", total_frames);
    return 0;
}

What this demonstrates

  • Opening the port directly, no daemon.
  • Timed reads (1000 ms) so the loop stays responsive to Ctrl+C.
  • Byte-stream to frame reassembly - the port gives you bytes, not messages, so the app owns the framing logic.
  • Decoupling: the read loop produces samples; a separate render thread or loop would consume them in a real app. This example does both in one thread for simplicity.
  • Ctrl+C handling so the app exits cleanly even mid-read.

Building the visualizer against libcomport.a

gcc -I D:\VS_Code\com-port-api\inc visualizer.c D:\VS_Code\com-port-api\libcomport.a -lkernel32 -o visualizer.exe

Run:

visualizer.exe COM3 115200

Standalone Diagnostic (readcom.exe)

If you just want to confirm the port is streaming, use the built-in standalone reader:

./readcom.exe COM3 115200

Prints incoming bytes as hex, exits on Ctrl+C. Useful for verifying hardware before wiring the library into a real program.

Ring Buffer Tests (ringtest.exe)

./ringtest.exe

Runs a handful of assertions against ringbuf.c. Safe to run any time.

Quick Pipe Test (comstream only)

If you just want to sanity-check that the daemon's pipe exists, PowerShell can act as a client:

$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "comstream", [System.IO.Pipes.PipeDirection]::In)
$pipe.Connect(2000)
$reader = New-Object System.IO.StreamReader($pipe)
$reader.ReadLine()

Note: PipeDirection lives under System.IO.Pipes, not System.IO.

Design Notes

Why two libraries?

They solve different problems. comport is the simplest possible thing that works for one consumer. comstream exists because Windows COM ports are exclusive, so if two programs need the same bytes, one has to own the port and hand the data to the other.

Why a daemon (for comstream)?

Windows COM ports are exclusive: only one process can hold a given port handle at a time. The daemon owns the port and shares the byte stream via named pipes.

Why a ring buffer (for comstream)?

The serial reader must never block. If it stalls, the driver's RX buffer fills and bytes are lost. A fixed-size ring buffer means the reader can always write (worst case, overwriting the oldest unread data), and each client tracks its own cursor. A slow client falls behind; the reader does not.

Why overlapped I/O plus WaitCommEvent?

Synchronous ReadFile on a COM port either blocks forever (no timeout) or returns immediately with 0 bytes (with MAXDWORD interval timeout), which leads to busy-waiting. Overlapped I/O plus WaitCommEvent(EV_RXCHAR) lets the thread sleep in the kernel until data actually arrives.

[serial] break messages

On some hardware (and especially virtual ports like com0com), the driver reports EV_BREAK frequently, often whenever the peer opens or closes its handle. It is currently surfaced for visibility; a future revision will drop EV_BREAK from the mask since it carries no data-integrity meaning.

Roadmap

  • Slow-client detection and drop policy (comstream)
  • Serial reconnect on cable unplug (both)
  • Configurable parity / stop bits / flow control via CLI flags
  • comport_open_ex for non-8N1 configurations
  • Windows service wrapper for comstreamd.exe
  • Optional framing protocol (length-prefixed messages, timestamps)
  • Test harness (unit and integration)

Contributing

Early-stage personal project. Feel free to open an issue with ideas or questions.

License

TBD

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages