modbus-connect
Version:
Modbus RTU over Web Serial and Node.js SerialPort
61 lines (56 loc) • 2.48 kB
JavaScript
// transport/factory.js
// @ts-nocheck
const logger = require('../logger.js');
/**
* Creates a new transport instance for the given type and options.
*
* @param {string} type - The type of transport to create. Supported types are:
* - `'node'`: For Node.js environment, uses serialport under the hood.
* - `'node-tcp'`: For Node.js environment, uses net under the hood.
* - `'web'`: For web environment, uses Web Serial API under the hood.
* - `'web-tcp'`: For web environment, uses Web Sockets under the hood.
* @param {object} [options] - Additional options for the transport.
* - For `'node'` transport, options are passed to the `SerialPort` constructor.
* - For `'node-tcp'` transport, options are passed to the `net.Socket` constructor.
* - For `'web'` transport, options are passed to the `WebSerialTransport` constructor.
* - For `'web-tcp'` transport, options are passed to the `WebTcpSerialTransport` constructor.
* @returns {Promise<Transport>} The transport instance.
* @throws {Error} If the type is unknown or unsupported, or if the options are invalid.
*/
async function createTransport(type, options = {}) {
logger.setTransportType(type);
try {
switch (type) {
// Creating a Transport for the Node.js Environment
case 'node': {
const path = options.port || options.path;
if (!path) {
throw new Error('Missing "port" (or "path") option for node transport');
}
const { NodeSerialTransport } = require('./node-transports/node-serialport.js');
const rest = { ...options };
delete rest.port;
delete rest.path;
return new NodeSerialTransport(path, rest);
}
// Creating a Transport for the Web Environment
case 'web': {
if (!options.port) {
throw new Error('Missing "port" option for web transport');
}
const { WebSerialTransport } = require('./web-transports/web-serialport.js');
const portInstance = options.port;
const rest = { ...options };
delete rest.port;
return new WebSerialTransport(portInstance, rest);
}
// Unknown or unsupported type
default:
throw new Error(`Unknown transport type: ${type}`);
}
} catch (err) {
logger.error(`Failed to create transport of type "${type}": ${err.message}`);
throw err;
}
}
module.exports = { createTransport }