Spaces:
Running
Running
Download rfid-handler.js from EHDEM/wastlessv6test2: direct link, hf CLI and curl.
- Browser
- Download file 9.97 kB
-
https://huggingface.co/spaces/EHDEM/wastlessv6test2/resolve/main/rfid-handler.js
- Command line
-
hf download hf://spaces/EHDEM/wastlessv6test2/rfid-handler.js
-
curl -L -o rfid-handler.js https://huggingface.co/spaces/EHDEM/wastlessv6test2/resolve/main/rfid-handler.js
9.97 kB
| // rfid-handler.js - RFID Integration for WASTE-LESS | |
| // Uses GITHUB_CONFIG from config.js for all GitHub operations | |
| const RFID_CONFIG = { | |
| SCANNER: { | |
| INPUT_TIMEOUT: 500, | |
| ID_LENGTH: 10, | |
| PREFIX: '', | |
| SUFFIX: '\n' | |
| } | |
| }; | |
| function parseStudentEntry(entry) { | |
| if (typeof entry === 'string') { | |
| const parts = entry.split('|'); | |
| return { name: parts[0], rfid: parts[1] || null }; | |
| } | |
| return entry; | |
| } | |
| class RFIDScanner { | |
| constructor() { | |
| this.buffer = ''; | |
| this.lastKeyTime = 0; | |
| this.onScanCallback = null; | |
| } | |
| init(onScan) { | |
| this.onScanCallback = onScan; | |
| document.addEventListener('keydown', this.handleKeyDown.bind(this)); | |
| console.log('RFID Scanner ready'); | |
| } | |
| handleKeyDown(event) { | |
| const now = Date.now(); | |
| const timeDiff = now - this.lastKeyTime; | |
| this.lastKeyTime = now; | |
| if (timeDiff > RFID_CONFIG.SCANNER.INPUT_TIMEOUT && this.buffer.length > 0) { | |
| this.buffer = ''; | |
| } | |
| if (event.ctrlKey || event.altKey || event.metaKey) return; | |
| if (event.key === 'Enter') { | |
| if (this.buffer.length >= 4) { | |
| this.processScan(this.buffer); | |
| } | |
| this.buffer = ''; | |
| event.preventDefault(); | |
| return; | |
| } | |
| if (event.key.length === 1) { | |
| this.buffer += event.key; | |
| } | |
| if (this.buffer.length >= RFID_CONFIG.SCANNER.ID_LENGTH) { | |
| this.processScan(this.buffer); | |
| this.buffer = ''; | |
| } | |
| } | |
| processScan(rawId) { | |
| let cleanId = rawId.trim().toUpperCase(); | |
| const prefixes = ['CARD:', 'ID:', 'RFID:', 'UID:']; | |
| prefixes.forEach(p => { | |
| if (cleanId.startsWith(p)) cleanId = cleanId.substring(p.length); | |
| }); | |
| cleanId = cleanId.replace(/[^A-Z0-9]/g, ''); | |
| this.onScanCallback?.(cleanId); | |
| } | |
| simulateScan(rfidId) { | |
| this.processScan(rfidId); | |
| } | |
| } | |
| class StudentRFIDManager { | |
| constructor() { | |
| this.scanner = new RFIDScanner(); | |
| this.students = {}; | |
| this.availableClasses = []; | |
| this.repo = GITHUB_CONFIG.REPOS.STUDENT_LIST; | |
| this.token = GITHUB_CONFIG.TOKEN; | |
| this.filePath = GITHUB_CONFIG.PATHS.STUDENTS; | |
| } | |
| async loadStudentList() { | |
| try { | |
| const response = await fetch( | |
| `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`, | |
| { | |
| headers: { | |
| 'Authorization': `token ${this.token}`, | |
| 'Accept': 'application/vnd.github.v3+json' | |
| } | |
| } | |
| ); | |
| if (response.status === 404) { | |
| this.students = {}; | |
| this.availableClasses = []; | |
| return false; | |
| } | |
| if (!response.ok) throw new Error('Failed to load student list'); | |
| const data = await response.json(); | |
| this.students = JSON.parse(atob(data.content)); | |
| this.migrateFormat(); | |
| this.availableClasses = [...new Set(Object.keys(this.students).map(k => k.split('-')[0]))].sort(); | |
| return true; | |
| } catch (error) { | |
| console.error('Error loading student list:', error); | |
| const local = localStorage.getItem('student-list-backup'); | |
| if (local) { | |
| this.students = JSON.parse(local); | |
| this.migrateFormat(); | |
| this.availableClasses = [...new Set(Object.keys(this.students).map(k => k.split('-')[0]))].sort(); | |
| } | |
| return false; | |
| } | |
| } | |
| migrateFormat() { | |
| for (const key in this.students) { | |
| if (Array.isArray(this.students[key]) && this.students[key].length > 0) { | |
| if (typeof this.students[key][0] === 'string') { | |
| this.students[key] = this.students[key].map(entry => { | |
| if (typeof entry === 'string') { | |
| const parts = entry.split('|'); | |
| return { name: parts[0], rfid: parts[1] || null }; | |
| } | |
| return entry; | |
| }); | |
| } | |
| } | |
| } | |
| } | |
| getStudentNames(classVal, formVal) { | |
| const key = `${classVal}-${formVal}`; | |
| if (!this.students[key]) return []; | |
| return this.students[key].map(s => s.name || s); | |
| } | |
| getStudentData(classVal, formVal, studentName) { | |
| const key = `${classVal}-${formVal}`; | |
| if (!this.students[key]) return null; | |
| return this.students[key].find(s => (s.name || s) === studentName) || null; | |
| } | |
| getRFIDByStudent(classVal, formVal, studentName) { | |
| const student = this.getStudentData(classVal, formVal, studentName); | |
| if (!student) return null; | |
| return student.rfid || null; | |
| } | |
| findStudentByRFID(rfidId) { | |
| const cleanId = rfidId.toUpperCase().replace(/[^A-Z0-9]/g, ''); | |
| for (const [key, studentList] of Object.entries(this.students)) { | |
| const [cls, form] = key.split('-'); | |
| for (const student of studentList) { | |
| const studentRfid = (student.rfid || '').toUpperCase().replace(/[^A-Z0-9]/g, ''); | |
| if (studentRfid === cleanId) { | |
| return { | |
| rfidId: cleanId, | |
| studentName: student.name || student, | |
| class: cls, | |
| form: form, | |
| rawData: student | |
| }; | |
| } | |
| } | |
| } | |
| return null; | |
| } | |
| async setStudentRFID(classVal, formVal, studentName, rfidId) { | |
| const key = `${classVal}-${formVal}`; | |
| if (!this.students[key]) return false; | |
| const idx = this.students[key].findIndex(s => (s.name || s) === studentName); | |
| if (idx === -1) return false; | |
| const existing = this.students[key][idx]; | |
| if (typeof existing === 'string') { | |
| this.students[key][idx] = { name: existing, rfid: rfidId }; | |
| } else { | |
| this.students[key][idx].rfid = rfidId; | |
| } | |
| return await this.saveStudentList(); | |
| } | |
| async removeStudentRFID(classVal, formVal, studentName) { | |
| return await this.setStudentRFID(classVal, formVal, studentName, null); | |
| } | |
| async saveStudentList() { | |
| try { | |
| let sha = null; | |
| const res = await fetch( | |
| `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`, | |
| { headers: { 'Authorization': `token ${this.token}` } } | |
| ); | |
| if (res.ok) sha = (await res.json()).sha; | |
| const putRes = await fetch( | |
| `https://api.github.com/repos/${this.repo}/contents/${this.filePath}`, | |
| { | |
| method: 'PUT', | |
| headers: { | |
| 'Authorization': `token ${this.token}`, | |
| 'Content-Type': 'application/json' | |
| }, | |
| body: JSON.stringify({ | |
| message: `Update student RFID data - ${new Date().toISOString()}`, | |
| content: btoa(JSON.stringify(this.students, null, 2)), | |
| sha, | |
| branch: 'main' | |
| }) | |
| } | |
| ); | |
| if (!putRes.ok) throw new Error('Save failed'); | |
| localStorage.setItem('student-list-backup', JSON.stringify(this.students)); | |
| return true; | |
| } catch (err) { | |
| console.error('Save error:', err); | |
| localStorage.setItem('student-list-backup', JSON.stringify(this.students)); | |
| return false; | |
| } | |
| } | |
| exportToCSV() { | |
| let csv = 'Class,Form,StudentName,RFID_Card_ID\n'; | |
| for (const [key, studentList] of Object.entries(this.students)) { | |
| const [cls, form] = key.split('-'); | |
| studentList.forEach(student => { | |
| const name = student.name || student; | |
| const rfid = student.rfid || ''; | |
| csv += `${cls},${form},"${name.replace(/"/g, '""')}",${rfid}\n`; | |
| }); | |
| } | |
| return csv; | |
| } | |
| importFromCSV(csvText) { | |
| const lines = csvText.split('\n').map(l => l.trim()).filter(l => l); | |
| if (lines.length < 2) throw new Error('Empty or invalid CSV'); | |
| const headers = lines[0].toLowerCase().split(','); | |
| const hasRfid = headers.includes('rfid_card_id') || headers.includes('rfid'); | |
| const rfidCol = headers.indexOf('rfid_card_id') !== -1 ? | |
| headers.indexOf('rfid_card_id') : | |
| headers.indexOf('rfid'); | |
| const newStudents = {}; | |
| for (let i = 1; i < lines.length; i++) { | |
| const match = lines[i].match(/([^,]*),([^,]*),([^,]*)(?:,(.*))?/); | |
| if (!match) continue; | |
| let cls = match[1].trim().toUpperCase(); | |
| let form = match[2].trim(); | |
| let name = match[3].trim().replace(/^"|"$/g, '').replace(/"""/g, '"'); | |
| let rfid = hasRfid && match[4] ? match[4].trim().replace(/^"|"$/g, '') : null; | |
| if (!cls || !form || !name) continue; | |
| const key = `${cls}-${form}`; | |
| if (!newStudents[key]) newStudents[key] = []; | |
| const exists = newStudents[key].find(s => (s.name || s) === name); | |
| if (!exists) { | |
| newStudents[key].push(rfid ? { name, rfid } : name); | |
| } | |
| } | |
| this.students = newStudents; | |
| this.availableClasses = [...new Set(Object.keys(newStudents).map(k => k.split('-')[0]))].sort(); | |
| return this.saveStudentList(); | |
| } | |
| } | |
| window.StudentRFIDManager = StudentRFIDManager; | |
| window.RFIDScanner = RFIDScanner; | |
| window.parseStudentEntry = parseStudentEntry; | |