Skip to content

Detailed Design: Modularization, Transport Abstraction, and Error Handling for Modbus Refactor #49

@takker99

Description

@takker99

Objective

Define the concrete design for refactoring modbus.ts, focusing on modularization, transport abstraction, error handling, and extensibility. This is a follow-up to the main refactor proposal.

Modularization Plan

  • Split code into functional modules:
    • functionCodes.ts: Defines function code enums/constants.
    • types.ts: Common types (Frame, Request, Response, ErrorKind, etc.).
    • crc.ts, lrc.ts: CRC16/LRC calculation and validation routines.
    • frameBuilder.ts, frameParser.ts: Build and parse Modbus frames (RTU/ASCII/TCP).
    • handlers/: One file per function code (e.g., readBits.ts, readRegisters.ts) for encode/decode logic.
    • transport.ts: IModbusTransport interface supporting Web Stream API, EventTarget, TypedArray, MessagePort, and Disposable.
    • rtuTransport.ts, asciiTransport.ts: Concrete transport implementations.
    • errors.ts: ModbusError class and error kinds.
    • scheduler.ts: Request queue for serialization (RTU).
    • index.ts: Public API surface.

Transport Abstraction

  • Define IModbusTransport interface for reading/writing frames:
    • Compatible with web, Deno, Node, Bun, Cloudflare Worker.
    • Methods: write(frame, opts), read(opts), close?().
  • Create RTU, ASCII, and TCP transports that implement this interface.
  • Ensure all frame handling logic is transport-agnostic.

Error Handling

  • Use Rust-like error model:
    • Recoverable errors: Returned as Result<T, ModbusError> (e.g., CRC errors, protocol exceptions, timeouts).
    • Unrecoverable errors: Thrown as exceptions (e.g., logic bugs, invariant violations).
  • Error types:
    • Timeout, CRCMismatch, Protocol, ExceptionResponse (with code), Transport, UnsupportedFunction.
  • Provide error conversions and helpers for UI/reporting.

Extensibility

  • Add new function codes by creating handler files, not by editing large switch/case blocks.
  • Frame building/parsing and business logic separated for RTU/ASCII/TCP.
  • Support new transports by implementing IModbusTransport.

Testing Strategy

  • Unit tests for pure functions (CRC/LRC, frame build/parse, handlers).
  • Integration tests with mock transport for end-to-end flows.
  • Fuzz/edge tests for frame parser with random/broken inputs.

Deliverables

  • Initial module skeletons and interfaces
  • Reference implementation for one RTU and one ASCII handler
  • Test cases for CRC, frame parsing, and transport abstraction
  • Documentation for API and error types

See the main refactor issue for context. Migration steps and code migration tasks will be tracked in a separate issue.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions