/
serviceserver.ts
345 lines (309 loc) · 10 KB
/
serviceserver.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
import {
BaseEvent,
SystemCmd,
SystemEvent,
SystemReg,
SystemStatusCodes,
} from "../../../jacdac-spec/dist/specconstants"
import {
CHANGE,
DEVICE_CHANGE,
FRAME_PROCESS_LARGE,
PACKET_RECEIVE,
PACKET_SEND,
REPORT_UPDATE,
} from "../constants"
import { JDServerServiceProvider } from "./serverserviceprovider"
import { JDEventSource } from "../eventsource"
import { Packet } from "../packet"
import { JDRegisterServer } from "./registerserver"
import { isRegister, serviceSpecificationFromClassIdentifier } from "../spec"
import { PackedValues } from "../pack"
import { JDService } from "../service"
const CALIBRATION_DELAY = 5000
/**
* Server instiation options
* @category Servers
*/
export interface JDServerOptions {
/**
* Service instance name
*/
instanceName?: string
/**
* This server instance is a twin of a physical device and should not emit any packet
*/
twin?: JDService
/**
* Initial value for the ``value`` register
*/
valueValues?: PackedValues
/**
* Initial value for the ``intensity`` register
*/
intensityValues?: PackedValues
/**
* A callback to transform the received intensity value data
*/
intensityProcessor?: (values: PackedValues) => PackedValues
/**
* Emit active/inactive events based on the intensity register
*/
isActive?: (intensity: PackedValues) => boolean
/**
* Initial value for the ``variant`` register
*/
variant?: number
/**
* Optional client variant register
*/
clientVariant?: string
/**
* A map of custom register initial values
*/
registerValues?: {
code: number
values: PackedValues
}[]
}
/**
* Base class for service server implementations
* @category Servers
*/
export class JDServiceServer extends JDEventSource {
public serviceIndex = -1 // set by device
private _device: JDServerServiceProvider
public readonly specification: jdspec.ServiceSpec
private readonly _registers: JDRegisterServer<PackedValues>[] = []
private readonly commands: {
[identifier: number]: (pkt: Packet) => void
} = {}
readonly statusCode: JDRegisterServer<[SystemStatusCodes, number]>
readonly instanceName: JDRegisterServer<[string]>
private _twin: JDService
private _twinCleanup: (() => void)[]
private _locked = false
constructor(
public readonly serviceClass: number,
options?: JDServerOptions,
) {
super()
const {
instanceName,
variant,
valueValues,
intensityValues,
intensityProcessor,
registerValues,
clientVariant,
isActive,
} = options || {}
this.specification = serviceSpecificationFromClassIdentifier(
this.serviceClass,
)
this.statusCode = this.addRegister<[SystemStatusCodes, number]>(
SystemReg.StatusCode,
[SystemStatusCodes.Ready, 0],
)
if (valueValues) this.addRegister(SystemReg.Value, valueValues)
if (intensityValues) {
const intensity = this.addRegister(
SystemReg.Intensity,
intensityValues,
)
if (intensityProcessor)
intensity.valueProcessor = intensityProcessor
if (isActive)
intensity.on(CHANGE, () => {
const ev = isActive(intensity.values())
if (ev !== undefined)
this.sendEvent(
isActive(intensity.values())
? SystemEvent.Active
: SystemEvent.Inactive,
)
})
}
if (variant) this.addRegister<[number]>(SystemReg.Variant, [variant])
if (clientVariant)
this.addRegister<[string]>(SystemReg.ClientVariant, [clientVariant])
this.instanceName = this.addRegister<[string]>(SystemReg.InstanceName, [
instanceName || "",
])
// any extra
registerValues?.forEach(({ code, values }) =>
this.addRegister<PackedValues>(code, values),
)
// emit event when status code changes
this.statusCode.on(CHANGE, () =>
this.sendEvent(BaseEvent.StatusCodeChanged, this.statusCode.data),
)
// if the device has a calibrate command, regiser handler
// and put device in calibrationneeded state
if (
this.specification.packets.find(
pkt =>
pkt.kind === "command" &&
pkt.identifier === SystemCmd.Calibrate,
)
) {
this.addCommand(
SystemCmd.Calibrate,
this.handleCalibrate.bind(this),
)
this.statusCode.setValues(
[SystemStatusCodes.CalibrationNeeded, 0],
true,
)
}
this.handleTwinPacket = this.handleTwinPacket.bind(this)
}
get device() {
return this._device
}
set device(value: JDServerServiceProvider) {
if (this._device !== value) {
this._device = value
this.emit(DEVICE_CHANGE)
this.emit(CHANGE)
}
}
get twin() {
return this._twin
}
set twin(service: JDService) {
if (service === this._twin) return
if (this._twin) {
this._twin.off(PACKET_RECEIVE, this.handleTwinPacket)
this._twin.off(PACKET_SEND, this.handleTwinPacket)
this._twinCleanup.forEach(tw => tw())
// unsubscribe
}
this._twin = service
this._twinCleanup = service ? [] : undefined
if (this._twin) {
this._twin.on(PACKET_RECEIVE, this.handleTwinPacket)
this._twin.on(PACKET_SEND, this.handleTwinPacket)
this._twin.registers().forEach(twinReg => {
const reg = this.register(twinReg.code)
if (reg) {
reg?.setValues(twinReg.unpackedValue)
this._twinCleanup.push(
twinReg.subscribe(REPORT_UPDATE, () =>
reg.setValues(twinReg.unpackedValue),
),
)
}
})
}
this.emit(CHANGE)
}
private handleTwinPacket(pkt: Packet) {
this.handlePacket(pkt)
}
get registers() {
return this._registers.slice(0)
}
get timestamp() {
const bus = this.device?.bus || this._twin?.device?.bus
return bus?.timestamp
}
register<TValues extends PackedValues = PackedValues>(
code: number,
): JDRegisterServer<TValues> {
return this._registers.find(
reg => reg.identifier === code,
) as JDRegisterServer<TValues>
}
protected addExistingRegister<TValues extends PackedValues = PackedValues>(
reg: JDRegisterServer<TValues>,
) {
this._registers.push(reg)
return reg
}
addRegister<TValues extends PackedValues = PackedValues>(
identifier: number,
defaultValue?: TValues,
): JDRegisterServer<TValues> {
let reg = this._registers.find(
r => r.identifier === identifier,
) as JDRegisterServer<TValues>
if (!reg && !this._locked) {
// make sure this register is supported
if (
!this.specification.packets.find(
pkt => isRegister(pkt) && pkt.identifier === identifier,
)
)
return undefined
reg = new JDRegisterServer<TValues>(this, identifier, defaultValue)
this._registers.push(reg)
}
return reg
}
reset() {
this.registers.forEach(reg => reg.reset())
}
/**
* Locks the current set of registers
*/
public lock() {
this._locked = true
}
protected addCommand(identifier: number, handler: (pkt: Packet) => void) {
if (this._locked) console.error(`adding command to locked service`)
this.commands[identifier] = handler
}
async handlePacket(pkt: Packet) {
if (pkt.isRegisterGet || pkt.isRegisterSet) {
// find register to handle
const rid = pkt.registerIdentifier
let reg = this._registers.find(r => r.identifier === rid)
if (!reg) {
// try adding
reg = this.addRegister(rid)
}
reg?.handlePacket(pkt)
} else if (pkt.isCommand) {
const cmd = this.commands[pkt.serviceCommand]
if (cmd) cmd(pkt)
else if (cmd === undefined)
console.debug(`ignored command`, { pkt })
}
// ignored?
}
async sendPacketAsync(pkt: Packet) {
if (this.twin) return
pkt.serviceIndex = this.serviceIndex
await this.device.sendPacketAsync(pkt)
}
async sendEvent(eventCode: number, data?: Uint8Array) {
if (this.twin) return
const { device } = this
if (!device) return
const { bus } = device
if (!bus) return
const now = bus.timestamp
const cmd = device.createEventCmd(eventCode)
const pkt = Packet.from(cmd, data || new Uint8Array(0))
await this.sendPacketAsync(pkt)
device.delayedSend(pkt, now + 20)
device.delayedSend(pkt, now + 100)
}
private async handleCalibrate() {
const [status] = this.statusCode.values()
if (status !== SystemStatusCodes.Ready) return
this.calibrate()
}
processLargeFrame(command: string, data: Uint8Array) {
this.emit(FRAME_PROCESS_LARGE, command, data)
}
async calibrate() {
// notify that calibration started
this.statusCode.setValues([SystemStatusCodes.Calibrating, 0])
// wait 5 seconds
await this.device.bus.delay(CALIBRATION_DELAY)
// finish
this.statusCode.setValues([SystemStatusCodes.Ready, 0])
}
}