motion-master-client 0.0.21 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (126) hide show
  1. package/.babelrc +3 -0
  2. package/.eslintrc.json +18 -0
  3. package/jest.config.ts +16 -0
  4. package/motion-master.proto +1822 -0
  5. package/package.json +2 -17
  6. package/project.json +45 -0
  7. package/src/lib/cia402.spec.ts +77 -0
  8. package/src/lib/cia402.ts +414 -0
  9. package/src/lib/config-file.spec.ts +114 -0
  10. package/src/lib/config-file.ts +63 -0
  11. package/src/lib/device-log-line.ts +5 -0
  12. package/src/lib/device-parameter.spec.ts +85 -0
  13. package/src/lib/device-parameter.ts +79 -0
  14. package/src/lib/device.ts +10 -0
  15. package/src/lib/hardware-description.spec.ts +253 -0
  16. package/src/lib/hardware-description.ts +129 -0
  17. package/src/lib/logger.ts +5 -0
  18. package/src/lib/monitoring-config.ts +6 -0
  19. package/src/lib/{monitoring-entry.d.ts → monitoring-entry.ts} +5 -4
  20. package/src/lib/motion-master-client.ts +221 -0
  21. package/src/lib/motion-master-pub-sub-client.ts +95 -0
  22. package/src/lib/motion-master-pub-sub-socket.ts +40 -0
  23. package/src/lib/motion-master-pub-sub-web-socket.ts +78 -0
  24. package/src/lib/motion-master-pub-sub-worker-socket.ts +51 -0
  25. package/src/lib/motion-master-req-res-client.spec.ts +740 -0
  26. package/src/lib/motion-master-req-res-client.ts +2120 -0
  27. package/src/lib/motion-master-req-res-socket.ts +62 -0
  28. package/src/lib/motion-master-req-res-web-socket.ts +124 -0
  29. package/src/lib/motion-master-req-res-worker-socket.ts +87 -0
  30. package/src/lib/motion-master.proto.js +2 -2
  31. package/src/lib/operators.ts +90 -0
  32. package/src/lib/options.ts +12 -0
  33. package/src/lib/parameter.spec.ts +160 -0
  34. package/src/lib/parameter.ts +170 -0
  35. package/src/lib/product-id-range.ts +8 -0
  36. package/src/lib/request-status-resolver.ts +403 -0
  37. package/src/lib/system-log-line.ts +9 -0
  38. package/src/lib/{types.d.ts → types.ts} +74 -143
  39. package/src/lib/urls.ts +6 -0
  40. package/src/lib/util.ts +305 -0
  41. package/tsconfig.json +23 -0
  42. package/tsconfig.lib.json +10 -0
  43. package/tsconfig.spec.json +20 -0
  44. package/typedoc.json +10 -0
  45. package/src/index.js +0 -29
  46. package/src/index.js.map +0 -1
  47. package/src/lib/cia402.d.ts +0 -182
  48. package/src/lib/cia402.js +0 -392
  49. package/src/lib/cia402.js.map +0 -1
  50. package/src/lib/config-file.d.ts +0 -13
  51. package/src/lib/config-file.js +0 -50
  52. package/src/lib/config-file.js.map +0 -1
  53. package/src/lib/device-log-line.d.ts +0 -5
  54. package/src/lib/device-log-line.js +0 -3
  55. package/src/lib/device-log-line.js.map +0 -1
  56. package/src/lib/device-parameter.d.ts +0 -56
  57. package/src/lib/device-parameter.js +0 -39
  58. package/src/lib/device-parameter.js.map +0 -1
  59. package/src/lib/device.d.ts +0 -9
  60. package/src/lib/device.js +0 -3
  61. package/src/lib/device.js.map +0 -1
  62. package/src/lib/hardware-description.d.ts +0 -41
  63. package/src/lib/hardware-description.js +0 -94
  64. package/src/lib/hardware-description.js.map +0 -1
  65. package/src/lib/logger.d.ts +0 -1
  66. package/src/lib/logger.js +0 -8
  67. package/src/lib/logger.js.map +0 -1
  68. package/src/lib/monitoring-config.d.ts +0 -6
  69. package/src/lib/monitoring-config.js +0 -3
  70. package/src/lib/monitoring-config.js.map +0 -1
  71. package/src/lib/monitoring-entry.js +0 -3
  72. package/src/lib/monitoring-entry.js.map +0 -1
  73. package/src/lib/motion-master-client.d.ts +0 -52
  74. package/src/lib/motion-master-client.js +0 -151
  75. package/src/lib/motion-master-client.js.map +0 -1
  76. package/src/lib/motion-master-pub-sub-client.d.ts +0 -16
  77. package/src/lib/motion-master-pub-sub-client.js +0 -68
  78. package/src/lib/motion-master-pub-sub-client.js.map +0 -1
  79. package/src/lib/motion-master-pub-sub-socket.d.ts +0 -34
  80. package/src/lib/motion-master-pub-sub-socket.js +0 -3
  81. package/src/lib/motion-master-pub-sub-socket.js.map +0 -1
  82. package/src/lib/motion-master-pub-sub-web-socket.d.ts +0 -14
  83. package/src/lib/motion-master-pub-sub-web-socket.js +0 -67
  84. package/src/lib/motion-master-pub-sub-web-socket.js.map +0 -1
  85. package/src/lib/motion-master-pub-sub-worker-socket.d.ts +0 -14
  86. package/src/lib/motion-master-pub-sub-worker-socket.js +0 -42
  87. package/src/lib/motion-master-pub-sub-worker-socket.js.map +0 -1
  88. package/src/lib/motion-master-req-res-client.d.ts +0 -920
  89. package/src/lib/motion-master-req-res-client.js +0 -1680
  90. package/src/lib/motion-master-req-res-client.js.map +0 -1
  91. package/src/lib/motion-master-req-res-socket.d.ts +0 -52
  92. package/src/lib/motion-master-req-res-socket.js +0 -3
  93. package/src/lib/motion-master-req-res-socket.js.map +0 -1
  94. package/src/lib/motion-master-req-res-web-socket.d.ts +0 -24
  95. package/src/lib/motion-master-req-res-web-socket.js +0 -99
  96. package/src/lib/motion-master-req-res-web-socket.js.map +0 -1
  97. package/src/lib/motion-master-req-res-worker-socket.d.ts +0 -20
  98. package/src/lib/motion-master-req-res-worker-socket.js +0 -69
  99. package/src/lib/motion-master-req-res-worker-socket.js.map +0 -1
  100. package/src/lib/operators.d.ts +0 -18
  101. package/src/lib/operators.js +0 -76
  102. package/src/lib/operators.js.map +0 -1
  103. package/src/lib/options.d.ts +0 -10
  104. package/src/lib/options.js +0 -14
  105. package/src/lib/options.js.map +0 -1
  106. package/src/lib/parameter.d.ts +0 -72
  107. package/src/lib/parameter.js +0 -119
  108. package/src/lib/parameter.js.map +0 -1
  109. package/src/lib/product-id-range.d.ts +0 -7
  110. package/src/lib/product-id-range.js +0 -12
  111. package/src/lib/product-id-range.js.map +0 -1
  112. package/src/lib/request-status-resolver.d.ts +0 -4
  113. package/src/lib/request-status-resolver.js +0 -345
  114. package/src/lib/request-status-resolver.js.map +0 -1
  115. package/src/lib/system-log-line.d.ts +0 -9
  116. package/src/lib/system-log-line.js +0 -3
  117. package/src/lib/system-log-line.js.map +0 -1
  118. package/src/lib/types.js +0 -28
  119. package/src/lib/types.js.map +0 -1
  120. package/src/lib/urls.d.ts +0 -3
  121. package/src/lib/urls.js +0 -10
  122. package/src/lib/urls.js.map +0 -1
  123. package/src/lib/util.d.ts +0 -40
  124. package/src/lib/util.js +0 -316
  125. package/src/lib/util.js.map +0 -1
  126. /package/src/{index.d.ts → index.ts} +0 -0
