Halil Umut Yalçın
Clinical IoT & Protocols

Connecting 6 Clinical Analyzers to FastAPI via HL7 and Serial Ports

Sep 24, 2026•5 min read•Halil Umut Yalçın
Connecting 6 Clinical Analyzers to FastAPI via HL7 and Serial Ports

Interfacing blood, urine, ECG, and spirometry instruments with an async FastAPI backend using MLLP streaming, dedicated threadpools, and noise-tolerant serial port readers.

Why Lab Telemetry Fails in Mobile Screening Vans

Medisan operates mobile health screening vans and regional clinics equipped with blood analyzers, urine instruments, spirometers, and audiometers. In industrial factory screenings, while 300 to 500 workers undergo sensory and physical checks per shift, roughly 100 to 150 workers require complete laboratory blood and urine panels. Across these clinical examinations, our instruments record over 2,300 discrete analyte parameters daily (hemogram, renal/liver markers, urinalysis), aggregating to more than 50,000 recorded diagnostic values each month.

Originally, technicians manually transcribed numbers from printed thermal receipts into clinic software. This introduced clerical errors, slowed down worker discharge, and created administrative bottlenecks during high-volume screening shifts.

To eliminate manual entry, we built a Clinical IoT Gateway using FastAPI. It interfaces with 6 diagnostic instruments and 2 external laboratory systems (Reference Lab and Hospital HIS) over RS-232 serial links and TCP/IP sockets. Incoming measurements are parsed, linked to patient barcodes, and dispatched to central databases without blocking the main application.

Automating Lab Telemetry

Direct MLLP and ASTM parsing with Modulo-10 (Luhn) barcode verification replaced paper re-entry. The client scanner verifies check digits at intake, catching 100% of single-digit substitutions and adjacent transpositions (except 09 ↔ 90) before associating results with patient records.

Protocol Inventory: 6 Analyzers and 2 LIMS Adapters

Each device relies on a different communication standard, baud rate, and framing convention:

Supported Lab Instruments and Interface Protocols
Instrument & ModelPhysical InterfaceCommunication ProtocolPayload FormatClinical Parameters
Mindray BC-5000 / BC-3000RS-232 Serial Port (DB9)HL7 v2.3.1 / ASTM E1381MLLP / ASCII Stream23-Parameter Complete Blood Count (WBC, RBC, HGB, PLT, MCV)
Urit-500B Urine AnalyzerRS-232 Serial (9600 baud)Proprietary Hex StreamRaw ASCII Text FramesUrinalysis Panels (GLU, PRO, BIL, URO, PH, BLD, KET, LEU)
Rayto RT-7600 BiochemistryTCP/IP Socket (Ethernet)HL7 v2.5 / XMLMLLP FramingLiver & Renal Panels (AST, ALT, GGT, Urea, Creatinine)
Maico MA-42 AudiometerUSB Virtual COM (FTDI)Bidirectional BinaryHex Frame + Checksum125Hz - 8000Hz Air/Bone Conduction Thresholds (dB)
Cosmed Spiropalm SFTUSB / RS-232 SerialCustom Serial StreamASCII CSV ArraysFlow-Volume Curves (FVC, FEV1, FEV1/FVC, PEF)
Nihon Kohden Cardiofax ECGTCP/IP EthernetDICOM-ECG / SCP-ECG12-Lead Microvolt VectorsP-Q-R-S-T Waveform Coordinates, Rhythm, Heart Rate
Reference Lab LIMS (Cloud)HTTPS (Cloud API)WSDL SOAP v5.0XML EnvelopeReference Lab Specimen Barcodes & Service Orders
Hospital Core HIS / LIMSVPN / TCPSOAP XML / RESTJSON / XMLHospital Inpatient Requisitions & Barcode Mapping

Handling MLLP Framing and Blocking Serial Ports

HL7 v2 messages are wrapped inside Minimal Lower Layer Protocol (MLLP) envelopes: a leading Start Block (0x0B) and a trailing End Block sequence (0x1C 0x0D). Under real clinic network conditions, TCP packets often fragment across message boundaries.

Our receiver accumulates incoming bytes in a sliding bytearray buffer. To prevent false matches caused by noisy transmission lines, it only searches for the closing sequence after a confirmed start block. Once a complete frame is verified, we commit the payload to a durable queue (Celery task with Redis AOF / PostgreSQL WAL persistence) before returning the HL7 ACK and releasing the socket, mitigating data loss risks during sudden power resets.

Serial communication introduced another hurdle: pyserial read operations are synchronous and blocking. Executing blocking read() calls directly on FastAPI's single-threaded asyncio event loop stalls all concurrent HTTP requests and WebSocket connections. We offloaded all physical serial I/O to a dedicated ThreadPoolExecutor, channeling parsed frames into an asyncio.Queue for asynchronous worker ingestion.

