| 1 | import { RequestCommand } from '../types/ocpp/Requests'; |
| 2 | import { |
| 3 | StartTransactionRequest, |
| 4 | StartTransactionResponse, |
| 5 | StopTransactionReason, |
| 6 | StopTransactionRequest, |
| 7 | StopTransactionResponse, |
| 8 | } from '../types/ocpp/Transaction'; |
| 9 | import { |
| 10 | BroadcastChannelProcedureName, |
| 11 | BroadcastChannelRequest, |
| 12 | } from '../types/WorkerBroadcastChannel'; |
| 13 | import ChargingStation from './ChargingStation'; |
| 14 | import WorkerBroadcastChannel from './WorkerBroadcastChannel'; |
| 15 | |
| 16 | type MessageEvent = { data: unknown }; |
| 17 | |
| 18 | export default class ChargingStationWorkerBroadcastChannel extends WorkerBroadcastChannel { |
| 19 | private readonly chargingStation: ChargingStation; |
| 20 | |
| 21 | constructor(chargingStation: ChargingStation) { |
| 22 | super(); |
| 23 | this.chargingStation = chargingStation; |
| 24 | this.onmessage = this.handleRequest.bind(this) as (message: MessageEvent) => void; |
| 25 | } |
| 26 | |
| 27 | private async handleRequest(messageEvent: MessageEvent): Promise<void> { |
| 28 | const [, command, payload] = messageEvent.data as BroadcastChannelRequest; |
| 29 | |
| 30 | if (payload.hashId !== this.chargingStation.hashId) { |
| 31 | return; |
| 32 | } |
| 33 | |
| 34 | // TODO: return a response stating the command success or failure |
| 35 | switch (command) { |
| 36 | case BroadcastChannelProcedureName.START_TRANSACTION: |
| 37 | await this.chargingStation.ocppRequestService.requestHandler< |
| 38 | StartTransactionRequest, |
| 39 | StartTransactionResponse |
| 40 | >(this.chargingStation, RequestCommand.START_TRANSACTION, { |
| 41 | connectorId: payload.connectorId, |
| 42 | idTag: payload.idTag, |
| 43 | }); |
| 44 | break; |
| 45 | case BroadcastChannelProcedureName.STOP_TRANSACTION: |
| 46 | await this.chargingStation.ocppRequestService.requestHandler< |
| 47 | StopTransactionRequest, |
| 48 | StopTransactionResponse |
| 49 | >(this.chargingStation, RequestCommand.STOP_TRANSACTION, { |
| 50 | transactionId: payload.transactionId, |
| 51 | meterStop: this.chargingStation.getEnergyActiveImportRegisterByTransactionId( |
| 52 | payload.transactionId |
| 53 | ), |
| 54 | idTag: this.chargingStation.getTransactionIdTag(payload.transactionId), |
| 55 | reason: StopTransactionReason.NONE, |
| 56 | }); |
| 57 | break; |
| 58 | case BroadcastChannelProcedureName.START_CHARGING_STATION: |
| 59 | this.chargingStation.start(); |
| 60 | break; |
| 61 | case BroadcastChannelProcedureName.STOP_CHARGING_STATION: |
| 62 | await this.chargingStation.stop(); |
| 63 | break; |
| 64 | } |
| 65 | } |
| 66 | } |