motion-master-client 0.0.43 → 0.0.44

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 (125) hide show
  1. package/package.json +17 -2
  2. package/src/index.js +29 -0
  3. package/src/index.js.map +1 -0
  4. package/src/lib/cia402.d.ts +182 -0
  5. package/src/lib/cia402.js +392 -0
  6. package/src/lib/cia402.js.map +1 -0
  7. package/src/lib/config-file.d.ts +13 -0
  8. package/src/lib/config-file.js +50 -0
  9. package/src/lib/config-file.js.map +1 -0
  10. package/src/lib/device-log-line.d.ts +5 -0
  11. package/src/lib/device-log-line.js +3 -0
  12. package/src/lib/device-log-line.js.map +1 -0
  13. package/src/lib/device-parameter.d.ts +56 -0
  14. package/src/lib/device-parameter.js +39 -0
  15. package/src/lib/device-parameter.js.map +1 -0
  16. package/src/lib/device.d.ts +9 -0
  17. package/src/lib/device.js +3 -0
  18. package/src/lib/device.js.map +1 -0
  19. package/src/lib/hardware-description.d.ts +41 -0
  20. package/src/lib/hardware-description.js +94 -0
  21. package/src/lib/hardware-description.js.map +1 -0
  22. package/src/lib/logger.d.ts +1 -0
  23. package/src/lib/logger.js +8 -0
  24. package/src/lib/logger.js.map +1 -0
  25. package/src/lib/monitoring-config.d.ts +6 -0
  26. package/src/lib/monitoring-config.js +3 -0
  27. package/src/lib/monitoring-config.js.map +1 -0
  28. package/src/lib/{monitoring-entry.ts → monitoring-entry.d.ts} +4 -5
  29. package/src/lib/monitoring-entry.js +3 -0
  30. package/src/lib/monitoring-entry.js.map +1 -0
  31. package/src/lib/motion-master-client.d.ts +56 -0
  32. package/src/lib/motion-master-client.js +167 -0
  33. package/src/lib/motion-master-client.js.map +1 -0
  34. package/src/lib/motion-master-pub-sub-client.d.ts +17 -0
  35. package/src/lib/motion-master-pub-sub-client.js +73 -0
  36. package/src/lib/motion-master-pub-sub-client.js.map +1 -0
  37. package/src/lib/motion-master-pub-sub-socket.d.ts +34 -0
  38. package/src/lib/motion-master-pub-sub-socket.js +3 -0
  39. package/src/lib/motion-master-pub-sub-socket.js.map +1 -0
  40. package/src/lib/motion-master-pub-sub-web-socket.d.ts +14 -0
  41. package/src/lib/motion-master-pub-sub-web-socket.js +67 -0
  42. package/src/lib/motion-master-pub-sub-web-socket.js.map +1 -0
  43. package/src/lib/motion-master-pub-sub-worker-socket.d.ts +14 -0
  44. package/src/lib/motion-master-pub-sub-worker-socket.js +42 -0
  45. package/src/lib/motion-master-pub-sub-worker-socket.js.map +1 -0
  46. package/src/lib/motion-master-req-res-client.d.ts +947 -0
  47. package/src/lib/motion-master-req-res-client.js +1735 -0
  48. package/src/lib/motion-master-req-res-client.js.map +1 -0
  49. package/src/lib/motion-master-req-res-socket.d.ts +52 -0
  50. package/src/lib/motion-master-req-res-socket.js +3 -0
  51. package/src/lib/motion-master-req-res-socket.js.map +1 -0
  52. package/src/lib/motion-master-req-res-web-socket.d.ts +24 -0
  53. package/src/lib/motion-master-req-res-web-socket.js +99 -0
  54. package/src/lib/motion-master-req-res-web-socket.js.map +1 -0
  55. package/src/lib/motion-master-req-res-worker-socket.d.ts +20 -0
  56. package/src/lib/motion-master-req-res-worker-socket.js +69 -0
  57. package/src/lib/motion-master-req-res-worker-socket.js.map +1 -0
  58. package/src/lib/operators.d.ts +20 -0
  59. package/src/lib/operators.js +85 -0
  60. package/src/lib/operators.js.map +1 -0
  61. package/src/lib/options.d.ts +10 -0
  62. package/src/lib/options.js +14 -0
  63. package/src/lib/options.js.map +1 -0
  64. package/src/lib/parameter.d.ts +72 -0
  65. package/src/lib/parameter.js +119 -0
  66. package/src/lib/parameter.js.map +1 -0
  67. package/src/lib/product-id-range.d.ts +7 -0
  68. package/src/lib/product-id-range.js +12 -0
  69. package/src/lib/product-id-range.js.map +1 -0
  70. package/src/lib/request-status-resolver.d.ts +4 -0
  71. package/src/lib/request-status-resolver.js +345 -0
  72. package/src/lib/request-status-resolver.js.map +1 -0
  73. package/src/lib/system-log-line.d.ts +9 -0
  74. package/src/lib/system-log-line.js +3 -0
  75. package/src/lib/system-log-line.js.map +1 -0
  76. package/src/lib/{types.ts → types.d.ts} +149 -81
  77. package/src/lib/types.js +29 -0
  78. package/src/lib/types.js.map +1 -0
  79. package/src/lib/urls.d.ts +3 -0
  80. package/src/lib/urls.js +10 -0
  81. package/src/lib/urls.js.map +1 -0
  82. package/src/lib/util.d.ts +42 -0
  83. package/src/lib/util.js +326 -0
  84. package/src/lib/util.js.map +1 -0
  85. package/.babelrc +0 -3
  86. package/.eslintrc.json +0 -18
  87. package/jest.config.ts +0 -16
  88. package/motion-master.proto +0 -1822
  89. package/project.json +0 -45
  90. package/src/lib/cia402.spec.ts +0 -77
  91. package/src/lib/cia402.ts +0 -414
  92. package/src/lib/config-file.spec.ts +0 -114
  93. package/src/lib/config-file.ts +0 -63
  94. package/src/lib/device-log-line.ts +0 -5
  95. package/src/lib/device-parameter.spec.ts +0 -85
  96. package/src/lib/device-parameter.ts +0 -79
  97. package/src/lib/device.ts +0 -10
  98. package/src/lib/hardware-description.spec.ts +0 -253
  99. package/src/lib/hardware-description.ts +0 -129
  100. package/src/lib/logger.ts +0 -5
  101. package/src/lib/monitoring-config.ts +0 -6
  102. package/src/lib/motion-master-client.ts +0 -250
  103. package/src/lib/motion-master-pub-sub-client.ts +0 -100
  104. package/src/lib/motion-master-pub-sub-socket.ts +0 -40
  105. package/src/lib/motion-master-pub-sub-web-socket.ts +0 -78
  106. package/src/lib/motion-master-pub-sub-worker-socket.ts +0 -51
  107. package/src/lib/motion-master-req-res-client.spec.ts +0 -740
  108. package/src/lib/motion-master-req-res-client.ts +0 -2206
  109. package/src/lib/motion-master-req-res-socket.ts +0 -62
  110. package/src/lib/motion-master-req-res-web-socket.ts +0 -124
  111. package/src/lib/motion-master-req-res-worker-socket.ts +0 -87
  112. package/src/lib/operators.ts +0 -110
  113. package/src/lib/options.ts +0 -12
  114. package/src/lib/parameter.spec.ts +0 -160
  115. package/src/lib/parameter.ts +0 -170
  116. package/src/lib/product-id-range.ts +0 -8
  117. package/src/lib/request-status-resolver.ts +0 -403
  118. package/src/lib/system-log-line.ts +0 -9
  119. package/src/lib/urls.ts +0 -6
  120. package/src/lib/util.ts +0 -317
  121. package/tsconfig.json +0 -23
  122. package/tsconfig.lib.json +0 -10
  123. package/tsconfig.spec.json +0 -20
  124. package/typedoc.json +0 -10
  125. /package/src/{index.ts → index.d.ts} +0 -0
