@springfield/ham-radio-utils 4.1.2 → 4.2.0

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.
@@ -0,0 +1,522 @@
1
+ import type {
2
+ RadioMemoryConfig,
3
+ RadioMemoryMap,
4
+ RadioMemoryMapField,
5
+ RadioMemoryMapStruct,
6
+ RadioMemoryMapValueKind,
7
+ RadioSettings,
8
+ RadioSettingValue,
9
+ } from '@springfield/ham-radio-api';
10
+
11
+ const DEFAULT_DTMF_CHARSET = '0123456789 *#ABCD';
12
+
13
+ /**
14
+ * Parse a seek address from a number or hex/decimal string.
15
+ */
16
+ export function parseSeekAddress(seek: number | string): number {
17
+ if (typeof seek === 'number') {
18
+ return seek;
19
+ }
20
+
21
+ const trimmed = seek.trim();
22
+
23
+ if (/^0x/i.test(trimmed)) {
24
+ return Number.parseInt(trimmed, 16);
25
+ }
26
+
27
+ return Number.parseInt(trimmed, 10);
28
+ }
29
+
30
+ /**
31
+ * Map a radio EEPROM address to an offset in the memory buffer.
32
+ *
33
+ * Packed buffers (driver read) concatenate segments in config order.
34
+ * Sparse buffers that cover the highest segment end address use absolute offsets.
35
+ */
36
+ export function radioAddressToBufferOffset(
37
+ radioAddress: number,
38
+ memoryConfig: RadioMemoryConfig,
39
+ bufferLength: number,
40
+ ): number {
41
+ const segments = Object.values(memoryConfig.segments);
42
+ const maxEndAddress = Math.max(...segments.map((segment) => segment.endAddress));
43
+
44
+ if (bufferLength >= maxEndAddress + 1) {
45
+ return radioAddress;
46
+ }
47
+
48
+ let offset = 0;
49
+
50
+ for (const segment of segments) {
51
+ if (radioAddress >= segment.startAddress && radioAddress <= segment.endAddress) {
52
+ return offset + (radioAddress - segment.startAddress);
53
+ }
54
+
55
+ offset += segment.endAddress - segment.startAddress + 1;
56
+ }
57
+
58
+ throw new Error(`Radio address 0x${radioAddress.toString(16)} is not in any memory segment`);
59
+ }
60
+
61
+ function bufferOffsetFor(radioAddress: number, memoryConfig: RadioMemoryConfig, contents: Uint8Array): number {
62
+ return radioAddressToBufferOffset(radioAddress, memoryConfig, contents.length);
63
+ }
64
+
65
+ function readByte(contents: Uint8Array, offset: number): number {
66
+ if (offset < 0 || offset >= contents.length) {
67
+ throw new RangeError(`Memory-map read out of bounds at offset ${offset}`);
68
+ }
69
+
70
+ return contents[offset];
71
+ }
72
+
73
+ function writeByte(contents: Uint8Array, offset: number, value: number): void {
74
+ if (offset < 0 || offset >= contents.length) {
75
+ throw new RangeError(`Memory-map write out of bounds at offset ${offset}`);
76
+ }
77
+
78
+ contents[offset] = value & 0xff;
79
+ }
80
+
81
+ function decodeRawValue(kind: RadioMemoryMapValueKind | undefined, raw: number | number[]): RadioSettingValue {
82
+ if (!kind) {
83
+ return typeof raw === 'number' ? raw : raw;
84
+ }
85
+
86
+ switch (kind.kind) {
87
+ case 'integer':
88
+ return typeof raw === 'number' ? raw : raw[0];
89
+ case 'boolean':
90
+ return (typeof raw === 'number' ? raw : raw[0]) !== 0;
91
+ case 'enum': {
92
+ const index = typeof raw === 'number' ? raw : raw[0];
93
+ return kind.values[index] ?? kind.values[0] ?? '';
94
+ }
95
+ case 'ascii': {
96
+ const bytes = typeof raw === 'number' ? [raw] : raw;
97
+ let text = '';
98
+
99
+ for (const byte of bytes) {
100
+ if (byte === 0xff || byte === 0x00) {
101
+ break;
102
+ }
103
+
104
+ text += String.fromCodePoint(byte);
105
+ }
106
+
107
+ return text.trimEnd();
108
+ }
109
+ case 'digits': {
110
+ const bytes = typeof raw === 'number' ? [raw] : raw;
111
+ let value = 0;
112
+
113
+ for (const digit of bytes) {
114
+ value = value * 10 + (digit & 0x0f);
115
+ }
116
+
117
+ return value * (kind.scale ?? 1);
118
+ }
119
+ case 'dtmf': {
120
+ const bytes = typeof raw === 'number' ? [raw] : raw;
121
+ const charset = kind.charset ?? DEFAULT_DTMF_CHARSET;
122
+ let text = '';
123
+
124
+ for (const byte of bytes) {
125
+ if (byte >= 0x1f) {
126
+ break;
127
+ }
128
+
129
+ if (byte < charset.length) {
130
+ text += charset[byte];
131
+ }
132
+ }
133
+
134
+ return text;
135
+ }
136
+ case 'bbcd': {
137
+ const bytes = typeof raw === 'number' ? [raw] : raw;
138
+ let value = 0;
139
+
140
+ for (const byte of bytes) {
141
+ value = value * 100 + ((byte >> 4) & 0x0f) * 10 + (byte & 0x0f);
142
+ }
143
+
144
+ return value;
145
+ }
146
+ default: {
147
+ const exhaustive: never = kind;
148
+ return exhaustive;
149
+ }
150
+ }
151
+ }
152
+
153
+ function encodeRawValue(kind: RadioMemoryMapValueKind | undefined, value: RadioSettingValue, byteLength: number): number[] {
154
+ const bytes = Array.from({ length: byteLength }, () => 0xff);
155
+
156
+ if (!kind) {
157
+ if (typeof value === 'number') {
158
+ bytes[0] = value & 0xff;
159
+ }
160
+
161
+ return bytes;
162
+ }
163
+
164
+ switch (kind.kind) {
165
+ case 'integer': {
166
+ bytes[0] = typeof value === 'number' ? value & 0xff : 0;
167
+ return bytes;
168
+ }
169
+ case 'boolean': {
170
+ bytes[0] = value ? 1 : 0;
171
+ return bytes;
172
+ }
173
+ case 'enum': {
174
+ const index = typeof value === 'string' ? kind.values.indexOf(value) : -1;
175
+ bytes[0] = index >= 0 ? index : 0;
176
+ return bytes;
177
+ }
178
+ case 'ascii': {
179
+ const text = typeof value === 'string' ? value : '';
180
+
181
+ for (let index = 0; index < byteLength; index += 1) {
182
+ bytes[index] = index < text.length ? (text.codePointAt(index) ?? 0xff) : 0xff;
183
+ }
184
+
185
+ return bytes;
186
+ }
187
+ case 'digits': {
188
+ const scale = kind.scale ?? 1;
189
+ let numeric = typeof value === 'number' ? Math.round(value / scale) : 0;
190
+
191
+ for (let index = byteLength - 1; index >= 0; index -= 1) {
192
+ bytes[index] = numeric % 10;
193
+ numeric = Math.floor(numeric / 10);
194
+ }
195
+
196
+ return bytes;
197
+ }
198
+ case 'dtmf': {
199
+ const text = typeof value === 'string' ? value : '';
200
+ const charset = kind.charset ?? DEFAULT_DTMF_CHARSET;
201
+
202
+ for (let index = 0; index < byteLength; index += 1) {
203
+ if (index < text.length) {
204
+ const charIndex = charset.indexOf(text[index]);
205
+ bytes[index] = charIndex >= 0 ? charIndex : 0xff;
206
+ } else {
207
+ bytes[index] = 0xff;
208
+ }
209
+ }
210
+
211
+ return bytes;
212
+ }
213
+ case 'bbcd': {
214
+ let numeric = typeof value === 'number' ? value : 0;
215
+ const digits: number[] = [];
216
+
217
+ for (let index = 0; index < byteLength * 2; index += 1) {
218
+ digits.unshift(numeric % 10);
219
+ numeric = Math.floor(numeric / 10);
220
+ }
221
+
222
+ for (let index = 0; index < byteLength; index += 1) {
223
+ bytes[index] = ((digits[index * 2] & 0x0f) << 4) | (digits[index * 2 + 1] & 0x0f);
224
+ }
225
+
226
+ return bytes;
227
+ }
228
+ default: {
229
+ const exhaustive: never = kind;
230
+ return exhaustive;
231
+ }
232
+ }
233
+ }
234
+
235
+ function fieldByteLength(field: RadioMemoryMapField): number {
236
+ if (field.type === 'u16') {
237
+ return 2;
238
+ }
239
+
240
+ if (field.type === 'bits') {
241
+ return 0;
242
+ }
243
+
244
+ if (
245
+ field.value?.kind === 'ascii' ||
246
+ field.value?.kind === 'digits' ||
247
+ field.value?.kind === 'dtmf' ||
248
+ field.value?.kind === 'bbcd'
249
+ ) {
250
+ return field.value.length;
251
+ }
252
+
253
+ return 1;
254
+ }
255
+
256
+ /**
257
+ * Chirp-style bitfields: declaration order is MSB → LSB within each byte.
258
+ */
259
+ class BitfieldCursor {
260
+ private radioAddress: number;
261
+ private bitIndex = -1;
262
+ private currentByte = 0;
263
+ private dirty = false;
264
+
265
+ constructor(
266
+ private readonly contents: Uint8Array,
267
+ private readonly memoryConfig: RadioMemoryConfig,
268
+ startRadioAddress: number,
269
+ ) {
270
+ this.radioAddress = startRadioAddress;
271
+ }
272
+
273
+ private load(): void {
274
+ if (this.bitIndex >= 0) {
275
+ return;
276
+ }
277
+
278
+ this.currentByte = readByte(this.contents, bufferOffsetFor(this.radioAddress, this.memoryConfig, this.contents));
279
+ this.bitIndex = 7;
280
+ this.dirty = false;
281
+ }
282
+
283
+ private flushByte(): void {
284
+ if (this.dirty) {
285
+ writeByte(this.contents, bufferOffsetFor(this.radioAddress, this.memoryConfig, this.contents), this.currentByte);
286
+ this.dirty = false;
287
+ }
288
+ }
289
+
290
+ read(width: number): number {
291
+ let result = 0;
292
+
293
+ for (let bit = 0; bit < width; bit += 1) {
294
+ this.load();
295
+ result = (result << 1) | ((this.currentByte >> this.bitIndex) & 1);
296
+ this.bitIndex -= 1;
297
+
298
+ if (this.bitIndex < 0) {
299
+ this.radioAddress += 1;
300
+ }
301
+ }
302
+
303
+ return result;
304
+ }
305
+
306
+ write(width: number, value: number): void {
307
+ for (let bit = width - 1; bit >= 0; bit -= 1) {
308
+ this.load();
309
+ const mask = 1 << this.bitIndex;
310
+
311
+ if ((value >> bit) & 1) {
312
+ this.currentByte |= mask;
313
+ } else {
314
+ this.currentByte &= ~mask;
315
+ }
316
+
317
+ this.dirty = true;
318
+ this.bitIndex -= 1;
319
+
320
+ if (this.bitIndex < 0) {
321
+ this.flushByte();
322
+ this.radioAddress += 1;
323
+ }
324
+ }
325
+ }
326
+
327
+ /**
328
+ * Absolute radio address of the next unused byte after this bitfield group.
329
+ */
330
+ nextRadioAddress(): number {
331
+ this.flushByte();
332
+
333
+ if (this.bitIndex >= 0) {
334
+ return this.radioAddress + 1;
335
+ }
336
+
337
+ return this.radioAddress;
338
+ }
339
+ }
340
+
341
+ function decodeStruct(
342
+ struct: RadioMemoryMapStruct,
343
+ contents: Uint8Array,
344
+ memoryConfig: RadioMemoryConfig,
345
+ instanceIndex: number,
346
+ ): Record<string, RadioSettingValue> {
347
+ const base = parseSeekAddress(struct.seek) + instanceIndex * (struct.stride ?? 0);
348
+ const result: Record<string, RadioSettingValue> = {};
349
+ let radioAddress = base;
350
+ let bitCursor: BitfieldCursor | undefined;
351
+
352
+ for (const field of struct.fields) {
353
+ if (field.type === 'bits') {
354
+ if (!bitCursor) {
355
+ bitCursor = new BitfieldCursor(contents, memoryConfig, radioAddress);
356
+ }
357
+
358
+ const raw = bitCursor.read(field.width ?? 1);
359
+
360
+ if (!field.reserved) {
361
+ result[field.id] = decodeRawValue(field.value ?? { kind: 'integer' }, raw);
362
+ }
363
+
364
+ continue;
365
+ }
366
+
367
+ if (bitCursor) {
368
+ radioAddress = bitCursor.nextRadioAddress();
369
+ bitCursor = undefined;
370
+ }
371
+
372
+ const length = fieldByteLength(field);
373
+ const bytes: number[] = [];
374
+
375
+ for (let index = 0; index < length; index += 1) {
376
+ bytes.push(readByte(contents, bufferOffsetFor(radioAddress + index, memoryConfig, contents)));
377
+ }
378
+
379
+ if (field.type === 'u16') {
380
+ const raw = bytes[0] | (bytes[1] << 8);
381
+
382
+ if (!field.reserved) {
383
+ result[field.id] = decodeRawValue(field.value ?? { kind: 'integer' }, raw);
384
+ }
385
+ } else if (!field.reserved) {
386
+ result[field.id] = decodeRawValue(field.value, length === 1 ? bytes[0] : bytes);
387
+ }
388
+
389
+ radioAddress += length;
390
+ }
391
+
392
+ return result;
393
+ }
394
+
395
+ function encodeStruct(
396
+ struct: RadioMemoryMapStruct,
397
+ values: Record<string, RadioSettingValue>,
398
+ contents: Uint8Array,
399
+ memoryConfig: RadioMemoryConfig,
400
+ instanceIndex: number,
401
+ ): void {
402
+ const base = parseSeekAddress(struct.seek) + instanceIndex * (struct.stride ?? 0);
403
+ let radioAddress = base;
404
+ let bitCursor: BitfieldCursor | undefined;
405
+ let bitStartAddress = base;
406
+
407
+ for (const field of struct.fields) {
408
+ if (field.type === 'bits') {
409
+ if (!bitCursor) {
410
+ bitStartAddress = radioAddress;
411
+ bitCursor = new BitfieldCursor(contents, memoryConfig, bitStartAddress);
412
+ }
413
+
414
+ const width = field.width ?? 1;
415
+
416
+ if (field.reserved) {
417
+ // Advance by reading existing bits (preserves memory)
418
+ bitCursor.read(width);
419
+ } else {
420
+ const encoded = encodeRawValue(field.value ?? { kind: 'integer' }, values[field.id] ?? 0, 1);
421
+ bitCursor.write(width, encoded[0]);
422
+ }
423
+
424
+ continue;
425
+ }
426
+
427
+ if (bitCursor) {
428
+ radioAddress = bitCursor.nextRadioAddress();
429
+ bitCursor = undefined;
430
+ }
431
+
432
+ const length = fieldByteLength(field);
433
+
434
+ if (field.reserved) {
435
+ radioAddress += length;
436
+ continue;
437
+ }
438
+
439
+ const settingValue = values[field.id];
440
+
441
+ if (field.type === 'u16') {
442
+ const encoded = encodeRawValue(field.value ?? { kind: 'integer' }, settingValue ?? 0, 1);
443
+ const value = encoded[0] & 0xffff;
444
+ writeByte(contents, bufferOffsetFor(radioAddress, memoryConfig, contents), value & 0xff);
445
+ writeByte(contents, bufferOffsetFor(radioAddress + 1, memoryConfig, contents), (value >> 8) & 0xff);
446
+ } else {
447
+ const encoded = encodeRawValue(field.value, settingValue ?? (field.value?.kind === 'ascii' ? '' : 0), length);
448
+
449
+ for (let index = 0; index < length; index += 1) {
450
+ writeByte(contents, bufferOffsetFor(radioAddress + index, memoryConfig, contents), encoded[index]);
451
+ }
452
+ }
453
+
454
+ radioAddress += length;
455
+ }
456
+
457
+ if (bitCursor) {
458
+ bitCursor.nextRadioAddress();
459
+ }
460
+ }
461
+
462
+ /**
463
+ * Decode radio-wide settings from a memory image using a JSON memory map.
464
+ */
465
+ export function decodeMemoryMap(
466
+ memoryMap: RadioMemoryMap,
467
+ contents: Uint8Array,
468
+ memoryConfig: RadioMemoryConfig,
469
+ ): RadioSettings {
470
+ const settings: RadioSettings = {};
471
+
472
+ for (const struct of memoryMap.structs) {
473
+ const count = struct.count ?? 1;
474
+
475
+ if (count > 1) {
476
+ const items: RadioSettingValue[] = [];
477
+
478
+ for (let index = 0; index < count; index += 1) {
479
+ items.push(decodeStruct(struct, contents, memoryConfig, index));
480
+ }
481
+
482
+ settings[struct.id] = items;
483
+ } else {
484
+ settings[struct.id] = decodeStruct(struct, contents, memoryConfig, 0);
485
+ }
486
+ }
487
+
488
+ return settings;
489
+ }
490
+
491
+ /**
492
+ * Encode radio-wide settings into an existing memory image in place.
493
+ * Returns the same buffer for convenience.
494
+ */
495
+ export function encodeMemoryMap(
496
+ memoryMap: RadioMemoryMap,
497
+ settings: RadioSettings,
498
+ contents: Uint8Array,
499
+ memoryConfig: RadioMemoryConfig,
500
+ ): Uint8Array {
501
+ for (const struct of memoryMap.structs) {
502
+ const count = struct.count ?? 1;
503
+ const value = settings[struct.id];
504
+
505
+ if (count > 1) {
506
+ const items = Array.isArray(value) ? value : [];
507
+
508
+ for (let index = 0; index < count; index += 1) {
509
+ const item = items[index];
510
+ const record =
511
+ item && typeof item === 'object' && !Array.isArray(item) ? (item as Record<string, RadioSettingValue>) : {};
512
+ encodeStruct(struct, record, contents, memoryConfig, index);
513
+ }
514
+ } else {
515
+ const record =
516
+ value && typeof value === 'object' && !Array.isArray(value) ? (value as Record<string, RadioSettingValue>) : {};
517
+ encodeStruct(struct, record, contents, memoryConfig, 0);
518
+ }
519
+ }
520
+
521
+ return contents;
522
+ }
@@ -0,0 +1,71 @@
1
+ import type { RadioMemoryMap, RadioMemoryMapFieldUi, RadioMemoryMapValueKind } from '@springfield/ham-radio-api';
2
+
3
+ /**
4
+ * Flattened field descriptor for schema-driven settings UI.
5
+ */
6
+ export interface RadioMemoryMapUiField {
7
+ /** Dot path into decoded settings, e.g. settings.squelch or pttid.0.code */
8
+ path: string;
9
+ structId: string;
10
+ fieldId: string;
11
+ arrayIndex?: number;
12
+ ui: RadioMemoryMapFieldUi;
13
+ value?: RadioMemoryMapValueKind;
14
+ }
15
+
16
+ /**
17
+ * Collect writable UI fields from a memory map, in declaration order.
18
+ */
19
+ export function collectMemoryMapUiFields(memoryMap: RadioMemoryMap): RadioMemoryMapUiField[] {
20
+ const fields: RadioMemoryMapUiField[] = [];
21
+
22
+ for (const struct of memoryMap.structs) {
23
+ const count = struct.count ?? 1;
24
+
25
+ for (let index = 0; index < count; index += 1) {
26
+ for (const field of struct.fields) {
27
+ if (field.reserved || !field.ui) {
28
+ continue;
29
+ }
30
+
31
+ const path =
32
+ count > 1 ? `${struct.id}.${index}.${field.id}` : `${struct.id}.${field.id}`;
33
+
34
+ const label =
35
+ count > 1 && field.ui.label.indexOf('%') === -1
36
+ ? `${field.ui.label} ${index + 1}`
37
+ : field.ui.label;
38
+
39
+ fields.push({
40
+ path,
41
+ structId: struct.id,
42
+ fieldId: field.id,
43
+ arrayIndex: count > 1 ? index : undefined,
44
+ ui: { ...field.ui, label },
45
+ value: field.value,
46
+ });
47
+ }
48
+ }
49
+ }
50
+
51
+ return fields;
52
+ }
53
+
54
+ /**
55
+ * Group UI fields by their ui.group key, preserving first-seen group order.
56
+ */
57
+ export function groupMemoryMapUiFields(fields: RadioMemoryMapUiField[]): Map<string, RadioMemoryMapUiField[]> {
58
+ const groups = new Map<string, RadioMemoryMapUiField[]>();
59
+
60
+ for (const field of fields) {
61
+ const existing = groups.get(field.ui.group);
62
+
63
+ if (existing) {
64
+ existing.push(field);
65
+ } else {
66
+ groups.set(field.ui.group, [field]);
67
+ }
68
+ }
69
+
70
+ return groups;
71
+ }