@supernick135/face-scanner-client
Version:
Node.js client library for ZKTeco face scanning devices integration with comprehensive API support
143 lines (118 loc) ⢠4.44 kB
JavaScript
/**
* Face Scanner Student Client Example
*
* This example demonstrates how to use the Face Scanner WebSocket client
* for a student to receive their own scan notifications with API key authentication.
*/
require('dotenv').config();
const WebSocketClient = require('../lib/client/WebSocketClient');
async function studentExample() {
console.log('š Starting Face Scanner Student Client Example');
// Use configuration from .env file
const config = {
wsUrl: process.env.WS_URL || 'ws://localhost:8080/ws',
apiKey: process.env.STUDENT_TOKEN,
schoolId: process.env.SCHOOL_ID || 'sch001',
studentId: process.env.STUDENT_ID || 'std12345',
reconnect: process.env.RECONNECT === 'true',
heartbeatInterval: parseInt(process.env.HEARTBEAT_INTERVAL || '30000')
};
// Check if token is configured
if (!config.apiKey || config.apiKey === 'your-student-token-here') {
console.error('ā Please configure STUDENT_TOKEN in .env file');
process.exit(1);
}
// Create student client using API key authentication
const studentClient = WebSocketClient.createStudentClient(config);
// Set up event listeners
studentClient.on('connected', () => {
console.log('ā
Student connected to Face Scanner server');
});
studentClient.on('authenticated', () => {
console.log('š Student authenticated successfully');
console.log('š” Student will automatically receive scan notifications for their ID');
});
studentClient.on('authError', (error) => {
console.error('ā Authentication failed:', error.message);
});
studentClient.on('disconnected', ({ code, reason }) => {
console.log(`š Student disconnected: ${code} - ${reason}`);
});
studentClient.on('reconnecting', (attempt) => {
console.log(`š Attempting to reconnect... (${attempt})`);
});
studentClient.on('error', (error) => {
console.error('ā WebSocket error:', error);
});
// Listen for face scan events related to this student
studentClient.on('faceDetected', (data) => {
console.log('š¤ Face detected for you:', {
deviceId: data.deviceId,
confidence: data.confidence,
timestamp: new Date(data.timestamp).toLocaleString()
});
});
studentClient.on('scanComplete', (data) => {
console.log('ā
Scan completed for you:', {
deviceId: data.deviceId,
success: data.success || 'completed',
timestamp: new Date(data.timestamp).toLocaleString()
});
// Show success message
if (data.success) {
console.log('š Your attendance has been recorded successfully!');
}
});
studentClient.on('noFace', (data) => {
console.log('š» No face detected during your scan attempt:', {
deviceId: data.deviceId,
reason: data.reason,
timestamp: new Date(data.timestamp).toLocaleString()
});
});
studentClient.on('faceError', (data) => {
console.log('ā ļø Error during your face scan:', {
deviceId: data.deviceId,
error: data.error,
timestamp: new Date(data.timestamp).toLocaleString()
});
});
// Listen for system alerts
studentClient.on('systemAlert', (data) => {
console.log('š¢ System alert:', data);
});
// Handle pong responses
studentClient.on('pong', (data) => {
console.log('š Received pong from server, connection is healthy');
});
try {
// Connect to server
await studentClient.connect();
// Send periodic pings to keep connection alive
const pingInterval = setInterval(() => {
if (studentClient.isConnected) {
studentClient.sendPingMessage();
console.log('š Sent ping to server');
}
}, 45000); // Every 45 seconds
// Keep running and listening for events
console.log('š Student client is now listening for scan events...');
console.log('ā±ļø Client will run for 2 minutes for demonstration...');
setTimeout(() => {
console.log('š Shutting down student client');
clearInterval(pingInterval);
studentClient.disconnect();
process.exit(0);
}, 120000); // Run for 2 minutes
} catch (error) {
console.error('ā Failed to start student client:', error);
process.exit(1);
}
}
// Handle process termination
process.on('SIGINT', () => {
console.log('\nš Received SIGINT, shutting down gracefully...');
process.exit(0);
});
// Run the example
studentExample().catch(console.error);