-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Description
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:
IModbusTransportinterface 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
IModbusTransportinterface 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).
- Recoverable errors: Returned as
- 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