()
| 26 | } |
| 27 | |
| 28 | private dial(): void { |
| 29 | const url = `${this.serverUrl}${this.stationId}`; |
| 30 | console.log(`[OCPP Client] Connecting to ${url}`); |
| 31 | |
| 32 | const ws = new WebSocket(url, ["ocpp1.6"]); |
| 33 | this.ws = ws; |
| 34 | |
| 35 | // force a close if the handshake never completes, so the retry loop kicks in |
| 36 | const handshakeTimer = setTimeout(() => { |
| 37 | if (!this.connected) { |
| 38 | console.log(`[OCPP Client] ${this.stationId} handshake timeout`); |
| 39 | ws.terminate(); |
| 40 | } |
| 41 | }, 5000); |
| 42 | |
| 43 | ws.on("open", () => { |
| 44 | clearTimeout(handshakeTimer); |
| 45 | console.log(`[OCPP Client] Connected as ${this.stationId}`); |
| 46 | this.connected = true; |
| 47 | // boot, then report the connector available, like a real charger would |
| 48 | this.bootNotification() |
| 49 | .then(() => this.statusNotification(1, "Available")) |
| 50 | .catch((error) => console.error(`[OCPP Client] init failed:`, error)); |
| 51 | }); |
| 52 | |
| 53 | ws.on("message", (data: WebSocket.Data) => { |
| 54 | const message = JSON.parse(data.toString()); |
| 55 | this.handleMessage(message); |
| 56 | }); |
| 57 | |
| 58 | ws.on("error", (error) => { |
| 59 | console.error(`[OCPP Client] Error:`, (error as Error).message || error); |
| 60 | }); |
| 61 | |
| 62 | ws.on("close", () => { |
| 63 | clearTimeout(handshakeTimer); |
| 64 | this.connected = false; |
| 65 | if (this.ws === ws) this.ws = null; |
| 66 | if (this.shouldReconnect) { |
| 67 | console.log( |
| 68 | `[OCPP Client] ${this.stationId} disconnected, retrying in ${RECONNECT_DELAY}ms` |
| 69 | ); |
| 70 | this.reconnectTimer = setTimeout(() => this.dial(), RECONNECT_DELAY); |
| 71 | } |
| 72 | }); |
| 73 | } |
| 74 | |
| 75 | private handleMessage(message: any[]) { |
| 76 | const messageType = message[0]; |
no test coverage detected