From f370612993f549116e32707dd9e9f47c1991447e Mon Sep 17 00:00:00 2001 From: Cristiano Aguzzi Date: Thu, 19 Jan 2023 14:49:31 +0100 Subject: [PATCH] Use singleton pattern in the Modbus client factory (#909) feat(binding-modbus): use a singleton client for modbus ops --- .../src/modbus-client-factory.ts | 29 +++++++++++++++---- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/binding-modbus/src/modbus-client-factory.ts b/packages/binding-modbus/src/modbus-client-factory.ts index e7f544443..ece956d02 100644 --- a/packages/binding-modbus/src/modbus-client-factory.ts +++ b/packages/binding-modbus/src/modbus-client-factory.ts @@ -12,19 +12,38 @@ * * SPDX-License-Identifier: EPL-2.0 OR W3C-20150513 ********************************************************************************/ -import { ProtocolClientFactory, ProtocolClient, createDebugLogger } from "@node-wot/core"; +import { ProtocolClientFactory, ProtocolClient, createDebugLogger, createWarnLogger } from "@node-wot/core"; import ModbusClient from "./modbus-client"; const debug = createDebugLogger("binding-modbus", "modbus-client-factory"); +const warn = createWarnLogger("binding-modbus", "modbus-client-factory"); export default class ModbusClientFactory implements ProtocolClientFactory { public readonly scheme: string = "modbus+tcp"; + private singleton: ModbusClient; public getClient(): ProtocolClient { - debug(`Creating client for '${this.scheme}'`); - return new ModbusClient(); + debug(`Get client for '${this.scheme}'`); + this.init(); + return this.singleton; } - public init = (): boolean => true; - public destroy = (): boolean => true; + public init(): boolean { + if (!this.singleton) { + debug(`Initializing client for '${this.scheme}'`); + this.singleton = new ModbusClient(); + } + return true; + } + + public destroy(): boolean { + debug(`Destroying client for '${this.scheme}'`); + if (!this.singleton) { + warn(`Destroying a not initialized client factory for '${this.scheme}'`); + return true; // do not cause an error + } + this.singleton.stop(); + this.singleton = undefined; + return true; + } }