Hook the OCPP 2.0 stack into the main code
[e-mobility-charging-stations-simulator.git] / src / charging-station / WorkerBroadcastChannel.ts
CommitLineData
32de5a57
LM
1import { BroadcastChannel } from 'worker_threads';
2
18057587 3import type { JsonType } from '../types/JsonType';
6c1761d4 4import type {
852a4c5f
JB
5 BroadcastChannelRequest,
6 BroadcastChannelResponse,
7 MessageEvent,
8} from '../types/WorkerBroadcastChannel';
5dea4c94
JB
9import logger from '../utils/Logger';
10import Utils from '../utils/Utils';
11
12const moduleName = 'WorkerBroadcastChannel';
4e3ff94d 13
6c8f5d90
JB
14export default abstract class WorkerBroadcastChannel extends BroadcastChannel {
15 protected constructor() {
32de5a57
LM
16 super('worker');
17 }
4e3ff94d
JB
18
19 public sendRequest(request: BroadcastChannelRequest): void {
20 this.postMessage(request);
21 }
02a6943a 22
6c8f5d90 23 protected sendResponse(response: BroadcastChannelResponse): void {
02a6943a
JB
24 this.postMessage(response);
25 }
6c8f5d90 26
18057587 27 protected isRequest(message: JsonType[]): boolean {
5f7e72c1 28 return Array.isArray(message) === true && message.length === 3;
6c8f5d90
JB
29 }
30
18057587 31 protected isResponse(message: JsonType[]): boolean {
5f7e72c1 32 return Array.isArray(message) === true && message.length === 2;
6c8f5d90 33 }
852a4c5f 34
5dea4c94 35 protected validateMessageEvent(messageEvent: MessageEvent): MessageEvent | false {
852a4c5f 36 if (Array.isArray(messageEvent.data) === false) {
5dea4c94
JB
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 }
03eacbe5 43 if (Utils.validateUUID(messageEvent.data[0]) === false) {
5dea4c94
JB
44 logger.error(
45 this.logPrefix(moduleName, 'validateMessageEvent') +
46 ' Worker broadcast channel protocol message event data UUID field is invalid'
47 );
48 return false;
852a4c5f 49 }
5e3cb728 50 return messageEvent;
852a4c5f 51 }
5dea4c94
JB
52
53 private logPrefix(modName: string, methodName: string): string {
54 return Utils.logPrefix(` Worker Broadcast Channel | ${modName}.${methodName}:`);
55 }
32de5a57 56}