@@ -0,0 +1,221 @@
1
+ import { combineLatest, defer, filter, first, firstValueFrom, map, mergeMap, Observable, timeout } from "rxjs";
2
+ import { v4 } from "uuid";
3
+ import { MonitoringConfig } from "./monitoring-config";
4
+ import { MotionMasterPubSubClient } from "./motion-master-pub-sub-client";
5
+ import { MotionMasterPubSubSocket } from "./motion-master-pub-sub-socket";
6
+ import { MotionMasterPubSubWebSocket } from "./motion-master-pub-sub-web-socket";
7
+ import { MotionMasterReqResClient } from "./motion-master-req-res-client";
8
+ import { MotionMasterReqResSocket } from "./motion-master-req-res-socket";
9
+ import { MotionMasterReqResWebSocket } from "./motion-master-req-res-web-socket";
10
+ import { mapMonitoringParameterValuesStatusMessageToDeviceParameters, mapMonitoringParameterValuesStatusMessageToParameterValues, selectMotionMasterMessageByTopic } from "./operators";
11
+ import { DeviceParameterIds, DeviceRef, MotionMasterMessage, ParameterValueType } from "./types";
12
+ import { Parameter } from "./parameter";
13
+
14
+ export function createMotionMasterClient(hostname: string) {
15
+ const reqResSocket = new MotionMasterReqResWebSocket();
16
+ const pubSubSocket = new MotionMasterPubSubWebSocket();
17
+
18
+ const client = new MotionMasterClient(reqResSocket, pubSubSocket);
19
+
20
+ const clientId = v4();
21
+ reqResSocket.open(`ws://${hostname}:63524?clientId=${clientId}`);
22
+ pubSubSocket.open(`ws://${hostname}:63525?clientId=${clientId}`);
23
+
24
+ return client;
25
+ }
26
+
27
+ export class MotionMasterClient {
28
+
29
+ readonly request: MotionMasterReqResClient;
30
+ readonly monitor: MotionMasterPubSubClient;
31
+
32
+ constructor(
33
+ readonly reqResSocket: MotionMasterReqResSocket,
34
+ readonly pubSubSocket: MotionMasterPubSubSocket,
35
+ ) {
36
+ this.request = new MotionMasterReqResClient(this.reqResSocket);
37
+ this.monitor = new MotionMasterPubSubClient(this.pubSubSocket);
38
+ }
39
+
40
+ /**
41
+ * This observable will emit true when both req/res and pub/sub sockets are opened.
42
+ * If any socket gets closed, this observable will emit false.
43
+ * This is a hot observable that will on subscription emit the last value of sockets opened.
44
+ */
45
+ socketsOpened$ = combineLatest([this.reqResSocket.opened$, this.pubSubSocket.opened$]).pipe(
46
+ map(([reqResSocketOpened, pubSubSocketOpened]) => reqResSocketOpened && pubSubSocketOpened),
47
+ );
48
+
49
+ /**
50
+ * Client is ready when both req/res and pub/sub sockets are opened.
51
+ * This observable will emit whenever the sockets opened property changes to true.
52
+ */
53
+ ready$ = this.socketsOpened$.pipe(
54
+ filter(Boolean),
55
+ );
56
+
57
+ /**
58
+ * This observable will emit only once when both req/res and pub/sub sockets are opened.
59
+ * NOTE: This observable might never emit and it doesn't timeout.
60
+ */
61
+ onceReady$ = this.ready$.pipe(
62
+ first(),
63
+ );
64
+
65
+ /**
66
+ * Client is ready when both req/res and pub/sub sockets are opened.
67
+ * If both sockets are already opened, this function will immediately resolve to true.
68
+ * Otherwise, it will wait up to requestTimeout for both sockets to open, or throw an error.
69
+ */
70
+ async whenReady(requestTimeout = 5000) {
71
+ return firstValueFrom(
72
+ this.ready$.pipe(
73
+ timeout(requestTimeout),
74
+ ),
75
+ );
76
+ }
77
+
78
+ startMonitoring(
79
+ ids: DeviceParameterIds,
80
+ interval: number,
81
+ config?: MonitoringConfig,
82
+ requestTimeout = 5000,
83
+ ): Observable<ParameterValueType[]> {
84
+ return defer(() => {
85
+ const topic = config?.topic ?? v4();
86
+ const messageId = config?.messageId ?? v4();
87
+
88
+ if (!config) {
89
+ config = { messageId, topic, bufferSize: 1, distinct: false };
90
+ }
91
+
92
+ this.request.resolveGetParameterValuesIds(ids).pipe(
93
+ mergeMap((refs) => {
94
+ if ((new Set(refs.map(([deviceAddress]) => deviceAddress))).size !== 1) {
95
+ throw new Error('Start monitoring only supports a single device');
96
+ }
97
+
98
+ const deviceAddress = refs[0][0];
99
+
100
+ const props: MotionMasterMessage.Request.IStartMonitoringDeviceParameterValues = {
101
+ getDeviceParameterValues: {
102
+ deviceAddress,
103
+ parameters: refs.map(([, index, subindex]) => ({ index, subindex, loadFromCache: false })),
104
+ sendProgress: false,
105
+ },
106
+ interval,
107
+ topic,
108
+ };
109
+
110
+ return this.request.startMonitoringDeviceParameterValues(props, requestTimeout, messageId);
111
+ }),
112
+ ).subscribe();
113
+
114
+ this.monitor.subscribe(config);
115
+
116
+ const values$ = this.monitor.socket.data$.pipe(
117
+ selectMotionMasterMessageByTopic(config.topic),
118
+ mapMonitoringParameterValuesStatusMessageToParameterValues(),
119
+ map((values) => values.slice(1)), // remove fixed timestamp prepended by Motion Master
120
+ );
121
+
122
+ return new Observable<ParameterValueType[]>((subscriber) => {
123
+ const subscription = values$.subscribe(subscriber);
124
+ return () => {
125
+ subscription.unsubscribe();
126
+ this.stopMonitoring(messageId);
127
+ };
128
+ });
129
+ });
130
+ }
131
+
132
+ /**
133
+ * TODO: return device parameters instead of just parameters
134
+ * get parameters from ESI uprfront, and then when parameters are received
135
+ * from motion master just concatenate (spread operator) props from ESI and props from parameter
136
+ * assign device parameter id like 0x1018:00.12345
137
+ * when assembling device parameter, get parameter from device in ESI based on product code, see ESI service
138
+ * this should probably done for other get parameters functions, get ESI file from device or prepared, get data from it
139
+ */
140
+ startMonitoringDeviceParameters(
141
+ ids: DeviceParameterIds,
142
+ interval: number,
143
+ config?: MonitoringConfig,
144
+ requestTimeout = 5000,
145
+ ): Observable<Parameter[]> {
146
+ return defer(() => {
147
+ const topic = config?.topic ?? v4();
148
+ const messageId = config?.messageId ?? v4();
149
+
150
+ if (!config) {
151
+ config = { messageId, topic, bufferSize: 1, distinct: false };
152
+ }
153
+
154
+ this.request.resolveGetParameterValuesIds(ids).pipe(
155
+ mergeMap((refs) => {
156
+ if ((new Set(refs.map(([deviceAddress]) => deviceAddress))).size !== 1) {
157
+ throw new Error('Start monitoring only supports a single device');
158
+ }
159
+
160
+ const deviceAddress = refs[0][0];
161
+
162
+ const props: MotionMasterMessage.Request.IStartMonitoringDeviceParameterValues = {
163
+ getDeviceParameterValues: {
164
+ deviceAddress,
165
+ parameters: refs.map(([, index, subindex]) => ({ index, subindex, loadFromCache: false })),
166
+ sendProgress: false,
167
+ },
168
+ interval,
169
+ topic,
170
+ };
171
+
172
+ return this.request.startMonitoringDeviceParameterValues(props, requestTimeout, messageId);
173
+ }),
174
+ ).subscribe();
175
+
176
+ this.monitor.subscribe(config);
177
+
178
+ const values$ = this.monitor.socket.data$.pipe(
179
+ selectMotionMasterMessageByTopic(config.topic),
180
+ mapMonitoringParameterValuesStatusMessageToDeviceParameters(),
181
+ map((values) => values.slice(1)), // remove fixed timestamp prepended by Motion Master
182
+ );
183
+
184
+ return new Observable<Parameter[]>((subscriber) => {
185
+ const subscription = values$.subscribe(subscriber);
186
+ return () => {
187
+ subscription.unsubscribe();
188
+ this.stopMonitoring(messageId);
189
+ };
190
+ });
191
+ });
192
+ }
193
+
194
+ startMonitoringValue<T extends ParameterValueType = number>(
195
+ id: string | [DeviceRef, number, number],
196
+ interval: number,
197
+ config?: MonitoringConfig,
198
+ requestTimeout = 5000,
199
+ ): Observable<T> {
200
+ const ids = typeof id === 'string' ? [id] : [id];
201
+ return this.startMonitoring(ids, interval, config, requestTimeout).pipe(
202
+ map((parameters) => (parameters[0] ?? 0) as T),
203
+ );
204
+ }
205
+
206
+ stopMonitoring(messageId: string): void {
207
+ this.request.stopMonitoringDeviceParameterValues({ startMonitoringRequestId: messageId });
208
+ this.monitor.unsubscribe(messageId);
209
+ }
210
+
211
+ closeSockets() {
212
+ this.reqResSocket.close();
213
+ this.pubSubSocket.close();
214
+ }
215
+
216
+ reopenSockets() {
217
+ this.reqResSocket.reopen();
218
+ this.pubSubSocket.reopen();
219
+ }
220
+
221
+ }
@@ -0,0 +1,95 @@
1
+ import { bufferCount, distinctUntilChanged, filter, map, Observable, Subject, Subscription } from "rxjs";
2
+ import { v4 } from "uuid";
3
+ import { MonitoringConfig } from "./monitoring-config";
4
+ import { MotionMasterPubSubSocket } from "./motion-master-pub-sub-socket";
5
+ import { selectMotionMasterMessageByTopic, selectMotionMasterMessageStatusByKey } from "./operators";
6
+ import { IMotionMasterMessage, MotionMasterMessage } from "./types";
7
+ import * as equal from "fast-deep-equal";
8
+ import { MotionMasterPubSubWorkerSocket } from "./motion-master-pub-sub-worker-socket";
9
+
10
+ export class MotionMasterPubSubClient {
11
+
12
+ readonly data$ = new Subject<[string, IMotionMasterMessage[]]>();
13
+
14
+ private subscriptions = new Map<string, Subscription>();
15
+
16
+ readonly notification$ = this.socket.data$.pipe(
17
+ selectMotionMasterMessageByTopic('notification'),
18
+ );
19
+
20
+ readonly systemEvent$ = this.notification$.pipe(
21
+ selectMotionMasterMessageStatusByKey<MotionMasterMessage.Status.ISystemEvent>('systemEvent'),
22
+ );
23
+
24
+ readonly deviceEvent$ = this.notification$.pipe(
25
+ selectMotionMasterMessageStatusByKey<MotionMasterMessage.Status.IDeviceEvent>('deviceEvent'),
26
+ );
27
+
28
+ constructor(
29
+ public readonly socket: MotionMasterPubSubSocket,
30
+ ) { }
31
+
32
+ subscribe(config: MonitoringConfig) {
33
+ if (!config.messageId) {
34
+ config = { ...config, messageId: v4() };
35
+ }
36
+
37
+ if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
38
+ this.socket.worker.postMessage({ subscribe: config });
39
+ } else {
40
+ const { bufferSize = 1, distinct = false, messageId, topic } = config;
41
+
42
+ let observable: Observable<IMotionMasterMessage> = this.socket.data$.pipe(
43
+ filter((data) => data[0] === topic),
44
+ map((data) => data[1]),
45
+ );
46
+
47
+ if (distinct) {
48
+ observable = observable.pipe(
49
+ distinctUntilChanged((prev, curr) => {
50
+ if (prev?.status?.monitoringParameterValues?.deviceParameterValues?.parameterValues
51
+ && curr?.status?.monitoringParameterValues?.deviceParameterValues?.parameterValues) {
52
+ return equal(
53
+ prev.status.monitoringParameterValues.deviceParameterValues.parameterValues,
54
+ curr.status.monitoringParameterValues.deviceParameterValues.parameterValues,
55
+ )
56
+ }
57
+ return false;
58
+ }),
59
+ );
60
+ }
61
+
62
+ const subscription = observable.pipe(
63
+ bufferCount(bufferSize),
64
+ ).subscribe((data) => {
65
+ this.data$.next([topic, data]);
66
+ });
67
+
68
+ this.subscriptions.set(messageId, subscription);
69
+ }
70
+
71
+ return config.messageId;
72
+ }
73
+
74
+ unsubscribe(messageId: string) {
75
+ if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
76
+ this.socket.worker.postMessage({ unsubcribe: { messageId } });
77
+ } else {
78
+ const subscription = this.subscriptions.get(messageId);
79
+ if (subscription) {
80
+ subscription.unsubscribe();
81
+ this.subscriptions.delete(messageId);
82
+ }
83
+ }
84
+ }
85
+
86
+ unsubscribeAll() {
87
+ if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
88
+ this.socket.worker.postMessage({ unsubscribeAll: true });
89
+ } else {
90
+ this.subscriptions.forEach((subscription) => subscription.unsubscribe());
91
+ this.subscriptions.clear();
92
+ }
93
+ }
94
+
95
+ }
@@ -0,0 +1,40 @@
1
+ import { BehaviorSubject, Observable } from "rxjs";
2
+ import { IMotionMasterMessage } from "./types";
3
+
4
+ export interface MotionMasterPubSubSocket {
5
+ /**
6
+ * Emits a boolean value when socket gets opened or closed.
7
+ */
8
+ readonly opened$: BehaviorSubject<boolean>;
9
+
10
+ /**
11
+ * Incoming data is a tuple of topic and decoded message.
12
+ */
13
+ readonly data$: Observable<[string, IMotionMasterMessage]>;
14
+
15
+ /**
16
+ * URL set in call to open.
17
+ */
18
+ get url(): string | undefined;
19
+
20
+ /**
21
+ * Open socket.
22
+ *
23
+ * The connected$ and eventually alive$ observables will emit true values.
24
+ */
25
+ open(url: string): void;
26
+
27
+ /**
28
+ * Reopen socket.
29
+ *
30
+ * Reopen if closed using the same url previously set in open.
31
+ */
32
+ reopen(): void;
33
+
34
+ /**
35
+ * Close socket.
36
+ *
37
+ * The opened$ and alive$ observables will emit false values.
38
+ */
39
+ close(): void;
40
+ }
@@ -0,0 +1,78 @@
1
+ import { BehaviorSubject, Subject } from "rxjs";
2
+ import { webSocket, WebSocketSubject, WebSocketSubjectConfig } from "rxjs/webSocket";
3
+ import { logger } from "./logger";
4
+ import { MotionMasterPubSubSocket } from "./motion-master-pub-sub-socket";
5
+ import { IMotionMasterMessage, MotionMasterMessage } from "./types";
6
+ import { createPlainObjectFromMotionMasterMessage } from "./util";
7
+
8
+ export class MotionMasterPubSubWebSocket implements MotionMasterPubSubSocket {
9
+
10
+ readonly opened$ = new BehaviorSubject<boolean>(false);
11
+
12
+ readonly data$ = new Subject<[string, IMotionMasterMessage]>();
13
+
14
+ private webSocket$?: WebSocketSubject<[string, IMotionMasterMessage]>;
15
+
16
+ private _url?: string;
17
+
18
+ get url(): string | undefined {
19
+ return this._url;
20
+ }
21
+
22
+ open(url: string): void {
23
+ if (this.opened$.getValue() === true) {
24
+ throw new Error('MotionMasterPubSubWebSocket is already opened!');
25
+ }
26
+
27
+ this._url = url;
28
+
29
+ this.webSocket$ = this.createWebSocket(url);
30
+
31
+ this.webSocket$.subscribe({
32
+ next: (value) => this.data$.next(value),
33
+ error: () => {
34
+ // ignore
35
+ },
36
+ });
37
+ }
38
+
39
+ close(): void {
40
+ this.webSocket$?.unsubscribe();
41
+ }
42
+
43
+ reopen() {
44
+ if (this.url && this.opened$.value === false) {
45
+ this.open(this.url);
46
+ }
47
+ }
48
+
49
+ private createWebSocket(url: string) {
50
+ const decoder = new TextDecoder('utf-8');
51
+
52
+ const webSocketConfig: WebSocketSubjectConfig<[string, IMotionMasterMessage]> = {
53
+ binaryType: 'arraybuffer',
54
+ closeObserver: {
55
+ next: () => {
56
+ this.opened$.next(false);
57
+ logger.info(`Connection closed ${url}`);
58
+ },
59
+ },
60
+ deserializer: (e: MessageEvent<ArrayBuffer>): [string, IMotionMasterMessage] => {
61
+ const end = new Uint8Array(e.data, 0, 1)[0] + 1;
62
+ const topic = decoder.decode(e.data.slice(1, end)); // topic starts from the 2nd byte
63
+ const message = MotionMasterMessage.decode(new Uint8Array(e.data.slice(end)));
64
+ return [topic, createPlainObjectFromMotionMasterMessage(message)];
65
+ },
66
+ openObserver: {
67
+ next: () => {
68
+ this.opened$.next(true);
69
+ logger.info(`Connection opened ${url}`);
70
+ },
71
+ },
72
+ url,
73
+ };
74
+
75
+ return webSocket(webSocketConfig);
76
+ }
77
+
78
+ }
@@ -0,0 +1,51 @@
1
+ import { BehaviorSubject, Subject } from "rxjs";
2
+ import { MotionMasterPubSubSocket } from "./motion-master-pub-sub-socket";
3
+ import { IMotionMasterMessage } from "./types";
4
+ import { logger } from "./logger";
5
+
6
+ export class MotionMasterPubSubWorkerSocket implements MotionMasterPubSubSocket {
7
+
8
+ opened$ = new BehaviorSubject(false);
9
+
10
+ data$ = new Subject<[string, IMotionMasterMessage]>();
11
+
12
+ private _url?: string;
13
+
14
+ constructor(
15
+ public readonly worker: Worker,
16
+ ) { }
17
+
18
+ get url(): string | undefined {
19
+ return this._url;
20
+ }
21
+
22
+ open(url: string): void {
23
+ this._url = url;
24
+
25
+ this.worker.onmessage = ({ data }) => {
26
+ if ('opened' in data) {
27
+ const { opened } = data;
28
+ this.opened$.next(opened);
29
+ logger.info(opened ? `Opened pub/sub 🔌 ${url}` : `Closed pub/sub 🔌 ${url}`);
30
+ } else if ('topic' in data) {
31
+ const { topic, messages }: { topic: string, messages: IMotionMasterMessage[] } = data;
32
+ messages.forEach((message) => this.data$.next([topic, message]));
33
+ }
34
+ }
35
+
36
+ this.worker.postMessage({
37
+ open: { url }
38
+ });
39
+ }
40
+
41
+ close(): void {
42
+ this.worker.postMessage({ close: true })
43
+ }
44
+
45
+ reopen() {
46
+ if (this.url && this.opened$.value === false) {
47
+ this.open(this.url);
48
+ }
49
+ }
50
+
51
+ }