Skip to content

Commit f370612

Browse files
authored
Use singleton pattern in the Modbus client factory (#909)
feat(binding-modbus): use a singleton client for modbus ops
1 parent 3acb1aa commit f370612

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

packages/binding-modbus/src/modbus-client-factory.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,38 @@
1212
*
1313
* SPDX-License-Identifier: EPL-2.0 OR W3C-20150513
1414
********************************************************************************/
15-
import { ProtocolClientFactory, ProtocolClient, createDebugLogger } from "@node-wot/core";
15+
import { ProtocolClientFactory, ProtocolClient, createDebugLogger, createWarnLogger } from "@node-wot/core";
1616
import ModbusClient from "./modbus-client";
1717

1818
const debug = createDebugLogger("binding-modbus", "modbus-client-factory");
19+
const warn = createWarnLogger("binding-modbus", "modbus-client-factory");
1920

2021
export default class ModbusClientFactory implements ProtocolClientFactory {
2122
public readonly scheme: string = "modbus+tcp";
23+
private singleton: ModbusClient;
2224

2325
public getClient(): ProtocolClient {
24-
debug(`Creating client for '${this.scheme}'`);
25-
return new ModbusClient();
26+
debug(`Get client for '${this.scheme}'`);
27+
this.init();
28+
return this.singleton;
2629
}
2730

28-
public init = (): boolean => true;
29-
public destroy = (): boolean => true;
31+
public init(): boolean {
32+
if (!this.singleton) {
33+
debug(`Initializing client for '${this.scheme}'`);
34+
this.singleton = new ModbusClient();
35+
}
36+
return true;
37+
}
38+
39+
public destroy(): boolean {
40+
debug(`Destroying client for '${this.scheme}'`);
41+
if (!this.singleton) {
42+
warn(`Destroying a not initialized client factory for '${this.scheme}'`);
43+
return true; // do not cause an error
44+
}
45+
this.singleton.stop();
46+
this.singleton = undefined;
47+
return true;
48+
}
3049
}

0 commit comments

Comments
 (0)