/
spec.ts
577 lines (529 loc) · 14.4 KB
/
spec.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../../jacdac-spec/spectool/jdspec.d.ts" />
import { NumberFormat } from "./buffer"
import serviceSpecificationData from "../../jacdac-spec/dist/services.json"
import { bufferEq, fromHex, toggleBit, toHex } from "./utils"
import {
SystemEvent,
SystemReg,
SensorReg,
SRV_CONTROL,
SRV_ROLE_MANAGER,
SRV_SETTINGS,
SRV_BOOTLOADER,
SRV_LOGGER,
SRV_INFRASTRUCTURE,
SRV_PROTO_TEST,
SRV_PROXY,
SRV_UNIQUE_BRAIN,
SRV_DASHBOARD,
SRV_BRIDGE,
SRV_JACSCRIPT_CONDITION,
SRV_JACSCRIPT_MANAGER,
} from "./constants"
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let _serviceSpecifications: jdspec.ServiceSpec[] =
serviceSpecificationData as any
let _serviceSpecificationMap: Record<number, jdspec.ServiceSpec> = undefined
let _customServiceSpecifications: Record<string, jdspec.ServiceSpec> = {}
/**
* Override built-in service specifications
* @param specs
* @category Specification
*/
export function loadServiceSpecifications(specs: jdspec.ServiceSpec[]) {
_serviceSpecifications = specs?.slice(0) || []
_serviceSpecificationMap = undefined
}
/**
* Adds a custom service specification
* @param service
* @category Specification
*/
export function addCustomServiceSpecification(service: jdspec.ServiceSpec) {
if (service && service.classIdentifier) {
_customServiceSpecifications[service.classIdentifier] = service
_serviceSpecificationMap = undefined
}
}
/**
* Clears any custom service specification
* @category Specification
*/
export function clearCustomServiceSpecifications() {
_customServiceSpecifications = {}
_serviceSpecificationMap = undefined
}
/**
* Returns a map from service short ids to service specifications
* @category Specification
*/
export function serviceMap(): Record<string, jdspec.ServiceSpec> {
const m: Record<string, jdspec.ServiceSpec> = {}
_serviceSpecifications.forEach(spec => (m[spec.shortId] = spec))
return m
}
/**
* Returns the list of service specifications
* @category Specification
*/
export function serviceSpecifications() {
return _serviceSpecifications.slice(0)
}
/**
* @internal
*/
export function identifierToUrlPath(id: string) {
if (!id) return id
const escape = (s: string) => s.replace(/[.:]/g, "").toLowerCase()
const parts = id.split(/-/g)
if (parts.length === 1) return id.replace(/[.:]/g, "").toLowerCase()
return `${parts.slice(0, -1).map(escape).join("-")}/${escape(
parts[parts.length - 1]
)}`
}
/**
* Checks if classIdentifier is compatible with requiredClassIdentifier
* @category Specification
*/
export function isInstanceOf(
classIdentifier: number,
requiredClassIdentifier: number
): boolean {
// garbage data
if (isNaN(classIdentifier)) return false
// direct hit
if (classIdentifier === requiredClassIdentifier) return true
// lookup inheritance chain
const classSpec = serviceSpecificationFromClassIdentifier(classIdentifier)
return !!classSpec?.extends?.some(extend => {
const extendSpec = serviceSpecificationFromName(extend)
return (
!!extendSpec &&
isInstanceOf(extendSpec.classIdentifier, requiredClassIdentifier)
)
})
}
/**
* Checks if the service supports the Jacdac infrastructure
* @param spec
* @returns
* @category Specification
*/
export function isInfrastructure(spec: jdspec.ServiceSpec) {
return (
spec &&
([
SRV_CONTROL,
SRV_ROLE_MANAGER,
SRV_LOGGER,
SRV_SETTINGS,
SRV_BOOTLOADER,
SRV_PROTO_TEST,
SRV_INFRASTRUCTURE,
SRV_PROXY,
SRV_UNIQUE_BRAIN,
SRV_DASHBOARD,
SRV_BRIDGE,
SRV_JACSCRIPT_CONDITION,
SRV_JACSCRIPT_MANAGER,
].indexOf(spec.classIdentifier) > -1 ||
spec.shortId[0] === "_")
)
}
/**
* Looks up a service specification by name
* @param shortId
* @category Specification
*/
export function serviceSpecificationFromName(
shortId: string
): jdspec.ServiceSpec {
if (!shortId) return undefined
return (
_serviceSpecifications.find(s => s.shortId === shortId) ||
Object.values(_customServiceSpecifications).find(
ser => ser.shortId === shortId
)
)
}
/**
* Looks up a service specification by class
* @param classIdentifier
* @category Specification
*/
export function serviceSpecificationFromClassIdentifier(
classIdentifier: number
): jdspec.ServiceSpec {
if (isNaN(classIdentifier)) return undefined
// try lookup cache
let srv = _serviceSpecificationMap?.[classIdentifier]
if (srv) return srv
// resolve
srv =
_serviceSpecifications.find(
s => s.classIdentifier === classIdentifier
) || _customServiceSpecifications[classIdentifier]
if (srv) {
if (!_serviceSpecificationMap) _serviceSpecificationMap = {}
_serviceSpecificationMap[classIdentifier] = srv
}
return srv
}
/**
* Indicates if the specified service is a sensor
* @param spec
* @returns
* @category Specification
*/
export function isSensor(spec: jdspec.ServiceSpec): boolean {
return (
spec &&
spec.packets.some(pkt => isReading(pkt)) &&
spec.packets.some(pkt => pkt.identifier == SensorReg.StreamingSamples)
)
}
/**
* Indicates if the specified service is an actuator
* @param spec
* @returns
* @category Specification
*/
export function isActuator(spec: jdspec.ServiceSpec): boolean {
return (
spec &&
spec.packets.some(pkt => pkt.identifier === SystemReg.Value) &&
spec.packets.some(pkt => pkt.identifier === SystemReg.Intensity)
)
}
/**
* Indicates if the packet information is a register
* @param spec
* @returns
* @category Specification
*/
export function isRegister(pkt: jdspec.PacketInfo) {
return pkt && (pkt.kind == "const" || pkt.kind == "ro" || pkt.kind == "rw")
}
/**
* Indicates if the packet information is a ``reading`` register
* @param spec
* @returns
* @category Specification
*/
export function isReading(pkt: jdspec.PacketInfo) {
return pkt && pkt.kind == "ro" && pkt.identifier == SystemReg.Reading
}
const ignoredRegister = [
SystemReg.StatusCode,
SystemReg.InstanceName,
SystemReg.StreamingInterval,
SystemReg.StreamingPreferredInterval,
SystemReg.StreamingSamples,
SystemReg.ReadingError,
SystemReg.ReadingResolution,
SystemReg.MinReading,
SystemReg.MaxReading,
SystemReg.MinValue,
SystemReg.MaxValue,
SystemReg.MaxPower,
]
/**
* Indicates if the register is usable from a high-level programming environment.
* @category Specification
*/
export function isHighLevelRegister(pkt: jdspec.PacketInfo) {
return (
isRegister(pkt) &&
!pkt.lowLevel &&
!pkt.internal &&
ignoredRegister.indexOf(pkt.identifier) < 0
)
}
const ignoredEvents = [SystemEvent.StatusCodeChanged]
/**
* Indicates if the event is usable from a high-level programming environment.
* @category Specification
*/
export function isHighLevelEvent(pkt: jdspec.PacketInfo) {
return (
isEvent(pkt) &&
!pkt.lowLevel &&
!pkt.internal &&
ignoredEvents.indexOf(pkt.identifier) < 0
)
}
/**
* Indicate if the register code is an auxilliary register to support streaming.
* @param code
* @returns
* @category Specification
*/
export function isOptionalReadingRegisterCode(code: number) {
const regs = [
SystemReg.MinReading,
SystemReg.MaxReading,
SystemReg.ReadingError,
SystemReg.ReadingResolution,
SystemReg.StreamingPreferredInterval,
]
return regs.indexOf(code) > -1
}
/**
* Indicates if the packet info represents an ``intensity`` register
* @category Specification
*/
export function isIntensity(pkt: jdspec.PacketInfo) {
return pkt && pkt.kind == "rw" && pkt.identifier == SystemReg.Intensity
}
/**
* Indicates if the packet info represents a ``value`` register
* @category Specification
*/
export function isValue(pkt: jdspec.PacketInfo) {
return pkt && pkt.kind == "rw" && pkt.identifier == SystemReg.Value
}
/**
* Indicates if the packet info represents a ``intensity`` or a ``value`` register
* @category Specification
*/
export function isValueOrIntensity(pkt: jdspec.PacketInfo) {
return (
pkt &&
pkt.kind == "rw" &&
(pkt.identifier == SystemReg.Value ||
pkt.identifier == SystemReg.Intensity)
)
}
/**
* Indicates if the packet info represents an ``const`` register
* @category Specification
*/
export function isConstRegister(pkt: jdspec.PacketInfo) {
return pkt?.kind === "const"
}
/**
* Indicates if the packet info is not rw
*/
export function isReadOnlyRegister(pkt: jdspec.PacketInfo) {
return pkt?.kind !== "rw"
}
/**
* Indicates if the packet info represents an ``event``
* @category Specification
*/
export function isEvent(pkt: jdspec.PacketInfo) {
return pkt.kind == "event"
}
/**
* Indicates if the packet info represents a ``command``
* @category Specification
*/
export function isCommand(pkt: jdspec.PacketInfo) {
return pkt.kind == "command"
}
/**
* Indicates if the packet info represents a ``pipe_report``
* @category Specification
*/
export function isPipeReport(pkt: jdspec.PacketInfo) {
return pkt.kind == "pipe_report"
}
/**
* Indicates if the `report` packet is the report specication of the `cmd` command.
* @category Specification
*/
export function isReportOf(cmd: jdspec.PacketInfo, report: jdspec.PacketInfo) {
return (
report.secondary &&
report.kind == "report" &&
cmd.kind == "command" &&
cmd.name == report.name
)
}
/**
* Indicates if the `report` packet is the *pipe* report specication of the `cmd` command.
* @category Specification
*/
export function isPipeReportOf(
cmd: jdspec.PacketInfo,
pipeReport: jdspec.PacketInfo
) {
return (
pipeReport.kind == "pipe_report" &&
cmd.kind == "command" &&
cmd.pipeType &&
cmd.pipeType === pipeReport.pipeType
)
}
/**
* @internal
*/
export function isIntegerType(tp: string) {
return /^[ui]\d+(\.|$)/.test(tp) || tp == "pipe_port" || tp == "bool"
}
/**
* @internal
*/
export function numberFormatFromStorageType(tp: jdspec.StorageType) {
switch (tp) {
case -1:
return NumberFormat.Int8LE
case 1:
return NumberFormat.UInt8LE
case -2:
return NumberFormat.Int16LE
case 2:
return NumberFormat.UInt16LE
case -4:
return NumberFormat.Int32LE
case 4:
return NumberFormat.UInt32LE
case -8:
return NumberFormat.Int64LE
case 8:
return NumberFormat.UInt64LE
case 0:
return null
default:
return null
}
}
/**
* @internal
*/
export function numberFormatToStorageType(nf: NumberFormat) {
switch (nf) {
case NumberFormat.Int8LE:
return -1
case NumberFormat.UInt8LE:
return 1
case NumberFormat.Int16LE:
return -2
case NumberFormat.UInt16LE:
return 2
case NumberFormat.Int32LE:
return -4
case NumberFormat.UInt32LE:
return 4
case NumberFormat.Int64LE:
return -8
case NumberFormat.UInt64LE:
return 8
default:
return null
}
}
/**
* @internal
*/
export function scaleIntToFloat(v: number, info: jdspec.PacketMember) {
if (!info.shift) return v
if (info.shift < 0) return v * (1 << -info.shift)
else return v / (1 << info.shift)
}
/**
* @internal
*/
export function scaleFloatToInt(v: number, info: jdspec.PacketMember) {
if (!info.shift) return v
if (info.shift < 0) return Math.round(v / (1 << -info.shift))
else return Math.round(v * (1 << info.shift))
}
/**
* @internal
*/
export function storageTypeRange(tp: jdspec.StorageType): [number, number] {
if (tp == 0) throw new Error("no range for 0")
if (tp < 0) {
const v = Math.pow(2, -tp * 8 - 1)
return [-v, v - 1]
} else {
const v = Math.pow(2, tp * 8)
return [0, v - 1]
}
}
/**
* @internal
*/
export function clampToStorage(v: number, tp: jdspec.StorageType) {
if (tp == null) return v // no clamping for floats
const [min, max] = storageTypeRange(tp)
if (isNaN(v)) return 0
if (v < min) return min
if (v > max) return max
return v
}
/**
* @internal
*/
export function memberValueToString(
value: any,
info: jdspec.PacketMember
): string {
if (value === undefined || value === null) return ""
switch (info.type) {
case "bytes":
return toHex(value)
case "string":
return value
default:
return "" + value
}
}
/**
* @internal
*/
export function tryParseMemberValue(
text: string,
info: jdspec.PacketMember
): { value?: any; error?: string } {
if (!text) return {}
if (info.type === "string") return { value: text }
else if (info.type === "pipe") return {}
// not supported
else if (info.type === "bytes") {
try {
return { value: fromHex(text) }
} catch (e) {
return {
error: "invalid hexadecimal format",
}
}
} else {
const n = isIntegerType(info.type) ? parseInt(text) : parseFloat(text)
if (isNaN(n)) return { error: "invalid format" }
else return { value: n }
}
}
/**
* Parses a device identifier into a buffer, returns undefined if invalid
* @param id
* @returns
* @category Specification
*/
export function parseDeviceId(id: string): Uint8Array {
if (!id) return undefined
id = id.replace(/\s/g, "")
if (id.length != 16 || !/^[a-f0-9]+$/i.test(id)) return undefined
return fromHex(id)
}
export function parseDualDeviceId(id: string) {
const rid = parseDeviceId(id)
toggleBit(rid, 0)
return rid
}
export function dualDeviceId(id: string): string {
return toHex(parseDualDeviceId(id))
}
/**
* Check if the left device identifier is a bootloader dual of the right identifier
* @param left
* @param right
* @returns
*/
export function isDualDeviceId(left: string, right: string) {
const lid = parseDeviceId(left)
const rid = parseDualDeviceId(right)
return bufferEq(lid, rid)
}