Skip to content

Refactor modbus.ts: Design Problems and Redesign Proposal #47

@takker99

Description

@takker99

Current Problems

  • Single file, multiple responsibilities: CRC/LRC calculation, function code definitions, parsing, frame validation, and I/O (serial communication) are all mixed together.
  • Unnecessary ModbusClient class: Logic that should not hold state is implemented as a class. Modbus RTU/ASCII/TCP communication is essentially stateless RPC, so class-based design is not justified.
  • Lack of responsibility separation: Frame building/parsing, business operations, and Transport (I/O) abstraction are not separated.
  • Poor extensibility: Adding new function codes requires editing large conditional blocks, violating the Open/Closed Principle.
  • No unified error model: Exception responses, CRC/LRC errors, timeouts, etc. are not handled consistently.
  • Poor testability: Many routines are not pure functions, making unit tests difficult.
  • Type safety issues: Magic numbers for payload/offsets make intent unclear.

Design Principles

  • Functional Core + Imperative Shell
    • All computation (CRC/LRC/frame building/parsing/data conversion) as pure functions.
    • I/O, retries, timeouts, request serialization managed at the Transport abstraction layer.
  • Modularization Plan
    • functionCodes.ts, types.ts, crc.ts, lrc.ts, frameBuilder.ts, frameParser.ts, handlers/*, transport.ts, rtuTransport.ts, asciiTransport.ts, errors.ts, scheduler.ts
  • Transport Abstraction
    • Design IModbusTransport interface assuming Web Stream API, EventTarget, TypedArray, MessagePort, Disposable exist.
    • Support for RTU/ASCII/TCP interchangeably.
  • Error Handling
    • Use Rust-style errors: recoverable errors via Result, fatal errors via exceptions.
  • Classless (Option A)
    • Pure function API (e.g., readHoldingRegisters(transport, unitId, start, quantity, opts)).
    • State management only in Transport layer.
  • Extensibility
    • Handlers for each function code split into separate files for easy addition.
  • Testing Strategy
    • Unit tests for CRC, frame building/parsing, each handler.
    • Integration tests with mock Transport implementation.

Support Targets

  • Support both RTU and ASCII (add ASCII if incomplete)
  • Run on any Web standard environment (web, Deno, Node, Bun, Cloudflare Worker)

Detailed design and migration plan will be split into separate issues/PRs.

Sub-issues

Metadata

Metadata

Labels

No labels
No labels

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions