cards: read EF.ICCID at equip and auto-select the matching preset (v2.2.16)

- Server: _decode_iccid (nibble-swapped E.118 digits, trailing-F pad) and
  _read_iccid (best-effort MF/2FE2 read through the parent-scoped select
  helper; the previous selection is restored, the read never raises). The
  equip path records the digit string before the TERMINAL PROFILE, i.e.
  before any CAT session is active; a startup with a card does the same.
  The value is cleared on card removal and exposed as /api/status 'iccid'
  (only while connected).
- PWA: when a connected status update reports a *new* ICCID, the matching
  card preset is selected in both SCP80 views - Secured Packet (sp-card-sel
  + form fill) and RAM (ram-card-sel + _ramCardIdx). Matching normalizes
  digits and accepts the raw EF hex form, leading zeros ignored; a manual
  choice for the same card is kept until the next equip, and a card removal
  re-arms the auto-selection. The status line shows the ICCID.
- Tests: tests/test_iccid.py (decode variants, model + probe read, equip
  recording, disconnect clearing) and frontend/tests/cards_iccid.test.js
  (normalize, find, select, no-override, card swap); the card_state test
  harness stubs the new hook and covers the guard reset.
- Docs: api.md /api/status fields, help EN+RU (SCP80 intro + Cards tab),
  READMEs, AGENTS. SW cache otaman-v183.
