|
12 | 12 | * |
13 | 13 | * SPDX-License-Identifier: EPL-2.0 OR W3C-20150513 |
14 | 14 | ********************************************************************************/ |
15 | | -import { ProtocolClientFactory, ProtocolClient, createDebugLogger } from "@node-wot/core"; |
| 15 | +import { ProtocolClientFactory, ProtocolClient, createDebugLogger, createWarnLogger } from "@node-wot/core"; |
16 | 16 | import ModbusClient from "./modbus-client"; |
17 | 17 |
|
18 | 18 | const debug = createDebugLogger("binding-modbus", "modbus-client-factory"); |
| 19 | +const warn = createWarnLogger("binding-modbus", "modbus-client-factory"); |
19 | 20 |
|
20 | 21 | export default class ModbusClientFactory implements ProtocolClientFactory { |
21 | 22 | public readonly scheme: string = "modbus+tcp"; |
| 23 | + private singleton: ModbusClient; |
22 | 24 |
|
23 | 25 | 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; |
26 | 29 | } |
27 | 30 |
|
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 | + } |
30 | 49 | } |
0 commit comments