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