server+ui: detect card removal passively and reflect it within 2s
The UI only noticed a removed card when some user action ran a real card command (e.g. Check status); /api/status is a cached-state read that kept returning the old card, and _handle_card_disconnect() did not clear app.card/rs. - start_card_monitor() registers a pyscard CardObserver for our reader; it only polls SCardGetStatusChange (no APDU, no connection, no extra process), and on removal sets server.card_present=False and calls _handle_card_disconnect() under _CARD_LOCK - /api/status now exposes connected (session usable) and card_present (physically inserted) and masks card/profile/atr/selection when not connected; _CARD_CONNECTED is initialized from card presence instead of being unconditionally True - the 2s UI poll includes /api/status; on disconnect it switches to the existing 'No card detected. Insert card and click Equip' state, or the new 'Card inserted — press Equip' hint when the card is back; the old _hadData heuristic is gone Tests for the observer (filtering, removal, insertion) and the UI state transitions. SW cache v90 -> v91.
This commit is contained in:
+27
-11
@@ -6400,6 +6400,7 @@ async function pysimStatusPoll() {
|
||||
}
|
||||
|
||||
let _pysimPollTimer = null;
|
||||
let _pysimLastConnected = null;
|
||||
|
||||
async function pysimPollToggle() {
|
||||
const btn = document.getElementById('pli-pause-btn');
|
||||
@@ -6435,27 +6436,41 @@ async function pysimPollStatusInit() {
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
|
||||
function pysimCardStateUpdate(status) {
|
||||
if (!status || typeof status.connected !== 'boolean') return;
|
||||
const statusEl = document.getElementById('pysim-status');
|
||||
if (status.connected === _pysimLastConnected) return;
|
||||
_pysimLastConnected = status.connected;
|
||||
if (status.connected) {
|
||||
pysimSetConnected(true);
|
||||
pysimRefresh();
|
||||
return;
|
||||
}
|
||||
pysimSetConnected(false);
|
||||
if (statusEl && statusEl.textContent.trim() !== '') {
|
||||
if (status.card_present) {
|
||||
statusEl.innerHTML = '<span class="text-amber-600">' + esc(t('Card inserted — press Equip')) + '</span>';
|
||||
} else {
|
||||
statusEl.innerHTML = '<span class="text-red-500">' + esc(t('No card detected. Insert card and click Equip card button')) + '</span>';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function pysimStartBackendPoll() {
|
||||
if (_pysimPollTimer) clearInterval(_pysimPollTimer);
|
||||
let _hadData = false;
|
||||
_pysimLastConnected = null;
|
||||
_pysimPollTimer = setInterval(async () => {
|
||||
try {
|
||||
const [log, stk, ps] = await Promise.all([
|
||||
const [log, stk, ps, status] = await Promise.all([
|
||||
pysimFetch('/api/proactive-log'),
|
||||
pysimFetch('/api/stk-status'),
|
||||
pysimFetch('/api/poll-status'),
|
||||
pysimFetch('/api/status'),
|
||||
]);
|
||||
pysimUpdatePollUI(ps.enabled, ps.interval);
|
||||
if (Array.isArray(log) && log.length > 0) _hadData = true;
|
||||
if (_hadData && !ps.enabled && Array.isArray(log) && log.length === 0) {
|
||||
_hadData = false;
|
||||
const statusEl = document.getElementById('pysim-status');
|
||||
if (statusEl && statusEl.textContent.trim() !== '') {
|
||||
statusEl.innerHTML = '<span class="text-red-500">Card disconnected</span>';
|
||||
}
|
||||
}
|
||||
pysimCardStateUpdate(status);
|
||||
} catch (e) { /* ignore */ }
|
||||
}, 5000);
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
// ===== proactive command log =====
|
||||
@@ -8746,6 +8761,7 @@ const LANG_RU = {
|
||||
'pysim-blocked-hint': 'Браузер, вероятно, заблокировал доступ к локальному серверу карт. Разрешите доступ к локальной сети для этого сайта (Chrome/Edge/Vivaldi: Настройки сайта → Доступ к локальной сети → Разрешить). Также проверьте, что pysim-otaman-server запущен по адресу {url}.',
|
||||
'pysim-unreachable-hint': 'Не удалось подключиться к серверу карт. Проверьте, что pysim-otaman-server запущен и адрес указан верно ({url}). Если эта страница открыта по HTTPS, также разрешите доступ к локальной сети в браузере (Chrome/Edge/Vivaldi: Настройки сайта → Доступ к локальной сети → Разрешить).',
|
||||
'No card detected. Insert card and click Equip card button': 'Карта не обнаружена. Вставьте карту и нажмите Подключить карту',
|
||||
'Card inserted — press Equip': 'Карта вставлена — нажмите «Подключить карту»',
|
||||
'Checking...': 'Проверка...',
|
||||
'Resetting...': 'Сброс...',
|
||||
'Equipping...': 'Подключение...',
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
const CACHE = 'otaman-v90';
|
||||
const CACHE = 'otaman-v91';
|
||||
const URLS = [
|
||||
'index.html',
|
||||
'help.html',
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
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 = 'var _pysimLastConnected = null;\n';
|
||||
code += extractFunc(html, 'pysimCardStateUpdate') + '\n';
|
||||
code += '\nglobalThis.esc = s => s;\n';
|
||||
code += 'globalThis.t = s => s;\n';
|
||||
eval(code);
|
||||
|
||||
function setup() {
|
||||
const el = { textContent: 'status line', innerHTML: '' };
|
||||
const calls = { connected: [], refresh: 0 };
|
||||
globalThis.document = { getElementById: () => el };
|
||||
globalThis.pysimSetConnected = v => calls.connected.push(v);
|
||||
globalThis.pysimRefresh = () => { calls.refresh++; };
|
||||
return { el, calls };
|
||||
}
|
||||
|
||||
test('disconnect without card shows the no-card message', () => {
|
||||
_pysimLastConnected = true;
|
||||
const { el, calls } = setup();
|
||||
pysimCardStateUpdate({ connected: false, card_present: false });
|
||||
assert.deepStrictEqual(calls.connected, [false]);
|
||||
assert.ok(el.innerHTML.includes('No card detected'), el.innerHTML);
|
||||
});
|
||||
|
||||
test('disconnect with card present shows the Equip hint', () => {
|
||||
_pysimLastConnected = true;
|
||||
const { el } = setup();
|
||||
pysimCardStateUpdate({ connected: false, card_present: true });
|
||||
assert.ok(el.innerHTML.includes('Card inserted'), el.innerHTML);
|
||||
});
|
||||
|
||||
test('unchanged state does not touch the UI again', () => {
|
||||
_pysimLastConnected = false;
|
||||
const { el, calls } = setup();
|
||||
el.innerHTML = 'unchanged';
|
||||
pysimCardStateUpdate({ connected: false, card_present: false });
|
||||
assert.deepStrictEqual(calls.connected, []);
|
||||
assert.strictEqual(el.innerHTML, 'unchanged');
|
||||
});
|
||||
|
||||
test('reconnect restores the connected UI and refreshes', () => {
|
||||
_pysimLastConnected = false;
|
||||
const { calls } = setup();
|
||||
pysimCardStateUpdate({ connected: true, card_present: true });
|
||||
assert.deepStrictEqual(calls.connected, [true]);
|
||||
assert.strictEqual(calls.refresh, 1);
|
||||
});
|
||||
|
||||
test('payload without connected flag is ignored', () => {
|
||||
_pysimLastConnected = null;
|
||||
const { calls } = setup();
|
||||
pysimCardStateUpdate({ reader: 'x' });
|
||||
pysimCardStateUpdate(null);
|
||||
assert.deepStrictEqual(calls.connected, []);
|
||||
});
|
||||
Reference in New Issue
Block a user