@@ -1,250 +0,0 @@
1
- import { combineLatest, defer, distinctUntilChanged, filter, first, firstValueFrom, map, mergeMap, Observable, tap, 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
- import { DeviceParameter } from "./device-parameter";
14
-
15
- export function createMotionMasterClient(hostname: string) {
16
- const reqResSocket = new MotionMasterReqResWebSocket();
17
- const pubSubSocket = new MotionMasterPubSubWebSocket();
18
-
19
- const client = new MotionMasterClient(reqResSocket, pubSubSocket);
20
-
21
- const clientId = v4();
22
- reqResSocket.open(`ws://${hostname}:63524?clientId=${clientId}`);
23
- pubSubSocket.open(`ws://${hostname}:63525?clientId=${clientId}`);
24
-
25
- return client;
26
- }
27
-
28
- export class MotionMasterClient {
29
-
30
- readonly request: MotionMasterReqResClient;
31
- readonly monitor: MotionMasterPubSubClient;
32
-
33
- constructor(
34
- readonly reqResSocket: MotionMasterReqResSocket,
35
- readonly pubSubSocket: MotionMasterPubSubSocket,
36
- ) {
37
- this.request = new MotionMasterReqResClient(this.reqResSocket);
38
- this.monitor = new MotionMasterPubSubClient(this.pubSubSocket);
39
- }
40
-
41
- /**
42
- * This observable will emit true when both req/res and pub/sub sockets are opened.
43
- * If any socket gets closed, this observable will emit false.
44
- * This is a hot observable that will on subscription emit the last value of sockets opened.
45
- */
46
- socketsOpened$ = combineLatest([this.reqResSocket.opened$, this.pubSubSocket.opened$]).pipe(
47
- map(([reqResSocketOpened, pubSubSocketOpened]) => reqResSocketOpened && pubSubSocketOpened),
48
- );
49
-
50
- /**
51
- * Client is ready when both req/res and pub/sub sockets are opened.
52
- * This observable will emit whenever the sockets opened property changes to true.
53
- */
54
- ready$ = this.socketsOpened$.pipe(
55
- filter(Boolean),
56
- );
57
-
58
- /**
59
- * This observable will emit only once when both req/res and pub/sub sockets are opened.
60
- * NOTE: This observable might never emit and it doesn't timeout.
61
- */
62
- onceReady$ = this.ready$.pipe(
63
- first(),
64
- );
65
-
66
- /**
67
- * Client is ready when both req/res and pub/sub sockets are opened.
68
- * If both sockets are already opened, this function will immediately resolve to true.
69
- * Otherwise, it will wait up to requestTimeout for both sockets to open, or throw an error.
70
- */
71
- whenReady(requestTimeout = 5000): Promise<true> {
72
- return firstValueFrom(
73
- this.ready$.pipe(
74
- timeout(requestTimeout),
75
- ),
76
- );
77
- }
78
-
79
- startMonitoring(
80
- ids: DeviceParameterIds,
81
- monitoringInterval: number,
82
- config?: MonitoringConfig,
83
- requestTimeout = 5000,
84
- ): Observable<ParameterValueType[]> {
85
- return defer(() => {
86
- const topic = config?.topic ?? v4();
87
- const messageId = config?.messageId ?? v4();
88
-
89
- if (!config) {
90
- config = { messageId, topic, bufferSize: 1, distinct: false };
91
- }
92
-
93
- this.request.resolveGetParameterValuesIds(ids).pipe(
94
- mergeMap((refs) => {
95
- if ((new Set(refs.map(([deviceAddress]) => deviceAddress))).size !== 1) {
96
- throw new Error('Start monitoring only supports a single device');
97
- }
98
-
99
- // Skipping write-only (wo) parameters is necessary because Motion Master does not initiate monitoring when the requested list contains such parameters.
100
- // For now, this serves as a temporary solution until Motion Master is fixed.
101
- refs = refs.filter(([, index]) => index !== 0x1024);
102
-
103
- const deviceAddress = refs[0][0];
104
-
105
- const props: MotionMasterMessage.Request.IStartMonitoringDeviceParameterValues = {
106
- getDeviceParameterValues: {
107
- deviceAddress,
108
- parameters: refs.map(([, index, subindex]) => ({ index, subindex, loadFromCache: false })),
109
- sendProgress: false,
110
- },
111
- interval: monitoringInterval,
112
- topic,
113
- };
114
-
115
- return this.request.startMonitoringDeviceParameterValues(props, requestTimeout, messageId);
116
- }),
117
- ).subscribe();
118
-
119
- this.monitor.subscribe(config);
120
-
121
- const values$ = this.monitor.socket.data$.pipe(
122
- selectMotionMasterMessageByTopic(config.topic),
123
- mapMonitoringParameterValuesStatusMessageToParameterValues(),
124
- );
125
-
126
- return new Observable<ParameterValueType[]>((subscriber) => {
127
- const subscription = values$.subscribe(subscriber);
128
- return () => {
129
- subscription.unsubscribe();
130
- this.stopMonitoring(messageId);
131
- };
132
- });
133
- });
134
- }
135
-
136
- /**
137
- * TODO: return device parameters instead of just parameters
138
- * get parameters from ESI uprfront, and then when parameters are received
139
- * from motion master just concatenate (spread operator) props from ESI and props from parameter
140
- * assign device parameter id like 0x1018:00.12345
141
- * when assembling device parameter, get parameter from device in ESI based on product code, see ESI service
142
- * this should probably done for other get parameters functions, get ESI file from device or prepared, get data from it
143
- */
144
- startMonitoringDeviceParameters(
145
- ids: DeviceParameterIds,
146
- monitoringInterval: number,
147
- config?: MonitoringConfig,
148
- requestTimeout = 5000,
149
- ): Observable<DeviceParameter[]> {
150
- return defer(() => {
151
- const topic = config?.topic ?? v4();
152
- const messageId = config?.messageId ?? v4();
153
-
154
- if (!config) {
155
- config = { messageId, topic, bufferSize: 1, distinct: false };
156
- }
157
-
158
- this.request.resolveGetParameterValuesIds(ids).pipe(
159
- mergeMap((refs) => {
160
- if ((new Set(refs.map(([deviceAddress]) => deviceAddress))).size !== 1) {
161
- throw new Error('Start monitoring only supports a single device');
162
- }
163
-
164
- // Skipping write-only (wo) parameters is necessary because Motion Master does not initiate monitoring when the requested list contains such parameters.
165
- // For now, this serves as a temporary solution until Motion Master is fixed.
166
- refs = refs.filter(([, index]) => index !== 0x1024);
167
-
168
- const deviceAddress = refs[0][0];
169
-
170
- const props: MotionMasterMessage.Request.IStartMonitoringDeviceParameterValues = {
171
- getDeviceParameterValues: {
172
- deviceAddress,
173
- parameters: refs.map(([, index, subindex]) => ({ index, subindex, loadFromCache: false })),
174
- sendProgress: false,
175
- },
176
- interval: monitoringInterval,
177
- topic,
178
- };
179
-
180
- return this.request.startMonitoringDeviceParameterValues(props, requestTimeout, messageId);
181
- }),
182
- ).subscribe();
183
-
184
- this.monitor.subscribe(config);
185
-
186
- const values$ = this.monitor.socket.data$.pipe(
187
- selectMotionMasterMessageByTopic(config.topic),
188
- mapMonitoringParameterValuesStatusMessageToDeviceParameters(this.request),
189
- );
190
-
191
- return new Observable<DeviceParameter[]>((subscriber) => {
192
- const subscription = values$.subscribe(subscriber);
193
- return () => {
194
- subscription.unsubscribe();
195
- this.stopMonitoring(messageId);
196
- };
197
- });
198
- });
199
- }
200
-
201
- startMonitoringValue<T extends ParameterValueType = number>(
202
- id: string | [DeviceRef, number, number],
203
- monitoringInterval: number,
204
- config?: MonitoringConfig,
205
- requestTimeout = 5000,
206
- ): Observable<T> {
207
- const ids = typeof id === 'string' ? [id] : [id];
208
- return this.startMonitoring(ids, monitoringInterval, config, requestTimeout).pipe(
209
- map((parameters) => (parameters[0] ?? 0) as T),
210
- );
211
- }
212
-
213
- trackTargetReached(deviceRef: DeviceRef, monitoringInterval = 20): Observable<boolean> {
214
- return this.startMonitoringValue([deviceRef, 0x6041, 0], monitoringInterval).pipe(
215
- map((value) => (value & 0x0400) > 0), // tr = target reached bit
216
- distinctUntilChanged(),
217
- );
218
- }
219
-
220
- waitUntilTargetReached(deviceRef: DeviceRef, monitoringInterval = 20): Observable<true> {
221
- return this.trackTargetReached(deviceRef, monitoringInterval).pipe(
222
- filter(Boolean),
223
- first(),
224
- );
225
- }
226
-
227
- whenTargetReached(deviceRef: DeviceRef, monitoringInterval = 20): Promise<true> {
228
- return firstValueFrom(this.waitUntilTargetReached(deviceRef, monitoringInterval));
229
- }
230
-
231
- stopMonitoring(messageId: string): void {
232
- this.request.stopMonitoringDeviceParameterValues({ startMonitoringRequestId: messageId });
233
- this.monitor.unsubscribe(messageId);
234
- }
235
-
236
- stopMonitoringAll(): void {
237
- this.monitor.messageIds.forEach(this.stopMonitoring);
238
- }
239
-
240
- closeSockets() {
241
- this.reqResSocket.close();
242
- this.pubSubSocket.close();
243
- }
244
-
245
- reopenSockets() {
246
- this.reqResSocket.reopen();
247
- this.pubSubSocket.reopen();
248
- }
249
-
250
- }
@@ -1,100 +0,0 @@
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
- get messageIds(): string[] {
33
- return Array.from(this.subscriptions.keys());
34
- }
35
-
36
- subscribe(config: MonitoringConfig): string {
37
- const messageId = config.messageId ?? v4();
38
- if (!config.messageId) {
39
- config = { ...config, messageId };
40
- }
41
-
42
- if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
43
- this.socket.worker.postMessage({ subscribe: config });
44
- } else {
45
- const { bufferSize = 1, distinct = false, topic } = config;
46
-
47
- let observable: Observable<IMotionMasterMessage> = this.socket.data$.pipe(
48
- filter((data) => data[0] === topic),
49
- map((data) => data[1]),
50
- );
51
-
52
- if (distinct) {
53
- observable = observable.pipe(
54
- distinctUntilChanged((prev, curr) => {
55
- if (prev?.status?.monitoringParameterValues?.deviceParameterValues?.parameterValues
56
- && curr?.status?.monitoringParameterValues?.deviceParameterValues?.parameterValues) {
57
- return equal(
58
- prev.status.monitoringParameterValues.deviceParameterValues.parameterValues,
59
- curr.status.monitoringParameterValues.deviceParameterValues.parameterValues,
60
- )
61
- }
62
- return false;
63
- }),
64
- );
65
- }
66
-
67
- const subscription = observable.pipe(
68
- bufferCount(bufferSize),
69
- ).subscribe((data) => {
70
- this.data$.next([topic, data]);
71
- });
72
-
73
- this.subscriptions.set(messageId, subscription);
74
- }
75
-
76
- return messageId;
77
- }
78
-
79
- unsubscribe(messageId: string): void {
80
- if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
81
- this.socket.worker.postMessage({ unsubcribe: { messageId } });
82
- } else {
83
- const subscription = this.subscriptions.get(messageId);
84
- if (subscription) {
85
- subscription.unsubscribe();
86
- this.subscriptions.delete(messageId);
87
- }
88
- }
89
- }
90
-
91
- unsubscribeAll(): void {
92
- if (this.socket instanceof MotionMasterPubSubWorkerSocket) {
93
- this.socket.worker.postMessage({ unsubscribeAll: true });
94
- } else {
95
- this.subscriptions.forEach((subscription) => subscription.unsubscribe());
96
- this.subscriptions.clear();
97
- }
98
- }
99
-
100
- }
@@ -1,40 +0,0 @@
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
- }
@@ -1,78 +0,0 @@
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
- }
@@ -1,51 +0,0 @@
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
- }