-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrfid-webusb-reader.js
More file actions
344 lines (295 loc) · 12.6 KB
/
rfid-webusb-reader.js
File metadata and controls
344 lines (295 loc) · 12.6 KB
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
// =========================================================
// State
// =========================================================
let connectedDevice = null;
let isReading = false;
let readLoopController = null; // AbortController for the read loop
let scanEntries = [];
// =========================================================
// UI Helpers
// =========================================================
function setStatus(state, text) {
const bar = document.getElementById('statusBar');
bar.className = `status-bar ${state}`;
document.getElementById('statusText').textContent = text;
}
function showError(message) {
const banner = document.getElementById('errorBanner');
banner.textContent = `⚠️ ${message}`;
banner.classList.add('visible');
setTimeout(() => banner.classList.remove('visible'), 8000);
}
function clearError() {
document.getElementById('errorBanner').classList.remove('visible');
}
function updateButtons(connected) {
document.getElementById('btnConnect').disabled = connected;
document.getElementById('btnDisconnect').disabled = !connected;
document.getElementById('btnStartRead').disabled = !connected;
document.getElementById('btnStopRead').disabled = true;
}
function showDeviceInfo(device) {
const container = document.getElementById('deviceInfo');
container.style.display = 'grid';
container.innerHTML = `
<dt>Product</dt> <dd>${device.productName || 'N/A'}</dd>
<dt>Manufacturer</dt><dd>${device.manufacturerName || 'N/A'}</dd>
<dt>Serial</dt> <dd>${device.serialNumber || 'N/A'}</dd>
<dt>Vendor ID</dt> <dd>0x${device.vendorId.toString(16).toUpperCase().padStart(4, '0')}</dd>
<dt>Product ID</dt> <dd>0x${device.productId.toString(16).toUpperCase().padStart(4, '0')}</dd>
<dt>USB Version</dt><dd>${device.usbVersionMajor}.${device.usbVersionMinor}.${device.usbVersionSubminor}</dd>
<dt>Class</dt> <dd>0x${device.deviceClass.toString(16).toUpperCase().padStart(2, '0')}</dd>
`;
}
function hideDeviceInfo() {
const container = document.getElementById('deviceInfo');
container.style.display = 'none';
container.innerHTML = '';
}
function updateScanCount() {
document.getElementById('scanCount').textContent =
`${scanEntries.length} scan${scanEntries.length !== 1 ? 's' : ''}`;
}
// =========================================================
// Configuration Readers
// =========================================================
function getFilters() {
const vendorRaw = document.getElementById('cfgVendorId').value.trim();
const productRaw = document.getElementById('cfgProductId').value.trim();
const filter = {};
if (vendorRaw) filter.vendorId = parseInt(vendorRaw, 16);
if (productRaw) filter.productId = parseInt(productRaw, 16);
return Object.keys(filter).length > 0 ? [filter] : [];
}
function getConfigNumber() { return parseInt(document.getElementById('cfgConfigNum').value, 10); }
function getInterfaceNumber() { return parseInt(document.getElementById('cfgInterfaceNum').value, 10); }
function getEndpoint() { return parseInt(document.getElementById('cfgEndpoint').value, 10); }
function getReadLength() { return parseInt(document.getElementById('cfgReadLength').value, 10); }
// =========================================================
// WebUSB — Connect
// =========================================================
async function connectDevice() {
clearError();
if (!navigator.usb) {
showError('WebUSB is not supported in this browser. Please use Chrome or Edge.');
return;
}
try {
setStatus('connecting', 'Requesting device…');
const filters = getFilters();
const requestOptions = filters.length > 0 ? { filters } : { filters: [] };
const device = await navigator.usb.requestDevice(requestOptions);
try {
await device.open();
} catch (openErr) {
if (openErr.message && openErr.message.includes('Access denied')) {
const isWindows = navigator.userAgent.includes('Windows');
const isLinux = navigator.userAgent.includes('Linux');
let hint = 'The operating system is blocking direct access to this USB device. ';
if (isWindows) {
hint += 'On Windows, you need to replace the device driver with WinUSB using Zadig (https://zadig.akeo.ie). '
+ 'Open Zadig → Options → List All Devices → select your reader → replace driver with WinUSB. '
+ 'Then unplug/replug the device and retry.';
} else if (isLinux) {
hint += 'On Linux, add a udev rule granting access to this device. '
+ 'Run: echo \'SUBSYSTEM=="usb", ATTR{idVendor}=="'
+ device.vendorId.toString(16).padStart(4, '0')
+ '", ATTR{idProduct}=="'
+ device.productId.toString(16).padStart(4, '0')
+ '", MODE="0666"\' | sudo tee /etc/udev/rules.d/50-rfid-reader.rules '
+ '&& sudo udevadm control --reload-rules && sudo udevadm trigger. '
+ 'Then unplug/replug the device and retry.';
} else {
hint += 'Close any other application that may be using this device, unplug and replug it, then retry.';
}
showError(hint);
setStatus('disconnected', 'Access denied — see instructions below');
updateButtons(false);
return;
}
throw openErr;
}
// Select configuration if the device is not already configured
if (device.configuration === null ||
device.configuration.configurationValue !== getConfigNumber()) {
await device.selectConfiguration(getConfigNumber());
}
await device.claimInterface(getInterfaceNumber());
connectedDevice = device;
setStatus('connected', `Connected — ${device.productName || 'USB Device'}`);
showDeviceInfo(device);
updateButtons(true);
// Listen for unexpected disconnect
navigator.usb.addEventListener('disconnect', onUnexpectedDisconnect);
} catch (err) {
setStatus('disconnected', 'Disconnected');
if (err.name === 'NotFoundError') {
// User cancelled the picker — not an error
} else {
console.error('Connection error:', err);
showError(`Connection failed: ${err.message}`);
}
updateButtons(false);
}
}
// =========================================================
// WebUSB — Disconnect
// =========================================================
async function disconnectDevice() {
clearError();
stopReading();
if (connectedDevice) {
try {
await connectedDevice.releaseInterface(getInterfaceNumber());
await connectedDevice.close();
} catch (err) {
console.warn('Error during disconnect:', err);
}
connectedDevice = null;
}
navigator.usb.removeEventListener('disconnect', onUnexpectedDisconnect);
setStatus('disconnected', 'Disconnected');
hideDeviceInfo();
updateButtons(false);
}
function onUnexpectedDisconnect(event) {
if (connectedDevice && event.device === connectedDevice) {
connectedDevice = null;
stopReading();
setStatus('disconnected', 'Device disconnected unexpectedly');
hideDeviceInfo();
updateButtons(false);
showError('The RFID reader was disconnected.');
}
}
// =========================================================
// WebUSB — Read Loop
// =========================================================
async function startReading() {
if (!connectedDevice || isReading) return;
clearError();
isReading = true;
readLoopController = new AbortController();
document.getElementById('btnStartRead').disabled = true;
document.getElementById('btnStopRead').disabled = false;
const endpointAddress = getEndpoint();
const readLength = getReadLength();
try {
while (isReading && connectedDevice) {
const result = await connectedDevice.transferIn(endpointAddress, readLength);
if (result.status === 'ok' && result.data && result.data.byteLength > 0) {
processRfidData(result.data);
} else if (result.status === 'stall') {
console.warn('Endpoint stalled, clearing…');
await connectedDevice.clearHalt('in', endpointAddress);
}
}
} catch (err) {
if (isReading) {
// Only treat as error if we didn't deliberately stop
console.error('Read error:', err);
showError(`Read error: ${err.message}`);
}
} finally {
isReading = false;
document.getElementById('btnStartRead').disabled = !connectedDevice;
document.getElementById('btnStopRead').disabled = true;
}
}
function stopReading() {
isReading = false;
if (readLoopController) {
readLoopController.abort();
readLoopController = null;
}
document.getElementById('btnStopRead').disabled = true;
if (connectedDevice) {
document.getElementById('btnStartRead').disabled = false;
}
}
// =========================================================
// Data Processing
// =========================================================
function processRfidData(dataView) {
const bytes = new Uint8Array(dataView.buffer);
// Filter out empty/zero-filled transfers (many readers send these on idle)
if (bytes.every(b => b === 0)) return;
// Convert to hex string (e.g. "A1 B2 C3 D4")
const hexString = Array.from(bytes)
.map(b => b.toString(16).toUpperCase().padStart(2, '0'))
.join(' ');
// Try to extract a printable ASCII representation
const ascii = Array.from(bytes)
.map(b => (b >= 32 && b <= 126) ? String.fromCharCode(b) : '.')
.join('');
// Deduplicate rapid consecutive identical scans (debounce)
const lastEntry = scanEntries[scanEntries.length - 1];
if (lastEntry && lastEntry.hex === hexString) {
const elapsed = Date.now() - lastEntry.epochMs;
if (elapsed < 1500) return; // Ignore duplicate within 1.5 s
}
const entry = {
hex: hexString,
ascii: ascii,
timestamp: new Date().toLocaleTimeString(),
epochMs: Date.now(),
rawBytes: Array.from(bytes)
};
scanEntries.push(entry);
appendScanEntry(entry);
updateScanCount();
}
function appendScanEntry(entry) {
const log = document.getElementById('scanLog');
// Remove empty state if present
const emptyState = log.querySelector('.empty-state');
if (emptyState) emptyState.remove();
const div = document.createElement('div');
div.className = 'scan-entry new';
div.innerHTML = `
<span class="tag-id" title="ASCII: ${entry.ascii}">${entry.hex}</span>
<span class="timestamp">${entry.timestamp}</span>
`;
log.prepend(div); // Newest on top
log.scrollTop = 0;
}
// =========================================================
// Log Utilities
// =========================================================
function clearLog() {
scanEntries = [];
const log = document.getElementById('scanLog');
log.innerHTML = `
<div class="empty-state">
<div class="icon">🏷️</div>
<div>No scans yet. Connect a reader and start reading.</div>
</div>`;
updateScanCount();
}
function exportLog() {
if (scanEntries.length === 0) {
showError('Nothing to copy — scan some FOBs first.');
return;
}
const csv = scanEntries
.map(e => `${e.timestamp}\t${e.hex}\t${e.ascii}`)
.join('\n');
navigator.clipboard.writeText(csv).then(() => {
const btn = event.target;
const original = btn.textContent;
btn.textContent = '✅ Copied!';
setTimeout(() => btn.textContent = original, 1500);
}).catch(() => showError('Failed to copy to clipboard.'));
}
// =========================================================
// Auto-reconnect paired devices on page load
// =========================================================
window.addEventListener('load', async () => {
if (!navigator.usb) return;
const devices = await navigator.usb.getDevices();
if (devices.length > 0) {
// Offer to reconnect to the first previously-paired device
const device = devices[0];
setStatus('connecting', `Found paired device: ${device.productName || 'USB Device'}. Click Connect to re-pair.`);
}
});