gateways/hl7_mllp_parser.py (Noise-Resilient MLLP Parser)python
Expand excerpt
MLLP_START = b"\x0b"
MLLP_END = b"\x1c\x0d"
MAX_BUFFER_SIZE = 65536  # Guard against line noise memory exhaustion

# Extract framed HL7 packet with defensive encoding and runaway buffer guards
def extract_mllp_frame(buffer: bytearray) -> tuple[Optional[str], bytearray]:
    start = buffer.find(MLLP_START)
    if start == -1:
        # Purge buffer if line noise accumulates without a start delimiter
        if len(buffer) > MAX_BUFFER_SIZE:
            buffer.clear()
        return None, buffer

    # Discard any spurious noise bytes that preceded the start block
    if start > 0:
        del buffer[:start]
        start = 0

    end = buffer.find(MLLP_END, start + 1)
    if end == -1:
        # Guard against runaway memory if start block arrived but end block is lost/delayed
        if len(buffer) > MAX_BUFFER_SIZE:
            buffer.clear()
        return None, buffer

    # Extract clean payload. Attempt UTF-8 first; fall back to ISO-8859-9 (Turkish Latin-5)
    # Note: ISO-8859-9 maps all 256 bytes and never raises UnicodeDecodeError, so UTF-8 must be tried first
    raw_payload = bytes(buffer[start + 1:end])
    try:
        frame = raw_payload.decode("utf-8")
    except UnicodeDecodeError:
        frame = raw_payload.decode("iso-8859-9", errors="replace")

    # Slice off processed frame from accumulator
    del buffer[:end + len(MLLP_END)]
    return frame, buffer

Diesel Generators and Noisy USB-Serial Adapters

The most frustrating operational failure occurred in mobile screening vans. When operating off portable diesel generators, minor voltage fluctuations caused standard USB-to-RS232 adapters (often FTDI or Prolific chipsets) to inject spurious bytes or lose frame synchronization mid-transmission.

During a hematology run, the Mindray analyzer would begin an ASTM frame, experience a line voltage dip, and drop the trailing ETX/CRLF sequence. The serial port reader would block indefinitely awaiting the terminator, stalling subsequent measurements.

We resolved this by adding a 50ms inter-character silence timeout on the serial stream. If transmission ceases for longer than 50ms without a terminator, the partial frame is discarded, a NAK is transmitted to prompt the analyzer's automatic retransmit, and the buffer is cleared.

Additionally, a software watchdog was added to reset and reinitialize the virtual COM port whenever three consecutive framing anomalies occur. This self-healing loop eliminated field service visits caused by hung ports.

Field Rules for Hospital Serial Ports

Never run blocking serial I/O on the asyncio event loop. Offload physical reads to a dedicated threadpool worker to preserve HTTP API responsiveness.

Buffer MLLP streams defensively. Hospital switches fragment packets frequently; always verify start and end delimiters sequentially rather than assuming complete packets per read.

Acknowledge the physical device only after committing the parsed payload to a durable queue or write-ahead log (WAL), then execute downstream LIMS synchronization asynchronously without blocking socket I/O.

Engineering Scope & Implementation Retrospective
My Direct Contribution:

Implemented the bidirectional MLLP framing parser with defensive encoding fallbacks (UTF-8 to ISO-8859-9), isolated blocking serial I/O in threadpool executors, and built the 50ms silence timeout and COM port watchdog for mobile screening vans.

Wider Team / Platform Scope:

Clinical lab technicians assisted in capturing physical serial packet dumps from laboratory analyzers. Senior backend colleagues managed the external hospital HIS VPN tunnel and SOAP endpoints.

Measurement Methodology:

Recorded frame processing times using Python time.perf_counter_ns() across synthetic 23-parameter CBC messages and verified with Wireshark packet captures under portable generator load.

What I'd Do Differently Today:

I would standardize on structured protocol buffers or lightweight binary serialization for internal task queues earlier rather than passing raw HL7 strings through intermediate worker stages.

Halil Umut Yalçın

Written by Halil Umut Yalçın

Software Engineer • Building regulated clinical systems, PACS/DICOM workflows, and high-reliability web applications.

Discuss this article or collaborate →
Author & Editorial Disclosure:These technical notes reflect production implementations, postmortems, and architectural decisions by Halil Umut Yalçın at Medisan. Large Language Models (Claude / AI tools) assisted in article structure, editorial drafting, and English phrasing. All code implementations, benchmarks, and clinical validations are verified by the author.