From 7576a4e8d1b3bdb4f63697b4cafbd671b661b348 Mon Sep 17 00:00:00 2001 From: parnic Date: Mon, 30 Nov 2026 15:43:53 -0600 Subject: [PATCH] feat(new tool): Matter QR code decoder (#604) Decode a Matter onboarding payload (the MT:... text of a Matter QR code) into its components: 11-digit manual pairing code (and the 21-digit code for non-standard commissioning flows), passcode and its validity, discriminator and short discriminator, vendor and product IDs, commissioning flow, discovery capabilities, payload version, raw bytes and the optional TLV data. QR codes holding several devices (payloads joined with '*') are decoded one card per device. Co-authored-by: Claude Opus 5.5 Co-authored-by: sharevb --- locales/en.yml | 26 ++ src/tools/matter-qr-code-decoder/index.ts | 28 ++ .../matter-qr-code-decoder.service.test.ts | 134 ++++++ .../matter-qr-code-decoder.service.ts | 431 ++++++++++++++++++ .../matter-qr-code-decoder.vue | 140 ++++++ 5 files changed, 759 insertions(+) create mode 100644 src/tools/matter-qr-code-decoder/index.ts create mode 100644 src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.test.ts create mode 100644 src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.ts create mode 100644 src/tools/matter-qr-code-decoder/matter-qr-code-decoder.vue diff --git a/locales/en.yml b/locales/en.yml index 3c84bfed..36031787 100644 --- a/locales/en.yml +++ b/locales/en.yml @@ -10385,6 +10385,32 @@ tools: label-input-key: Input Key placeholder-paste-ssh-key-here: Paste SSH key here... title-output-key: Output Key + matter-qr-code-decoder: + title: Matter QR code decoder + description: >- + Decode a Matter onboarding payload (MT:... QR code text) into its + components: manual pairing code, passcode, discriminator, vendor and + product IDs, discovery capabilities and optional data. + texts: + label-matter-qr-code-payload: Matter QR code payload + placeholder-matter-qr-code-payload: 'MT:...' + hint-qr-code-decoder: 'Only have the QR code image? Read its text with the' + link-qr-code-decoder: QR Code Decoder + title-device: 'Device {0}' + title-optional-data: Optional data + label-manual-pairing-code: Manual pairing code + label-long-manual-pairing-code: Manual pairing code (with vendor/product ID) + label-passcode: Passcode (setup PIN) + label-discriminator: Discriminator + label-short-discriminator: Short discriminator + label-vendor-id: Vendor ID + label-product-id: Product ID + label-commissioning-flow: Commissioning flow + label-discovery-capabilities: Discovery capabilities + label-version: Version + label-raw-payload: Raw payload (hex) + test-vendor: test vendor + none: None analogSignalConverter: texts: title-input: Input diff --git a/src/tools/matter-qr-code-decoder/index.ts b/src/tools/matter-qr-code-decoder/index.ts new file mode 100644 index 00000000..04e33f82 --- /dev/null +++ b/src/tools/matter-qr-code-decoder/index.ts @@ -0,0 +1,28 @@ +import { defineTool } from '../tool'; +import { translate as t } from '@/plugins/i18n.plugin'; + +export const tool = defineTool({ + name: t('tools.matter-qr-code-decoder.title'), + path: '/matter-qr-code-decoder', + description: t('tools.matter-qr-code-decoder.description'), + keywords: [ + 'matter', + 'qrcode', + 'qr-code', + 'decoder', + 'onboarding', + 'payload', + 'pairing', + 'setup', + 'code', + 'discriminator', + 'passcode', + 'smart', + 'home', + 'iot', + ], + component: () => import('./matter-qr-code-decoder.vue'), + icon: defineAsyncComponent(() => import('@vicons/tabler/es/Qrcode')), + createdAt: new Date('2026-11-28'), + category: 'Barcodes', +}); diff --git a/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.test.ts b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.test.ts new file mode 100644 index 00000000..44e46be9 --- /dev/null +++ b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.test.ts @@ -0,0 +1,134 @@ +import { describe, expect, it } from 'vitest'; +import { + base38Decode, + base38Encode, + computeManualPairingCode, + decodeMatterQrPayload, + encodeMatterQrPayload, + formatManualPairingCode, + isValidPasscode, + verhoeffCheckDigit, +} from './matter-qr-code-decoder.service'; + +// Default payloads of the Matter SDK example devices. +const SDK_EXAMPLE = 'MT:-24J0AFN00KA0648G00'; +const SDK_EXAMPLE_BLE = 'MT:Y.K9042C00KA0648G00'; +const SDK_EXAMPLE_FIELDS = { + vendorId: 0xfff1, + productId: 0x8001, + commissioningFlow: 0, + discoveryCapabilities: 4, + discriminator: 3840, + passcode: 20202021, +}; + +describe('matter-qr-code-decoder', () => { + it('decodes the Matter SDK example payload', () => { + const [payload] = decodeMatterQrPayload(SDK_EXAMPLE); + expect(payload).toMatchObject({ + version: 0, + vendorId: 0xfff1, + productId: 0x8001, + commissioningFlow: 0, + commissioningFlowName: 'Standard', + discoveryCapabilities: 4, + discoveryCapabilityNames: ['On IP network'], + discriminator: 3840, + shortDiscriminator: 15, + passcode: 20202021, + isPasscodeValid: true, + manualPairingCode: '34970112332', + longManualPairingCode: null, + optionalData: [], + rawHex: '88FF0F008400E04B846802', + warnings: [], + }); + expect(decodeMatterQrPayload(SDK_EXAMPLE_BLE)[0]).toMatchObject({ + productId: 0x8000, + discoveryCapabilityNames: ['BLE'], + manualPairingCode: '34970112332', + }); + }); + + it('accepts lowercase input and surrounding whitespace', () => { + expect(decodeMatterQrPayload(` ${SDK_EXAMPLE.toLowerCase()}\n`)[0].passcode).toBe(20202021); + }); + + it('decodes concatenated payloads', () => { + const second = encodeMatterQrPayload({ + vendorId: 0x1234, + productId: 0x5678, + commissioningFlow: 0, + discoveryCapabilities: 4, + discriminator: 0x123, + passcode: 12345679, + }); + const payloads = decodeMatterQrPayload(`${SDK_EXAMPLE}*${second.slice(3)}`); + expect(payloads).toHaveLength(2); + expect(payloads[1]).toMatchObject({ vendorId: 0x1234, productId: 0x5678, discriminator: 0x123 }); + }); + + it('round-trips encode and decode', () => { + const fields = { + vendorId: 0xabcd, + productId: 0x0042, + commissioningFlow: 2, + discoveryCapabilities: 0b111, + discriminator: 0xabc, + passcode: 99999998, + }; + expect(encodeMatterQrPayload(SDK_EXAMPLE_FIELDS)).toBe(SDK_EXAMPLE); + const [payload] = decodeMatterQrPayload(encodeMatterQrPayload(fields)); + expect(payload).toMatchObject({ + ...fields, + commissioningFlowName: 'Custom', + discoveryCapabilityNames: ['SoftAP', 'BLE', 'On IP network'], + }); + // 10 digits of discriminator/passcode, vendor ID, product ID, check digit + expect(payload.longManualPairingCode).toBe('641214610343981000666'); + expect(formatManualPairingCode(payload.longManualPairingCode!)).toBe('6412-146-1034-39810-00666'); + }); + + it('parses optional TLV data', () => { + const fixed = base38Decode(SDK_EXAMPLE.slice(3)); + const serial = new TextEncoder().encode('SN-001'); + const tlv = [0x15, 0x2c, 0x00, serial.length, ...serial, 0x24, 0x80, 0x2a, 0x18]; + const [payload] = decodeMatterQrPayload(`MT:${base38Encode(Uint8Array.from([...fixed, ...tlv]))}`); + expect(payload.optionalData).toEqual([ + { tag: 'Context 0x00', tagNumber: 0, name: 'Serial number', type: 'UTF-8 string', value: 'SN-001' }, + { + tag: 'Context 0x80', + tagNumber: 0x80, + name: 'Vendor-specific (0x80)', + type: 'Unsigned int (8 bits)', + value: '42', + }, + ]); + }); + + it('reports invalid passcodes and versions', () => { + const [payload] = decodeMatterQrPayload( + encodeMatterQrPayload({ ...SDK_EXAMPLE_FIELDS, version: 1, passcode: 12345678 }), + ); + expect(payload.isPasscodeValid).toBe(false); + expect(payload.warnings).toHaveLength(2); + }); + + it('rejects malformed input', () => { + expect(() => decodeMatterQrPayload('')).toThrow(); + expect(() => decodeMatterQrPayload('XX:-24J0AFN00KA0648G00')).toThrow(/MT:/); + expect(() => decodeMatterQrPayload('MT:')).toThrow(); + expect(() => decodeMatterQrPayload('MT:-24J0AFN00KA0648G0')).toThrow(/length/); + expect(() => decodeMatterQrPayload('MT:-24J0AFN00KA0648G0_')).toThrow(/character/); + expect(() => decodeMatterQrPayload('MT:-24J0')).toThrow(/too short/); + }); + + it('computes manual pairing codes', () => { + expect(computeManualPairingCode({ discriminator: 3840, passcode: 20202021 })).toBe('34970112332'); + expect(formatManualPairingCode('34970112332')).toBe('3497-011-2332'); + expect(verhoeffCheckDigit('236')).toBe(3); + expect(isValidPasscode(20202021)).toBe(true); + expect(isValidPasscode(11111111)).toBe(false); + expect(isValidPasscode(99999999)).toBe(false); + }); +}); diff --git a/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.ts b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.ts new file mode 100644 index 00000000..ff149538 --- /dev/null +++ b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.service.ts @@ -0,0 +1,431 @@ +// Matter onboarding payload decoder (Matter Core Specification, section 5.1 "Onboarding Payload"). +// +// A Matter QR code contains the text "MT:" followed by a Base-38 encoded bit stream. The +// first 88 bits hold fixed-width fields packed least significant bit first; any remaining +// bytes are optional data encoded as Matter TLV. Several payloads may be concatenated +// with '*' in a single QR code (one per device). + +export const MATTER_QR_PREFIX = 'MT:'; + +const BASE38_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-.'; +// Number of Base-38 characters produced for a chunk of 1, 2 or 3 bytes. +const BASE38_CHARS_PER_CHUNK = [2, 4, 5]; +const BASE38_CHUNK_CHARS = 5; +const BASE38_CHUNK_BYTES = 3; + +// Field widths in bits, in payload order. +const FIELDS = [ + ['version', 3], + ['vendorId', 16], + ['productId', 16], + ['commissioningFlow', 2], + ['discoveryCapabilities', 8], + ['discriminator', 12], + ['passcode', 27], + ['padding', 4], +] as const; +type FieldName = (typeof FIELDS)[number][0]; +const FIXED_PAYLOAD_BYTES = 11; // 88 bits + +export const COMMISSIONING_FLOWS = ['Standard', 'User intent', 'Custom', 'Reserved'] as const; + +export const DISCOVERY_CAPABILITY_FLAGS = [ + { bit: 0, name: 'SoftAP' }, + { bit: 1, name: 'BLE' }, + { bit: 2, name: 'On IP network' }, + { bit: 3, name: 'Wi-Fi Public Action Frame' }, + { bit: 4, name: 'NFC' }, +] as const; + +// Well-known tags of the optional TLV data (context-specific tags). +const OPTIONAL_DATA_TAGS: Record = { + 0x00: 'Serial number', + 0x01: 'PBKDF iterations', + 0x02: 'PBKDF salt', + 0x03: 'Number of devices', + 0x04: 'Commissioning timeout (s)', +}; + +const INVALID_PASSCODES = new Set([ + 0, 11111111, 22222222, 33333333, 44444444, 55555555, 66666666, 77777777, 88888888, 99999999, 12345678, 87654321, +]); +const MAX_PASSCODE = 99999998; + +export interface MatterOptionalDataElement { + tag: string; + tagNumber: number | null; + name: string; + type: string; + value: string; +} + +export interface MatterPayload { + version: number; + vendorId: number; + productId: number; + commissioningFlow: number; + commissioningFlowName: string; + discoveryCapabilities: number; + discoveryCapabilityNames: string[]; + discriminator: number; + shortDiscriminator: number; + passcode: number; + padding: number; + isPasscodeValid: boolean; + manualPairingCode: string; + longManualPairingCode: string | null; + optionalData: MatterOptionalDataElement[]; + rawHex: string; + warnings: string[]; +} + +export function base38Decode(text: string): Uint8Array { + const bytes: number[] = []; + for (let start = 0; start < text.length; start += BASE38_CHUNK_CHARS) { + const chunk = text.slice(start, start + BASE38_CHUNK_CHARS); + const byteCount = BASE38_CHARS_PER_CHUNK.indexOf(chunk.length) + 1; + if (byteCount === 0) { + throw new Error(`Invalid Base-38 length: ${text.length} characters`); + } + let value = 0; + for (let i = chunk.length - 1; i >= 0; i--) { + const digit = BASE38_ALPHABET.indexOf(chunk[i]); + if (digit < 0) { + throw new Error(`Invalid Base-38 character: '${chunk[i]}'`); + } + value = value * 38 + digit; + } + if (value >= 2 ** (8 * byteCount)) { + throw new Error(`Invalid Base-38 chunk: '${chunk}'`); + } + for (let i = 0; i < byteCount; i++) { + bytes.push(value & 0xff); + value = Math.floor(value / 256); + } + } + return Uint8Array.from(bytes); +} + +export function base38Encode(bytes: Uint8Array): string { + let text = ''; + for (let start = 0; start < bytes.length; start += BASE38_CHUNK_BYTES) { + const chunk = bytes.slice(start, start + BASE38_CHUNK_BYTES); + let value = 0; + for (let i = chunk.length - 1; i >= 0; i--) { + value = value * 256 + chunk[i]; + } + for (let i = 0; i < BASE38_CHARS_PER_CHUNK[chunk.length - 1]; i++) { + text += BASE38_ALPHABET[value % 38]; + value = Math.floor(value / 38); + } + } + return text; +} + +function readBits(bytes: Uint8Array, offset: number, count: number): number { + let value = 0; + for (let i = count - 1; i >= 0; i--) { + const bit = offset + i; + value = value * 2 + ((bytes[bit >> 3] >> (bit & 7)) & 1); + } + return value; +} + +function writeBits(bytes: Uint8Array, offset: number, count: number, value: number) { + for (let i = 0; i < count; i++) { + const bit = offset + i; + if (Math.floor(value / 2 ** i) % 2) { + bytes[bit >> 3] |= 1 << (bit & 7); + } + } +} + +// Verhoeff check digit, as used by the Matter manual pairing code. +const VERHOEFF_D = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 2, 3, 4, 0, 6, 7, 8, 9, 5], + [2, 3, 4, 0, 1, 7, 8, 9, 5, 6], + [3, 4, 0, 1, 2, 8, 9, 5, 6, 7], + [4, 0, 1, 2, 3, 9, 5, 6, 7, 8], + [5, 9, 8, 7, 6, 0, 4, 3, 2, 1], + [6, 5, 9, 8, 7, 1, 0, 4, 3, 2], + [7, 6, 5, 9, 8, 2, 1, 0, 4, 3], + [8, 7, 6, 5, 9, 3, 2, 1, 0, 4], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], +]; +const VERHOEFF_P = [ + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [1, 5, 7, 6, 2, 8, 3, 0, 9, 4], + [5, 8, 0, 3, 7, 9, 6, 1, 4, 2], + [8, 9, 1, 6, 0, 4, 3, 5, 2, 7], + [9, 4, 5, 3, 1, 2, 6, 8, 7, 0], + [4, 2, 8, 6, 5, 7, 3, 9, 0, 1], + [2, 7, 9, 3, 8, 0, 6, 4, 1, 5], + [7, 0, 4, 6, 9, 1, 3, 2, 5, 8], +]; +const VERHOEFF_INV = [0, 4, 3, 2, 1, 5, 6, 7, 8, 9]; + +export function verhoeffCheckDigit(digits: string): number { + let c = 0; + for (let i = 0; i < digits.length; i++) { + const digit = Number(digits[digits.length - 1 - i]); + c = VERHOEFF_D[c][VERHOEFF_P[(i + 1) % 8][digit]]; + } + return VERHOEFF_INV[c]; +} + +export function computeManualPairingCode({ + discriminator, + passcode, + vendorId, + productId, + includeVendorAndProduct = false, +}: { + discriminator: number; + passcode: number; + vendorId?: number; + productId?: number; + includeVendorAndProduct?: boolean; +}): string { + const shortDiscriminator = (discriminator >> 8) & 0xf; + const chunk1 = ((includeVendorAndProduct ? 1 : 0) << 2) | (shortDiscriminator >> 2); + const chunk2 = ((shortDiscriminator & 0x3) << 14) | (passcode & 0x3fff); + const chunk3 = Math.floor(passcode / 2 ** 14) & 0x1fff; + let code = `${chunk1}${String(chunk2).padStart(5, '0')}${String(chunk3).padStart(4, '0')}`; + if (includeVendorAndProduct) { + code += `${String(vendorId ?? 0).padStart(5, '0')}${String(productId ?? 0).padStart(5, '0')}`; + } + return code + verhoeffCheckDigit(code); +} + +export function formatManualPairingCode(code: string): string { + // 11 digits: XXXX-XXX-XXXX, 21 digits: XXXX-XXX-XXXX-XXXXX-XXXXX + const groups = code.length === 21 ? [4, 3, 4, 5, 5] : [4, 3, 4]; + const parts: string[] = []; + let index = 0; + for (const size of groups) { + parts.push(code.slice(index, index + size)); + index += size; + } + return parts.filter(Boolean).join('-'); +} + +export function isValidPasscode(passcode: number): boolean { + return passcode >= 1 && passcode <= MAX_PASSCODE && !INVALID_PASSCODES.has(passcode); +} + +function toHex(value: number, width: number) { + return `0x${value.toString(16).toUpperCase().padStart(width, '0')}`; +} + +function bytesToHex(bytes: Uint8Array) { + return Array.from(bytes, (b) => b.toString(16).toUpperCase().padStart(2, '0')).join(''); +} + +// Minimal Matter TLV reader (Matter Core Specification, Appendix A), enough to list the +// elements of the onboarding payload optional data. +function parseTlv(bytes: Uint8Array): MatterOptionalDataElement[] { + const elements: MatterOptionalDataElement[] = []; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let pos = 0; + let depth = 0; + + const need = (n: number) => { + if (pos + n > bytes.length) { + throw new Error('Truncated TLV data'); + } + }; + const readUint = (size: number): bigint => { + need(size); + let value = 0n; + for (let i = size - 1; i >= 0; i--) { + value = (value << 8n) | BigInt(bytes[pos + i]); + } + pos += size; + return value; + }; + + while (pos < bytes.length) { + const control = bytes[pos++]; + const tagControl = control >> 5; + const elementType = control & 0x1f; + + let tag = 'Anonymous'; + let tagNumber: number | null = null; + const tagSizes = [0, 1, 2, 4, 2, 4, 6, 8]; + const tagSize = tagSizes[tagControl]; + if (tagControl === 1) { + tagNumber = Number(readUint(1)); + tag = `Context ${toHex(tagNumber, 2)}`; + } else if (tagSize > 0) { + tag = `Tag ${readUint(tagSize).toString(16).toUpperCase()}`; + } + + if (elementType === 0x18) { + depth--; + continue; + } + + let type: string; + let value: string; + if (elementType <= 0x03) { + const size = 1 << elementType; + need(size); + const signed = BigInt.asIntN(size * 8, readUint(size)); + type = `Signed int (${size * 8} bits)`; + value = signed.toString(); + } else if (elementType <= 0x07) { + const size = 1 << (elementType - 4); + type = `Unsigned int (${size * 8} bits)`; + value = readUint(size).toString(); + } else if (elementType === 0x08 || elementType === 0x09) { + type = 'Boolean'; + value = String(elementType === 0x09); + } else if (elementType === 0x0a) { + need(4); + type = 'Float'; + value = String(view.getFloat32(pos, true)); + pos += 4; + } else if (elementType === 0x0b) { + need(8); + type = 'Double'; + value = String(view.getFloat64(pos, true)); + pos += 8; + } else if (elementType <= 0x13) { + const isString = elementType <= 0x0f; + const length = Number(readUint(1 << ((elementType - (isString ? 0x0c : 0x10)) & 3))); + need(length); + const data = bytes.slice(pos, pos + length); + pos += length; + type = isString ? 'UTF-8 string' : 'Byte string'; + value = isString ? new TextDecoder().decode(data) : bytesToHex(data); + } else if (elementType === 0x14) { + type = 'Null'; + value = 'null'; + } else if (elementType >= 0x15 && elementType <= 0x17) { + // Containers: the onboarding payload wraps its optional data in an anonymous + // structure; its members are listed flat. + depth++; + if (depth === 1 && tagControl === 0) { + continue; + } + type = ['Structure', 'Array', 'List'][elementType - 0x15]; + value = ''; + } else { + throw new Error(`Invalid TLV element type: ${toHex(elementType, 2)}`); + } + + let name = tag; + if (tagNumber !== null) { + name = OPTIONAL_DATA_TAGS[tagNumber] ?? (tagNumber >= 0x80 ? `Vendor-specific (${toHex(tagNumber, 2)})` : tag); + } + elements.push({ tag, tagNumber, name, type, value }); + } + return elements; +} + +function decodeSinglePayload(base38: string): MatterPayload { + const bytes = base38Decode(base38); + if (bytes.length < FIXED_PAYLOAD_BYTES) { + throw new Error(`Payload too short: ${bytes.length} bytes, at least ${FIXED_PAYLOAD_BYTES} expected`); + } + + const fields = {} as Record; + let offset = 0; + for (const [name, size] of FIELDS) { + fields[name] = readBits(bytes, offset, size); + offset += size; + } + + const warnings: string[] = []; + if (fields.version !== 0) { + warnings.push(`Unsupported payload version ${fields.version} (only version 0 is defined)`); + } + if (fields.padding !== 0) { + warnings.push('Padding bits are not zero'); + } + const isPasscodeValid = isValidPasscode(fields.passcode); + if (!isPasscodeValid) { + warnings.push(`Passcode ${fields.passcode} is not allowed by the Matter specification`); + } + + let optionalData: MatterOptionalDataElement[] = []; + if (bytes.length > FIXED_PAYLOAD_BYTES) { + try { + optionalData = parseTlv(bytes.slice(FIXED_PAYLOAD_BYTES)); + } catch (error: any) { + warnings.push(`Unable to parse optional data: ${error.message}`); + } + } + + const manualParams = { + discriminator: fields.discriminator, + passcode: fields.passcode, + vendorId: fields.vendorId, + productId: fields.productId, + }; + + return { + version: fields.version, + vendorId: fields.vendorId, + productId: fields.productId, + commissioningFlow: fields.commissioningFlow, + commissioningFlowName: COMMISSIONING_FLOWS[fields.commissioningFlow], + discoveryCapabilities: fields.discoveryCapabilities, + discoveryCapabilityNames: [ + ...DISCOVERY_CAPABILITY_FLAGS.filter(({ bit }) => fields.discoveryCapabilities & (1 << bit)).map( + ({ name }) => name, + ), + ...(fields.discoveryCapabilities & 0xe0 + ? [`Reserved bits ${toHex(fields.discoveryCapabilities & 0xe0, 2)}`] + : []), + ], + discriminator: fields.discriminator, + shortDiscriminator: fields.discriminator >> 8, + passcode: fields.passcode, + padding: fields.padding, + isPasscodeValid, + manualPairingCode: computeManualPairingCode(manualParams), + // Devices with a non-standard commissioning flow use the 21-digit code, which + // also carries the vendor and product IDs. + longManualPairingCode: + fields.commissioningFlow !== 0 + ? computeManualPairingCode({ ...manualParams, includeVendorAndProduct: true }) + : null, + optionalData, + rawHex: bytesToHex(bytes), + warnings, + }; +} + +export function decodeMatterQrPayload(input: string): MatterPayload[] { + const text = input.trim().toUpperCase(); + if (!text.startsWith(MATTER_QR_PREFIX)) { + throw new Error(`A Matter QR code payload must start with '${MATTER_QR_PREFIX}'`); + } + const body = text.slice(MATTER_QR_PREFIX.length); + if (!body) { + throw new Error('Empty Matter QR code payload'); + } + return body.split('*').map((part) => decodeSinglePayload(part)); +} + +export function encodeMatterQrPayload( + payload: Pick< + MatterPayload, + 'vendorId' | 'productId' | 'commissioningFlow' | 'discoveryCapabilities' | 'discriminator' | 'passcode' + > & { version?: number }, +): string { + const bytes = new Uint8Array(FIXED_PAYLOAD_BYTES); + const values: Record = { version: 0, padding: 0, ...payload }; + let offset = 0; + for (const [name, size] of FIELDS) { + writeBits(bytes, offset, size, values[name]); + offset += size; + } + return MATTER_QR_PREFIX + base38Encode(bytes); +} + +export function formatHex(value: number, width: number) { + return toHex(value, width); +} diff --git a/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.vue b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.vue new file mode 100644 index 00000000..305b5db2 --- /dev/null +++ b/src/tools/matter-qr-code-decoder/matter-qr-code-decoder.vue @@ -0,0 +1,140 @@ + + +