This commit is contained in:
2026-09-18 21:05:25 +03:00
parent ab91fcff54
commit 6d5d23487a
13 changed files with 400 additions and 17 deletions
+2 -2
View File
@@ -241,7 +241,7 @@
<section class="mb-10">
<h2 id="scp80" class="text-xl font-semibold mb-3 border-b border-gray-300 dark:border-slate-700 pb-1">3. Вкладка SCP80</h2>
<p class="mb-3">Верхнеуровневая вкладка <strong>SCP80</strong> объединяет разделы, связанные с SCP80. Переключение — двумя переключателями: <strong>Secured Packet</strong> и <strong>RAM</strong>. Собирает защищённые пакеты SCP80 по ETSI TS 102 225.</p>
<p class="mb-3">Верхнеуровневая вкладка <strong>SCP80</strong> объединяет разделы, связанные с SCP80. Переключение — двумя переключателями: <strong>Secured Packet</strong> и <strong>RAM</strong>. Собирает защищённые пакеты SCP80 по ETSI TS 102 225. При подключении карты сервер читает её <strong>EF.ICCID</strong> (2FE2); если в предустановке указан тот же номер (цифрами или сырым hex из EF), она автоматически выбирается в обоих представлениях.</p>
<h3 id="secured-packet" class="text-lg font-medium mb-2">3.1 Secured Packet</h3>
<p class="mb-2">Собирает защищённые пакеты SCP80 по ETSI TS 102 225.</p>
@@ -298,7 +298,7 @@
<section class="mb-10">
<h2 id="cards" class="text-xl font-semibold mb-3 border-b border-gray-300 dark:border-slate-700 pb-1">4. Вкладка &laquo;Карты&raquo;</h2>
<p class="mb-2">Хранит предустановки карт локально в браузере (<code class="font-mono text-sm">localStorage</code>), чтобы представление Secured Packet могло автоматически подставлять ключи и параметры, а слушатель SCP81 HTTP OTA — находить PSK-ключи. &laquo;Карты&raquo; — верхнеуровневая вкладка.</p>
<p class="mb-2">Хранит предустановки карт локально в браузере (<code class="font-mono text-sm">localStorage</code>), чтобы представление Secured Packet могло автоматически подставлять ключи и параметры, а слушатель SCP81 HTTP OTA — находить PSK-ключи. &laquo;Карты&raquo; — верхнеуровневая вкладка. При подключении карты читается её EF.ICCID, и предустановка с тем же ICCID автоматически выбирается в обоих представлениях SCP80.</p>
<table class="w-full text-sm mb-3 border-collapse">
<thead><tr class="border-b border-gray-300 dark:border-slate-700"><th class="text-left py-1 px-2">Поле</th><th class="text-left py-1 px-2">Описание</th></tr></thead>
<tbody>
+2 -2
View File
@@ -241,7 +241,7 @@
<section class="mb-10">
<h2 id="scp80" class="text-xl font-semibold mb-3 border-b border-gray-300 dark:border-slate-700 pb-1">3. SCP80 tab</h2>
<p class="mb-3">The <strong>SCP80</strong> top-level tab groups the SCP80-related views. It is switched by two pills: <strong>Secured Packet</strong> and <strong>RAM</strong>. Assembles SCP80 secured packets per ETSI TS 102 225.</p>
<p class="mb-3">The <strong>SCP80</strong> top-level tab groups the SCP80-related views. It is switched by two pills: <strong>Secured Packet</strong> and <strong>RAM</strong>. Assembles SCP80 secured packets per ETSI TS 102 225. When a card is equipped the server reads its <strong>EF.ICCID</strong> (2FE2); if a card preset carries the same number (digits, or the raw EF hex), it is selected automatically in both views.</p>
<h3 id="secured-packet" class="text-lg font-medium mb-2">3.1 Secured Packet</h3>
<p class="mb-2">Builds SCP80 secured packets per ETSI TS 102 225.</p>
@@ -298,7 +298,7 @@
<section class="mb-10">
<h2 id="cards" class="text-xl font-semibold mb-3 border-b border-gray-300 dark:border-slate-700 pb-1">4. Cards tab</h2>
<p class="mb-2">Stores card presets locally in the browser (<code class="font-mono text-sm">localStorage</code>) so the Secured Packet view can auto-fill keys and parameters, and so the SCP81 HTTP OTA listener can look up PSK keys. Cards is a top-level tab.</p>
<p class="mb-2">Stores card presets locally in the browser (<code class="font-mono text-sm">localStorage</code>) so the Secured Packet view can auto-fill keys and parameters, and so the SCP81 HTTP OTA listener can look up PSK keys. Cards is a top-level tab. When the card is equipped its EF.ICCID is read and the preset with the same ICCID is selected automatically in both SCP80 views.</p>
<table class="w-full text-sm mb-3 border-collapse">
<thead><tr class="border-b border-gray-300 dark:border-slate-700"><th class="text-left py-1 px-2">Field</th><th class="text-left py-1 px-2">Description</th></tr></thead>
<tbody>
+42 -1
View File
@@ -18,7 +18,7 @@
<div class="max-w-7xl mx-auto px-6 py-2">
<div class="flex items-center justify-between mb-3">
<h1 class="text-2xl font-bold text-heading">OTAMan <span id="slogan" class="text-sm font-normal text-gray-500 dark:text-slate-400 ml-2" data-l10n="SIM OTA with a Human Face">SIM OTA with a Human Face</span> <span class="text-xs text-gray-400 dark:text-slate-500 ml-1">v2.2.15</span></h1>
<h1 class="text-2xl font-bold text-heading">OTAMan <span id="slogan" class="text-sm font-normal text-gray-500 dark:text-slate-400 ml-2" data-l10n="SIM OTA with a Human Face">SIM OTA with a Human Face</span> <span class="text-xs text-gray-400 dark:text-slate-500 ml-1">v2.2.16</span></h1>
<div class="flex items-center gap-4">
<span id="state-indicator" class="flex items-center select-none" style="cursor:default" title="Connecting...">
<span id="state-indicator-dot" class="text-xs text-gray-400" title="Connecting..."></span>
@@ -4859,6 +4859,7 @@ async function pysimRefresh() {
(data.sel_ctrl ? ' | SEL: <b>' + esc(data.sel_ctrl) + '</b>' : '') +
' | Channels: <b>' + (data.channels && data.channels.length ? data.channels.join(', ') : 'none') + '</b><br>' +
'ADM: <b>' + (data.adm_verified ? 'verified' : 'not verified') + '</b>' +
(data.iccid ? ' | ICCID: <b>' + esc(data.iccid) + '</b>' : '') +
' | Selection: <b>' + (data.current_selection
? (data.current_selection.name || data.current_selection.fid || '?')
: 'none') + '</b>' +
@@ -6114,6 +6115,44 @@ function cardsRebuildSelect() {
if (prev !== '' && cards[parseInt(prev, 10)]) sel.value = prev;
}
// ===== ICCID-based preset auto-selection =====
// After every equip /api/status carries the card's EF.ICCID (2FE2); when a
// preset holds the same number it is selected in both SCP80 views (Secured
// packet + RAM). Users may store the ICCID as digits or as the raw EF hex,
// so both forms are normalized to plain digits.
function cardsNormIccid(v) {
let s = String(v == null ? '' : v).trim().toUpperCase().replace(/[\s-]/g, '');
if (!s) return '';
if (/[A-F]/.test(s)) s = decIccid(s); // raw EF content (nibble-swapped)
return String(s || '').replace(/\D/g, '').replace(/^0+/, '');
}
function cardsFindByIccid(iccid) {
const norm = cardsNormIccid(iccid);
if (!norm) return -1;
return cards.findIndex(c => cardsNormIccid(c.iccid) === norm);
}
let _cardsAutoIccid = null;
function cardsAutoSelectByIccid(iccid) {
// Act only when the equip reports a *new* ICCID: a manual preset choice
// for the same card must not be overridden by later status updates.
const norm = cardsNormIccid(iccid);
if (!norm) { _cardsAutoIccid = null; return -1; }
if (norm === _cardsAutoIccid) return -1;
_cardsAutoIccid = norm;
const idx = cardsFindByIccid(norm);
if (idx < 0) return -1;
const sp = document.getElementById('sp-card-sel');
if (sp) sp.value = String(idx);
const ram = document.getElementById('ram-card-sel');
if (ram) ram.value = String(idx);
_ramCardIdx = idx;
cardsApply(String(idx));
return idx;
}
function cardsApply(idx) {
const c = cards[parseInt(idx)];
if (!c) return;
@@ -7622,9 +7661,11 @@ function pysimCardStateUpdate(status) {
if (status.connected) {
pysimSetConnected(true);
pysimResetCardData(true);
cardsAutoSelectByIccid(status.iccid);
return;
}
pysimSetConnected(false);
_cardsAutoIccid = null;
const statusEl = document.getElementById('pysim-status');
if (statusEl && statusEl.textContent.trim() !== '') {
if (status.equipping || (status.card_present && status.auto_equip)) {
+1 -1
View File
@@ -1,4 +1,4 @@
const CACHE = 'otaman-v182';
const CACHE = 'otaman-v183';
const URLS = [
'index.html',
'help.html',
+14 -3
View File
@@ -23,7 +23,8 @@ function extractFunc(src, name) {
let code = 'var _pysimCardStateKey = null;\nvar _pysimCardSession = null;\n'
+ 'var _pysimServerAvailable = null;\nvar _pysimCardEquipped = false;\n'
+ 'var _pysimProactiveSeq = null;\nvar _pysimStkSig = null;\nvar _pysimAdmVerified = null;\n';
+ 'var _pysimProactiveSeq = null;\nvar _pysimStkSig = null;\nvar _pysimAdmVerified = null;\n'
+ 'var _cardsAutoIccid = null;\n';
code += extractFunc(html, 'pysimCardStateUpdate') + '\n';
code += extractFunc(html, 'pysimAvailabilityState') + '\n';
code += extractFunc(html, 'pysimControlDisabled') + '\n';
@@ -53,12 +54,13 @@ function fakeIndicator() {
function setup() {
const el = { textContent: 'status line', innerHTML: '' };
const adm = fakeIndicator();
const calls = { connected: [], resets: [], refreshStatus: [], proactive: 0 };
const calls = { connected: [], resets: [], refreshStatus: [], proactive: 0, autoIccid: [] };
_pysimCardStateKey = null;
_pysimCardSession = null;
_pysimProactiveSeq = null;
_pysimAdmVerified = null;
_pysimServerAvailable = null;
_cardsAutoIccid = null;
globalThis.document = {
getElementById: id => id === 'state-indicator-adm' ? adm : el,
querySelectorAll: () => [],
@@ -68,6 +70,7 @@ function setup() {
globalThis.pysimApplyAvailability = () => {};
globalThis.isViewVisible = () => true;
globalThis.pysimProactiveLogRender = () => { calls.proactive++; };
globalThis.cardsAutoSelectByIccid = iccid => { calls.autoIccid.push(iccid); return -1; };
return { el, adm, calls };
}
@@ -106,9 +109,17 @@ test('unchanged state key does not touch the UI again', () => {
test('connected restores the UI and reloads card data', () => {
const { calls } = setup();
pysimCardStateUpdate(status({ connected: true, card_present: true, card_session: 2 }));
pysimCardStateUpdate(status({ connected: true, card_present: true, card_session: 2, iccid: '8970119000004600098' }));
assert.deepStrictEqual(calls.connected, [true]);
assert.deepStrictEqual(calls.resets, [true]);
assert.deepStrictEqual(calls.autoIccid, ['8970119000004600098']);
});
test('a disconnect clears the ICCID auto-selection guard', () => {
setup();
_cardsAutoIccid = '8970119000004600098';
pysimCardStateUpdate(status({ connected: false, card_present: false, card_session: 5 }));
assert.strictEqual(_cardsAutoIccid, null);
});
test('card session change triggers a data reset', () => {
+111
View File
@@ -0,0 +1,111 @@
const { test } = require('node:test');
const assert = require('node:assert');
const fs = require('node:fs');
const path = require('node:path');
const html = fs.readFileSync(path.join(__dirname, '..', 'index.html'), 'utf8');
function extractFunc(src, name) {
const re = new RegExp('function\\s+' + name + '\\s*\\([^)]*\\)\\s*\\{');
const m = re.exec(src);
if (!m) throw new Error('function ' + name + ' not found');
let i = m.index + m[0].length - 1;
let depth = 0;
for (; i < src.length; i++) {
if (src[i] === '{') depth++;
else if (src[i] === '}') {
depth--;
if (depth === 0) break;
}
}
return src.slice(m.index, i + 1);
}
let code = '';
for (const fn of ['swapNibbles', 'encIccid', 'decIccid',
'cardsNormIccid', 'cardsFindByIccid', 'cardsAutoSelectByIccid']) {
code += extractFunc(html, fn) + '\n';
}
eval(code);
// live-card style raw EF.ICCID content (nibble-swapped digits + 'F' pad)
const RAW_HEX = '980711090000640090F8';
const DIGITS = '8970119000004600098';
function fakeDoc() {
const els = { 'sp-card-sel': { value: '' }, 'ram-card-sel': { value: '' } };
globalThis.document = { getElementById: id => els[id] || null };
return els;
}
test('cardsNormIccid accepts digits, separators and raw EF hex', () => {
assert.strictEqual(cardsNormIccid(DIGITS), DIGITS);
assert.strictEqual(cardsNormIccid(' 89 70 1190-0000 4600 098 '), DIGITS);
assert.strictEqual(cardsNormIccid(RAW_HEX), DIGITS);
assert.strictEqual(cardsNormIccid(RAW_HEX.toLowerCase()), DIGITS);
assert.strictEqual(cardsNormIccid(''), '');
assert.strictEqual(cardsNormIccid(null), '');
});
test('cardsFindByIccid matches regardless of the stored form', () => {
globalThis.cards = [
{ name: 'A', iccid: '1111111111111111111' },
{ name: 'B', iccid: RAW_HEX },
{ name: 'C', iccid: '89 70 1190 0000 4600 098' },
];
assert.strictEqual(cardsFindByIccid(DIGITS), 1);
assert.strictEqual(cardsFindByIccid('1111111111111111111'), 0);
assert.strictEqual(cardsFindByIccid('2222222222222222222'), -1);
assert.strictEqual(cardsFindByIccid(''), -1);
});
test('cardsAutoSelectByIccid selects the preset in both SCP80 views', () => {
const els = fakeDoc();
const applied = [];
globalThis.cardsApply = idx => applied.push(idx);
globalThis.cards = [{ name: 'A', iccid: RAW_HEX }, { name: 'B', iccid: '' }];
globalThis._ramCardIdx = null;
globalThis._cardsAutoIccid = null;
const idx = cardsAutoSelectByIccid(DIGITS);
assert.strictEqual(idx, 0);
assert.strictEqual(els['sp-card-sel'].value, '0');
assert.strictEqual(els['ram-card-sel'].value, '0');
assert.deepStrictEqual(applied, ['0']);
assert.strictEqual(globalThis._ramCardIdx, 0);
});
test('cardsAutoSelectByIccid does not override a manual choice for the same card', () => {
const els = fakeDoc();
const applied = [];
globalThis.cardsApply = idx => applied.push(idx);
globalThis.cards = [{ name: 'A', iccid: DIGITS }, { name: 'B', iccid: '' }];
globalThis._ramCardIdx = null;
globalThis._cardsAutoIccid = null;
assert.strictEqual(cardsAutoSelectByIccid(DIGITS), 0);
// user picks the empty preset B for this card, then status polls repeat
els['sp-card-sel'].value = '1';
els['ram-card-sel'].value = '1';
assert.strictEqual(cardsAutoSelectByIccid(DIGITS), -1);
assert.strictEqual(els['sp-card-sel'].value, '1');
assert.deepStrictEqual(applied, ['0']);
});
test('cardsAutoSelectByIccid reacts to a card swap and to unreadable ICCIDs', () => {
fakeDoc();
globalThis.cardsApply = () => {};
globalThis.cards = [{ name: 'A', iccid: DIGITS }, { name: 'B', iccid: '89390100000129506903' }];
globalThis._cardsAutoIccid = null;
assert.strictEqual(cardsAutoSelectByIccid(DIGITS), 0);
assert.strictEqual(cardsAutoSelectByIccid('89390100000129506903'), 1);
// ICCID not readable: reset the guard, keep the current selection
assert.strictEqual(cardsAutoSelectByIccid(null), -1);
assert.strictEqual(globalThis._cardsAutoIccid, null);
assert.strictEqual(cardsAutoSelectByIccid(DIGITS), 0);
assert.strictEqual(cardsAutoSelectByIccid('1234567890123456789'), -1);
});
test('the card-state update wires the ICCID into the preset selection', () => {
assert.ok(html.includes('cardsAutoSelectByIccid(status.iccid);'));
assert.ok(html.includes('_cardsAutoIccid = null;'));
assert.ok(html.includes("(data.iccid ? ' | ICCID: <b>' + esc(data.iccid) + '</b>' : '')"));
});