### Raspberry Pi Setup: Install PC/SC and Node Module Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install PC/SC libraries and daemon, enable and start the PC/SC service, then install the Node module. ```bash # Install dependencies sudo apt-get install libpcsclite1 libpcsclite-dev pcscd # Enable PC/SC daemon sudo systemctl enable pcscd sudo systemctl start pcscd # Install Node module npm install thai-national-id-card-reader ``` -------------------------------- ### Build and Run Example Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md This command sequence first builds the project and then runs an example to test the compiled output. Ensure dependencies are installed before running. ```bash npm run build && npm run example ``` -------------------------------- ### Windows Setup: Install Dependencies and Verify Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install the card reader package and verify PC/SC availability in Device Manager. ```bash # Install dependencies npm install thai-national-id-card-reader # Verify PC/SC availability # Device Manager → Smart Card Readers should show your reader ``` -------------------------------- ### Linux/Ubuntu Setup: Install PC/SC and Enable Service Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Update package manager, install PC/SC libraries and daemon, and enable/start the PC/SC service. ```bash # Update package manager sudo apt-get update # Install PC/SC libraries sudo apt-get install libpcsclite1 libpcsclite-dev pcscd # Enable and start PC/SC daemon sudo systemctl enable pcscd sudo systemctl start pcscd ``` -------------------------------- ### Minimal Example Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/SUMMARY.txt A basic example demonstrating how to read data from a Thai national ID card with minimal setup. ```javascript import { ThaiIdCardReader } from "thai-id-card-reader"; const reader = new ThaiIdCardReader(); const data = await reader.getData(); console.log(data); reader.destroy(); ``` -------------------------------- ### Windows Setup: Install Build Tools Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install Windows build tools required for native module compilation on Windows. ```bash # Install Windows build tools npm install --global windows-build-tools ``` -------------------------------- ### Linux/Ubuntu Setup: Install Node Module and Verify Daemon Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install the card reader Node module and check the status of the PC/SC daemon. ```bash # Install Node module npm install thai-national-id-card-reader # Verify daemon is running systemctl status pcscd ``` -------------------------------- ### Install from Source Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Clone the repository, install dependencies, and build the project from source code. ```bash git clone https://github.com/nonth/thai-national-id-card-reader.git cd thai-national-id-card-reader npm install npm run build ``` -------------------------------- ### macOS Setup: Install Xcode Tools and Dependencies Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install Xcode command line tools if necessary and then install the card reader package. The PC/SC framework is included with macOS. ```bash # Install Xcode command line tools (if needed) xcode-select --install # Install dependencies npm install thai-national-id-card-reader # PC/SC framework is included with macOS ``` -------------------------------- ### Build and Run Example Project Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Commands to build and run the example project for development and testing. This is for local development and not for library usage in other projects. ```bash # Build the project (for development) npm run build # Run the working example npm run example # Or run directly node example.js ``` -------------------------------- ### Linux/Ubuntu/Raspberry Pi Setup Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/README.md Install necessary PC/SC Lite packages and enable the pcscd service for Linux-based systems. This setup is required for the card reader to function correctly. ```bash sudo apt-get install libpcsclite1 libpcsclite-dev pcscd sudo systemctl enable pcscd sudo systemctl start pcscd ``` -------------------------------- ### Install thai-national-id-card-reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/README.md Install the library using npm. Ensure Node.js and npm are installed and meet the version requirements. ```bash npm install thai-national-id-card-reader ``` -------------------------------- ### Testing Commands Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/CLAUDE.md Commands to build the library and test it using the example, or to execute the example directly. ```bash npm run build && npm run example # Build and test with example node example.js # Direct example execution ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Run this command in the project's root directory to install all necessary npm packages listed in package.json. ```bash npm install ``` -------------------------------- ### Global npm Installation Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install the package globally on your system for command-line access. ```bash npm install --global thai-national-id-card-reader ``` -------------------------------- ### Development npm Installation Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Install the package as a development dependency for building or testing. ```bash npm install --save-dev thai-national-id-card-reader ``` -------------------------------- ### Build and Development Commands Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/CLAUDE.md Commands for compiling, watching, type checking, and running the example in a TypeScript project. ```bash npm run build # Compile TypeScript to CommonJS in dist/ npm run dev # Watch mode compilation npm run typecheck # Type checking without emit npm run example # Run the working example (requires build first) ``` -------------------------------- ### Install PC/SC Daemon and Development Libraries on Ubuntu/Raspberry Pi Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Installs necessary PC/SC components for card reading on Debian-based systems. Ensures the PC/SC daemon is running and enabled. ```bash sudo apt-get update sudo apt-get install libpcsclite1 libpcsclite-dev pcscd sudo systemctl start pcscd sudo systemctl enable pcscd ``` -------------------------------- ### init() Method Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Initializes the card reader and starts listening for card reader devices. This method establishes a connection with the PC/SC smartcard framework and registers device event listeners. ```APIDOC ## Method: init() ### Description Initialize the card reader and start listening for card reader devices. Establishes connection with PC/SC smartcard framework and registers device event listeners. ### Method `init(): void` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | — | — | — | — | ### Request Example ```typescript try { cardReader.init(); console.log('Card reader initialized'); } catch (error) { console.error('Failed to initialize:', error.message); } ``` ### Response #### Success Response (200) Returns `void`. #### Response Example None explicitly provided. ### Throws - `Error` - If reader is already initialized - `Error` - If PC/SC framework initialization fails ``` -------------------------------- ### Example Integration Pattern Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/CLAUDE.md Demonstrates best practices for integrating the card reader, including CommonJS import, error handling configuration, and event management. ```javascript const { ThaiIdCardReader } = require('./dist/index.js'); const reader = new ThaiIdCardReader({ exitOnReadError: false }); reader.on('cardInserted', (event) => { console.log('Card inserted:', event.data); }); reader.on('cardData', (event) => { console.log('Card data:', event.data); }); reader.on('error', (error) => { console.error('Reader error:', error); }); process.on('SIGINT', () => { console.log('Shutting down...'); reader.close(); process.exit(0); }); ``` -------------------------------- ### Promise-Based Usage Example Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Shows how to use the card reader with Promises for asynchronous operations. ```APIDOC ## Promise-Based Card Reading ### Description Encapsulates the card reading process into a Promise, resolving with card data or rejecting with an error. ### Function Signature ```javascript function readCardData() ``` ### Usage ```javascript readCardData() .then(data => console.log('Card data:', data)) .catch(error => console.error('Failed to read card:', error)); ``` ### Returns A Promise that resolves with the card data or rejects with an error. ``` -------------------------------- ### Error Handling Example Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Demonstrates how to handle card-related errors using event listeners. ```APIDOC ## Event: card-error ### Description Listens for errors during card operations. Provides status, description, and detailed data about the error. ### Usage ```javascript cardReader.on('card-error', (event) => { console.error(`Error (${event.status}): ${event.description}`); console.error('Details:', event.data.message); switch (event.status) { case 400: console.log('Please insert a valid Thai National ID Card'); break; case 404: console.log('Card reader not found - check connections'); break; case 500: console.log('Card reading failed:', event.data.error); break; } }); ``` #### Event Payload * **status** (number) - The HTTP-style status code of the error. * **description** (string) - A human-readable description of the error. * **data** (object) - An object containing detailed error information, potentially including a `message` or `error` field. ``` -------------------------------- ### Run Development Server Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Starts the development server in watch mode, automatically recompiling and reloading on code changes. Useful for active development. ```bash npm run dev ``` -------------------------------- ### Example Usage of isNhsoSuccess (TypeScript) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-nhso.md Demonstrates how to use the `isNhsoSuccess` function to check the status of a card command response and log a success message. ```typescript const response = await card.issueCommand(cmd); if (isNhsoSuccess(response.status)) { console.log('NHSO data read successfully'); } ``` -------------------------------- ### Basic NhsoApplet Usage Example Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Demonstrates the basic usage of the NhsoApplet to retrieve and log health insurance information. Assumes a 'card' instance is available and handles potential errors if NHSO data is not present. ```typescript import { NhsoApplet } from 'thai-national-id-card-reader'; // Assuming 'card' is a Card instance from smartcard reader const nhsoApplet = new NhsoApplet(card); try { const healthData = await nhsoApplet.getInfo(); console.log('Health Insurance Information:'); console.log('Main Insurance Level:', healthData.mainInscl); console.log('Main Hospital:', healthData.mainHospitalName); console.log('Issue Date:', healthData.issueDate); console.log('Expiration Date:', healthData.expireDate); } catch (error) { console.log('NHSO data not available on this card'); } ``` -------------------------------- ### Check Card Reader Status Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Verify if the card reader is initialized and ready before sending commands. If not ready, this example shows how to initialize it. ```typescript if (cardReader.isReady()) { console.log('Reader is active'); } else { cardReader.init(); } ``` -------------------------------- ### Integrate Laser ID Extraction with Card Data Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/utilities.md This example shows how to extract both personal data and the optional laser ID from a card. It includes error handling for the laser ID extraction. ```typescript import { Card } from '@nonth/smartcard'; import { getData, getLaser } from 'thai-national-id-card-reader'; async function extractAllCardData(card) { const req = [0x00, 0xc0, 0x00, 0x00]; const data = {}; // Extract personal data const cidBuffer = await getData(card, apduPerson.CMD_CID, req); data.cid = cidBuffer.slice(0, -2).toString().trim(); // Extract laser ID (optional) try { data.laserId = await getLaser(card, req); } catch { console.log('Laser ID not available'); data.laserId = null; } return data; } ``` -------------------------------- ### Handle All Card Reader Events Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/README.md This example demonstrates how to subscribe to all available events emitted by the ThaiIdCardReader, including device connection/disconnection, card insertion/removal, successful data reads, and errors. This provides comprehensive feedback on the reader's status. ```typescript reader.on('device-connected', (event) => { console.log('Reader connected:', event.data.device); }); reader.on('card-inserted', (event) => { console.log('Card detected, ATR:', event.data.atr); }); reader.on('card-data', (event) => { console.log('Card read successful'); // Process all available fields processCard(event.data); }); reader.on('card-error', (event) => { console.error('Read error:', event.data.message); }); reader.on('card-removed', (event) => { console.log('Card removed'); }); reader.on('device-disconnected', (event) => { console.log('Reader disconnected'); }); ``` -------------------------------- ### Example Usage of getNhsoStatusDescription (TypeScript) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-nhso.md Shows how to call `getNhsoStatusDescription` with a specific status code (0x6a82) and what the expected output string would be. ```typescript const description = getNhsoStatusDescription(0x6a82); // Returns: "NHSO applet not found on this card" ``` -------------------------------- ### Read Card Data Using Promises Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/README.md This example demonstrates a promise-based approach to reading card data, which can be more convenient for asynchronous control flow. It uses `reader.once` to listen for either a successful 'card-data' event or a 'card-error' event, cleans up the reader, and resolves or rejects the promise accordingly. The reader must be initialized with `reader.init()`. ```typescript function readCardData() { return new Promise((resolve, reject) => { const reader = new ThaiIdCardReader({ exitOnReadError: false }); reader.once('card-data', (event) => { reader.destroy(); resolve(event.data); }); reader.once('card-error', (event) => { reader.destroy(); reject(new Error(event.data.message)); }); reader.init(); }); } readCardData() .then(data => console.log('Card:', data)) .catch(error => console.error('Failed:', error)); ``` -------------------------------- ### CommonJS Usage of Thai National ID Card Reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Demonstrates how to use the Thai National ID Card Reader with CommonJS modules. Includes setup for event listeners and graceful shutdown. ```javascript const { ThaiIdCardReader } = require('thai-national-id-card-reader'); // Create reader instance - automatically reads ALL fields const cardReader = new ThaiIdCardReader({ debug: false, // Enable for troubleshooting exitOnReadError: false // Don't exit on read errors }); // Set up event listeners cardReader.on('device-connected', (event) => { console.log('✅ Card reader connected:', event.data.message); }); cardReader.on('card-inserted', (event) => { console.log('💳 Card detected:', event.data.message); }); cardReader.on('card-data', (event) => { const data = event.data; console.log('📄 Thai National ID Card Data:'); console.log('├─ Citizen ID:', data.cid); console.log('├─ Thai Name:', data.name); console.log('├─ English Name:', data.nameEn); console.log('├─ Date of Birth:', data.dob); console.log('├─ Gender:', data.gender); console.log('├─ Address:', data.address); console.log('├─ Issue Date:', data.issueDate); console.log('├─ Expire Date:', data.expireDate); console.log('├─ Issuer:', data.issuer); console.log('├─ NHSO Data:', data.nhso ? JSON.stringify(data.nhso, null, 2) : 'Not Available'); console.log('├─ Laser ID:', data.laserId || 'Not Available'); console.log('└─ Photo:', data.photo ? 'Available (Base64)' : 'Not Available'); }); cardReader.on('card-removed', (event) => { console.log('📤 Card removed:', event.data.message); }); cardReader.on('card-error', (event) => { console.error('❌ Error:', event.data.message); }); // Initialize and start reading cardReader.init(); console.log('🚀 Thai National ID Card Reader initialized. Insert a card...'); // Graceful shutdown process.on('SIGINT', () => { console.log('\n🛑 Shutting down...'); cardReader.destroy(); process.exit(0); }); ``` -------------------------------- ### Contributing to the Project Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Follow these steps to contribute to the project. Ensure code quality and test with hardware before committing. ```bash git checkout -b feature/amazing-feature ``` ```bash npm run lint && npm run typecheck ``` ```bash npm run build && npm run example ``` ```bash git commit -m 'Add amazing feature' ``` ```bash git push origin feature/amazing-feature ``` -------------------------------- ### Count Event Listeners Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Get the number of registered listeners for a specific event. This is useful for monitoring or debugging. ```typescript const count = cardReader.listenerCount('card-data'); console.log(`${count} listener(s) for card-data event`); ``` -------------------------------- ### Get Event Listeners Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Retrieve an array of all listener functions registered for a specific event. This can be used for inspection or advanced manipulation. ```typescript const handlers = cardReader.listeners('card-data'); console.log(`Listeners for card-data:`, handlers); ``` -------------------------------- ### Initialize Card Reader and Listen for Card Data Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/README.md This snippet shows how to instantiate the ThaiIdCardReader, configure it, and listen for the 'card-data' event to log basic card information like CID, name, and DOB. Ensure the reader is initialized using `reader.init()`. ```typescript import { ThaiIdCardReader } from 'thai-national-id-card-reader'; const reader = new ThaiIdCardReader({ debug: false, exitOnReadError: false }); reader.on('card-data', (event) => { const data = event.data; console.log('CID:', data.cid); console.log('Name:', data.name); console.log('DOB:', data.dob); }); reader.init(); ``` -------------------------------- ### isReady() Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Checks if the card reader is currently initialized and ready to accept commands. Returns a boolean indicating the readiness state of the reader. ```APIDOC ## Method: isReady() ### Description Check if the card reader is currently initialized and ready to accept commands. ### Method `boolean` ### Parameters None ### Returns `boolean` - True if initialized, false otherwise ### Example ```typescript if (cardReader.isReady()) { console.log('Reader is active'); } else { cardReader.init(); } ``` ``` -------------------------------- ### Decode TIS-620 Thai Text Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/utilities.md Reads data from the card, decodes it from TIS-620 encoding, and trims whitespace. Ensure the 'legacy-encoding' library is installed. ```typescript import legacy from 'legacy-encoding'; import { getData } from 'thai-national-id-card-reader'; async function readThaiText(card, command, req) { const buffer = await getData(card, command, req); const cleanData = buffer.slice(0, -2); const thaiText = legacy.decode(cleanData, 'tis620'); return thaiText.toString().trim(); } ``` -------------------------------- ### Get All Registered Event Names Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Retrieves an array of all event names that currently have registered listeners. Useful for inspecting the state of event subscriptions. ```typescript public eventNames(): Array const events = cardReader.eventNames(); console.log('Registered events:', events); // Output: ['card-data', 'card-error', 'device-connected'] ``` -------------------------------- ### Initialize Card Reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Initialize the card reader to begin listening for devices. This method establishes the connection to the PC/SC framework and registers listeners. Ensure to handle potential errors during initialization. ```typescript try { cardReader.init(); console.log('Card reader initialized'); } catch (error) { console.error('Failed to initialize:', error.message); } ``` -------------------------------- ### SELECT Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Activates the NHSO applet on the card. This command is a prerequisite for executing other NHSO applet commands. ```APIDOC ## SELECT SELECT ### Description Activates the NHSO applet on the card. This command is a prerequisite for executing other NHSO applet commands. ### Command SELECT ### Address — ### Field NHSO applet ### Length — ### Purpose Activate NHSO applet ``` -------------------------------- ### Get NHSO Applet Version Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Retrieves the version of the NHSO applet. This method is currently a placeholder and returns null, but is intended for future use in version detection. ```typescript public async getAppletVersion(): Promise ``` -------------------------------- ### Get All Photo Segment Commands Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-person.md Retrieves an array of all 20 APDU commands required to read photo segments sequentially. Use this to iterate through photo data. ```typescript export function getPhotoCommands(): number[][] ``` ```typescript const commands = getPhotoCommands(); for (const cmd of commands) { const data = await card.issueCommand(new CommandApdu({ bytes: cmd })); // Process segment } ``` -------------------------------- ### Check Hardware Connection (macOS) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md On macOS, use system_profiler to list USB devices and verify hardware detection. ```bash system_profiler SPUSBDataType ``` -------------------------------- ### Promise-based Usage Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/SUMMARY.txt Shows how to use the library's methods with Promises for asynchronous operations, ensuring proper handling of results and errors. ```javascript import { ThaiIdCardReader } from "thai-id-card-reader"; async function readCard() { const reader = new ThaiIdCardReader(); try { const data = await reader.getData(); console.log("Successfully read card data:", data); } catch (error) { console.error("Failed to read card data:", error); } finally { reader.destroy(); } } readCard(); ``` -------------------------------- ### Get NHSO Status Description (TypeScript) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-nhso.md Provides a human-readable description for a given NHSO status code. This is useful for debugging or informing users about operation outcomes. ```typescript function getNhsoStatusDescription(statusCode: number): string { // Implementation details would map codes to descriptions // For example: // if (statusCode === 0x6a82) return "NHSO applet not found on this card"; // ... other status codes return "Unknown status code"; } ``` -------------------------------- ### Add Listener to Beginning of Event Queue Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Adds a listener function to the start of the event queue for a specific event. This ensures the listener is executed before any other listeners for the same event. ```typescript public prependListener( event: K, listener: EventListener ): this // This handler runs BEFORE other card-data handlers cardReader.prependListener('card-data', (event) => { console.log('Priority handler called first'); }); // This handler runs AFTER the prepended one cardReader.on('card-data', (event) => { console.log('Normal handler called second'); }); ``` -------------------------------- ### Handle Card Errors Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Example of handling card-related errors using the 'card-error' event. It logs the error status and description, and provides specific messages for common error codes. ```javascript cardReader.on('card-error', (event) => { console.error(`Error (${event.status}): ${event.description}`); console.error('Details:', event.data.message); switch (event.status) { case 400: console.log('Please insert a valid Thai National ID Card'); break; case 404: console.log('Card reader not found - check connections'); break; case 500: console.log('Card reading failed:', event.data.error); break; } }); ``` -------------------------------- ### Minimal Thai ID Card Reader Configuration Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Initializes the reader with default settings for minimal configuration. Uses `exitOnReadError: true` and `debug: false`. ```typescript import { ThaiIdCardReader } from 'thai-national-id-card-reader'; // Uses all defaults: exitOnReadError: true, debug: false const reader = new ThaiIdCardReader(); reader.on('card-data', (event) => { console.log('Card data:', event.data); }); reader.init(); ``` -------------------------------- ### Safely Get Data from Card Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/utilities.md Executes an APDU command and retrieves data, handling potential errors and removing status bytes. Use this for robust data reading operations. ```typescript async function safeGetData(card, command, req) { try { const data = await getData(card, command, req); // Remove status bytes and return return data.slice(0, -2); } catch (error) { console.error('Command failed:', error.message); throw new Error(`Data read failed: ${error.message}`); } } ``` -------------------------------- ### Instantiate ThaiIdCardReader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Create a new instance of the ThaiIdCardReader with optional configuration. Use this to set up debugging or error handling behavior. ```typescript import { ThaiIdCardReader } from 'thai-national-id-card-reader'; const cardReader = new ThaiIdCardReader({ debug: false, exitOnReadError: false }); cardReader.on('card-data', (event) => { console.log('Card data:', event.data); }); cardReader.init(); ``` -------------------------------- ### Promise-based Integration Patterns Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/SUMMARY.txt Demonstrates advanced patterns for integrating card reading operations within a larger asynchronous application using Promises. ```javascript import { ThaiIdCardReader } from "thai-id-card-reader"; async function processCardData() { const reader = new ThaiIdCardReader(); try { const personalData = await reader.getPersonalData(); const nhsoData = await reader.getNhsoData(); console.log("Personal Data:", personalData); console.log("NHSO Data:", nhsoData); // Further processing... } catch (error) { console.error("Error during card processing:", error); } finally { reader.destroy(); } } processCardData(); ``` -------------------------------- ### Select NHSO Applet Command Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-nhso.md This command activates the NHSO applet on the smartcard. It must be executed before any other NHSO data reading commands. Ensure the card contains the NHSO applet for this command to succeed. ```typescript SELECT: [0x00, 0xa4, 0x04, 0x00, 0x08, 0xa0, 0x00, 0x00, 0x00, 0x54, 0x48, 0x00, 0x83] ``` -------------------------------- ### ESM Usage of Thai National ID Card Reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Demonstrates the use of the Thai National ID Card Reader with ECMAScript Modules (ESM). Features similar event handling and initialization as the CommonJS example. ```javascript import { ThaiIdCardReader } from 'thai-national-id-card-reader'; // Create reader instance - automatically reads ALL fields const cardReader = new ThaiIdCardReader({ debug: false, // Enable for troubleshooting exitOnReadError: false // Don't exit on read errors }); // Set up event listeners (same as CommonJS example) cardReader.on('device-connected', (event) => { console.log('✅ Card reader connected:', event.data.message); }); cardReader.on('card-data', (event) => { const data = event.data; console.log('📄 Thai National ID Card Data:'); console.log('├─ Citizen ID:', data.cid); console.log('├─ Thai Name:', data.name); // ... rest of data processing }); // Initialize and start reading cardReader.init(); console.log('🚀 Thai National ID Card Reader initialized. Insert a card...'); // Graceful shutdown process.on('SIGINT', () => { console.log(' 🛑 Shutting down...'); cardReader.destroy(); process.exit(0); }); ``` -------------------------------- ### Production Configuration for Thai ID Card Reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Sets up the reader for production environments with graceful error handling and minimal logging overhead. `exitOnReadError` is `false` and `debug` is `false`. ```typescript const reader = new ThaiIdCardReader({ exitOnReadError: false, // Graceful error handling debug: false // No debug overhead }); reader.on('card-data', (event) => { // Validate data if (!event.data.cid) { logger.warn('Missing CID in card data'); return; } // Process validated data try { const result = await saveCardDataToDB(event.data); logger.info(`Card processed: ${event.data.cid}`); } catch (error) { logger.error(`Failed to save card data: ${error.message}`); } }); reader.on('card-error', (event) => { // Log error for monitoring logger.error(`Card read failed: ${event.data.message}`, { status: event.status, timestamp: new Date().toISOString() }); // Alert system or trigger retry logic alertMonitoring('Card reader error detected'); }); reader.init(); ``` -------------------------------- ### ThaiIdCardReader Constructor Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md Initializes a new instance of the Thai National ID Card Reader. Accepts an optional configuration object to customize reader behavior. ```APIDOC ## Constructor ThaiIdCardReader ### Description Creates a new instance of the Thai National ID Card Reader. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | options | CardReaderOptions | No | `{}` | Configuration object for reader behavior | ### Request Example ```typescript import { ThaiIdCardReader } from 'thai-national-id-card-reader'; const cardReader = new ThaiIdCardReader({ debug: false, exitOnReadError: false }); cardReader.on('card-data', (event) => { console.log('Card data:', event.data); }); cardReader.init(); ``` ### Response #### Success Response (200) Returns a `ThaiIdCardReader` instance extending `CardReaderEventEmitter`. #### Response Example None explicitly provided, but returns an instance of `ThaiIdCardReader`. ``` -------------------------------- ### Convert Buddhist Year Date to Gregorian Format Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/personal-applet.md Converts a date string from Buddhist year format (YYYYMMDD) to Gregorian format (YYYY-MM-DD). The conversion logic subtracts 543 from the Buddhist year to get the Gregorian year. ```typescript private convertBuddhistToGregorianDate(buddhistDateStr: string): string ``` -------------------------------- ### Initialize ThaiIdCardReader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Constructor for the ThaiIdCardReader class. Accepts optional configuration options. ```typescript new ThaiIdCardReader(options?: CardReaderOptions) ``` -------------------------------- ### Check Hardware Connection (Linux) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md On Linux, use lsusb to list USB devices and check if the card reader hardware is detected at the USB level. ```bash lsusb ``` -------------------------------- ### Handle NhsoApplet Initialization and Data Retrieval Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Use a try-catch block to gracefully handle potential errors during NhsoApplet initialization or data retrieval. This snippet logs available fields on success or a message indicating the applet is not available on the card. ```typescript try { const nhsoData = await nhsoApplet.getInfo(); // May contain partial data if some fields failed console.log('Available fields:', Object.keys(nhsoData)); } catch (error) { // NHSO applet not available on this card console.log('Health insurance data not available'); } ``` -------------------------------- ### NhsoApplet Constructor Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Creates a new NhsoApplet instance for reading health insurance data from a specific card. It takes a Card instance and an optional APDU request command. ```APIDOC ## Constructor NhsoApplet ### Description Creates a new NhsoApplet instance for reading health insurance data from a specific card. ### Parameters #### Path Parameters - **card** (Card) - Required - Smartcard instance from @nonth/smartcard - **requestCommand** (number[]) - Optional - APDU request command bytes. Defaults to [0x00, 0xc0, 0x00, 0x00]. ### Returns `NhsoApplet` instance ### Throws None ``` -------------------------------- ### Full Event Handling Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/SUMMARY.txt Demonstrates comprehensive event handling for various card reader states, including connection, disconnection, insertion, data retrieval, removal, and errors. ```javascript import { ThaiIdCardReader } from "thai-id-card-reader"; const reader = new ThaiIdCardReader(); reader.on("device-connected", () => console.log("Device connected")); reader.on("device-disconnected", () => console.log("Device disconnected")); reader.on("card-inserted", () => console.log("Card inserted")); reader.on("card-data", (data) => console.log("Card data:", data)); reader.on("card-removed", () => console.log("Card removed")); reader.on("card-error", (error) => console.error("Card error:", error)); reader.on("card-incorrect", () => console.log("Incorrect card type")); // ... rest of your code reader.destroy(); ``` -------------------------------- ### Create PersonalApplet Instance Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/personal-applet.md Instantiates a PersonalApplet for reading personal information from a smartcard. The requestCommand parameter is optional and defaults to [0x00, 0xc0, 0x00, 0x00]. ```typescript new PersonalApplet( card, requestCommand?: number[] ): PersonalApplet ``` -------------------------------- ### Verify System PC/SC on macOS Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Use the `system_profiler` command to check the system's PC/SC status on macOS. This helps in diagnosing issues related to the card reader's detection. ```bash # macOS: Verify system PC/SC system_profiler SPUSBDataType ``` -------------------------------- ### PersonalApplet Constructor Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/personal-applet.md Creates a new PersonalApplet instance for reading personal information from a specific card. It takes a Card instance and an optional APDU request command. ```APIDOC ## Constructor PersonalApplet ### Description Creates a new PersonalApplet instance for reading personal information from a specific card. ### Parameters #### Path Parameters - **card** (Card) - Required - Smartcard instance from @nonth/smartcard - **requestCommand** (number[]) - Optional - APDU request command bytes. Defaults to [0x00, 0xc0, 0x00, 0x00]. ### Returns `PersonalApplet` instance ### Throws None ``` -------------------------------- ### List Available Card Readers Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md This command scans and lists all available smart card readers connected to the system. It helps in identifying if the reader is recognized by the PC/SC layer. ```bash pcsc_scan ``` -------------------------------- ### Code Quality Commands Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/CLAUDE.md Commands for running ESLint and Prettier for code linting and formatting checks. ```bash npm run lint # ESLint check npm run lint:fix # Auto-fix ESLint issues npm run format # Format with Prettier npm run format:check # Check Prettier formatting ``` -------------------------------- ### Importing with ESM Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md Use import statements for modern Node.js environments or bundlers. Default import is also available. ```javascript // Works in modern Node.js with "type": "module" or .mjs files import { ThaiIdCardReader, ErrorCodes } from 'thai-national-id-card-reader'; // Also works with default import import ThaiIdCardReader from 'thai-national-id-card-reader'; ``` -------------------------------- ### Server Application Configuration for Thai ID Card Reader Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Sets up the reader for a server application, ensuring the server remains operational after read errors. `exitOnReadError` is `false` and `debug` is `false`. ```typescript const reader = new ThaiIdCardReader({ exitOnReadError: false, // Keep server running debug: false // Clean logs }); reader.on('card-data', (event) => { // Process card data const cidData = { cid: event.data.cid, name: event.data.name, timestamp: new Date().toISOString() }; // Save to database, send to API, etc. processCardData(cidData); }); reader.on('card-error', (event) => { logger.error('Card read error', { message: event.data.message, status: event.status }); // Server continues, can retry with next card }); reader.init(); ``` -------------------------------- ### Code Quality and Formatting Commands Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/README.md A set of npm scripts for maintaining code quality, including linting for style issues and formatting with Prettier. Use lint:fix to automatically resolve fixable issues. ```bash npm run lint ``` ```bash npm run lint:fix ``` ```bash npm run format ``` ```bash npm run typecheck ``` -------------------------------- ### getInfo() Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Extracts NHSO (health insurance) information from the card. Initializes the NHSO applet and reads all available health insurance data fields. Returns partial data if some fields fail. ```APIDOC ## Method: getInfo() ### Description Extract NHSO (health insurance) information from the card. Initializes the NHSO applet and reads all available health insurance data fields. ### Method `public async getInfo(): Promise` ### Parameters None ### Returns `Promise` - Promise resolving to NHSO data object with available fields ### Throws - `Error` - If NHSO applet initialization fails - `Error` - If NHSO data cannot be read ### Notes - Returns partial data if some fields fail (graceful degradation) - Health insurance data is optional; NHSO applet not present on all cards - All dates are converted from Buddhist to Gregorian calendar automatically ### Request Example ```typescript import { NhsoApplet } from 'thai-national-id-card-reader'; // Assuming 'card' is a Card instance from smartcard reader const nhsoApplet = new NhsoApplet(card); try { const healthData = await nhsoApplet.getInfo(); console.log('Health Insurance Information:'); console.log('Main Insurance Level:', healthData.mainInscl); console.log('Main Hospital:', healthData.mainHospitalName); console.log('Issue Date:', healthData.issueDate); console.log('Expiration Date:', healthData.expireDate); } catch (error) { console.log('NHSO data not available on this card'); } ``` ### Response #### Success Response (200) - **mainInscl** (string) - Main insurance level - **mainHospitalName** (string) - Name of the main hospital - **issueDate** (string) - Date when the insurance was issued (Gregorian format) - **expireDate** (string) - Date when the insurance expires (Gregorian format) - **subHospitalName** (string) - Name of the secondary hospital (optional) - **paidType** (string) - Type of payment (optional) ``` -------------------------------- ### SELECT Command for Applet Selection Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/apdu-person.md This command selects the card applet application. It must be issued before reading personal data. The command specifies selection by application name and expects an 8-byte AID. ```typescript SELECT: [0x00, 0xa4, 0x04, 0x00, 0x08] ``` -------------------------------- ### Handle Device Connection Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/thai-id-card-reader.md This snippet logs details about the connected card reader, including the specific device, a message, and a list of all available devices. ```typescript cardReader.on('device-connected', (event) => { console.log('Reader connected:', event.data.device); console.log('Message:', event.data.message); console.log('All devices:', event.data.devices); }); ``` -------------------------------- ### Type-Safe Event Handling with TypeScript Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Illustrates valid and invalid event registrations using TypeScript for type safety, ensuring correct event names and data properties. ```typescript // ✓ Valid - TypeScript knows card-data has CardDataEvent type cardReader.on('card-data', (event) => { console.log(event.data.cid); // ✓ cid exists on ThaiIdCardData }); // ✗ Invalid - TypeScript error: 'invalid-event' is not a valid event // cardReader.on('invalid-event', (event) => {}); // ✗ Invalid - TypeScript error: 'cid' does not exist on CardErrorEvent // cardReader.on('card-error', (event) => { // console.log(event.data.cid); // }); ``` -------------------------------- ### NhsoApplet getInfo Method Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Extracts NHSO (health insurance) information from the card. Initializes the NHSO applet and reads all available health insurance data fields. Returns partial data if some fields fail and converts Buddhist dates to Gregorian automatically. ```typescript public async getInfo(): Promise ``` -------------------------------- ### getAppletVersion() Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Retrieves the NHSO applet version information if available. This method is currently a placeholder for future implementation. ```APIDOC ## Method: getAppletVersion() ### Description Get NHSO applet version information if available. Currently a placeholder implementation for future use. ### Returns `Promise` - Version string or null if not available. ### Notes This method is currently a placeholder and returns `null`. Future versions may implement full version detection. ``` -------------------------------- ### Initialize Reader - Debug Mode Enabled Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Initializes the ThaiIdCardReader with debug logging enabled. This provides verbose output for troubleshooting, including lifecycle events, APDU communication, and card state changes. Recommended for development and testing. ```typescript const reader = new ThaiIdCardReader({ debug: true // Verbose logging enabled }); reader.init(); // Output: // [ThaiIdCardReader] Thai National ID Card Reader initialized successfully // [ThaiIdCardReader] Device activated // [ThaiIdCardReader] Card inserted // [ThaiIdCardReader] Starting card data extraction... // [ThaiIdCardReader] APDU Command sent: [0x00, 0xa4, 0x04, 0x00, ...] // [ThaiIdCardReader] APDU Response received: [0x90, 0x00] // [ThaiIdCardReader] Card data extracted successfully ``` -------------------------------- ### Core Library Architecture Flow Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/CLAUDE.md Visual representation of the event-driven flow from device detection to event emission. ```text Device Detection → Card Insertion → Data Reading → Event Emission ``` -------------------------------- ### Register Event Listeners with Priority Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/event-emitter.md Shows how to register a normal priority handler and a high-priority handler that runs first for the 'card-data' event. ```typescript // Low-priority handler (runs last) cardReader.on('card-data', (event) => { console.log('Normal priority handler'); }); // High-priority handler (runs first) cardReader.prependListener('card-data', (event) => { console.log('High priority handler - runs first'); }); ``` -------------------------------- ### NhsoApplet Constructor Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/nhso-applet.md Creates a new NhsoApplet instance for reading health insurance data from a specific card. The requestCommand parameter is optional and defaults to [0x00, 0xc0, 0x00, 0x00]. ```typescript new NhsoApplet( card: Card, requestCommand?: number[] ): NhsoApplet ``` -------------------------------- ### Initialize Reader - Debug Mode Disabled (Default) Source: https://github.com/nonth/thai-national-id-card-reader/blob/main/_autodocs/configuration.md Initializes the ThaiIdCardReader with debug logging disabled. This results in minimal console output, logging only errors, which is appropriate for production environments. ```typescript const reader = new ThaiIdCardReader({ debug: false // Normal operation, minimal logging }); reader.init(); // Output: Only errors (if any) ```