Fix timestamping at OCPP firmware update command handling
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
1 import { BroadcastChannel } from 'worker_threads';
2
3 import type { JsonType } from '../types/JsonType';
4 import type {
5 BroadcastChannelRequest,
6 BroadcastChannelResponse,
7 MessageEvent,
8 } from '../types/WorkerBroadcastChannel';
9 import logger from '../utils/Logger';
10 import Utils from '../utils/Utils';
11
12 const moduleName = 'WorkerBroadcastChannel';
13
14 export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
15 protected constructor() {
16 super('worker');
17 }
18
19 public sendRequest(request: BroadcastChannelRequest): void {
20 this.postMessage(request);
21 }
22
23 protected sendResponse(response: BroadcastChannelResponse): void {
24 this.postMessage(response);
25 }
26
27 protected isRequest(message: JsonType[]): boolean {
28 return Array.isArray(message) === true && message.length === 3;
29 }
30
31 protected isResponse(message: JsonType[]): boolean {
32 return Array.isArray(message) === true && message.length === 2;
33 }
34
35 protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false {
36 if (Array.isArray(messageEvent.data) === false) {
37 logger.error(
38 this.logPrefix(moduleName, 'validateMessageEvent') +
39 ' Worker broadcast channel protocol message event data is not an array'
40 );
41 return false;
42 }
43 if (Utils.validateUUID(messageEvent.data[0]) === false) {
44 logger.error(
45 this.logPrefix(moduleName, 'validateMessageEvent') +
46 ' Worker broadcast channel protocol message event data UUID field is invalid'
47 );
48 return false;
49 }
50 return messageEvent;
51 }
52
53 private logPrefix(modName: string, methodName: string): string {
54 return Utils.logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`);
55 }
56 }