hikvision-isapi-client
v0.1.52
Published
Enhanced TypeScript version of hikvision-isapi-client with modern features, type safety, and video decoding
Maintainers
Readme
hikvision-isapi-client
A modern TypeScript toolkit for connecting and controlling Hikvision equipment with enhanced error handling, dependency injection, and type safety.
Note: This is an enhanced TypeScript version with additional features. For the original JavaScript implementation, see hikvision-isapi-client.
Features
Enhanced Features (vs. original hikvision-api)
- 🔒 Type Safety - Full TypeScript support with strict typing
- 🛡️ Error Handling - Comprehensive error handling with custom error types
- 🔧 Dependency Injection - Configurable HTTP client, logger, and validator
- 📦 Modern Architecture - Clean barrel exports and modular design
- ✅ Testing - Comprehensive test coverage with Jest
- 🚀 Performance - Optimized build with tree shaking
- 🎥 Video Decoding - WebAssembly-based video decoder for real-time streaming
- 🌐 Cross-Platform - Works in Node.js and browsers
- 🔄 Retry Logic - Built-in retry mechanism for network failures
- 📊 Better Logging - Structured logging with configurable levels
Installation
npm install hikvision-isapi-clientyarn add hikvision-isapi-clientpnpm add hikvision-isapi-clientWhy This Fork?
This project builds upon the excellent work from hikvision-isapi-client with the following enhancements:
| Feature | Original | This Version | | -------------- | ---------- | ---------------------------------- | | Language | JavaScript | TypeScript | | Type Safety | ❌ | ✅ Full TypeScript support | | Error Handling | Basic | ✅ Custom error types & retry logic | | Testing | Limited | ✅ Comprehensive test suite | | Architecture | Monolithic | ✅ Dependency injection | | Video Decoding | ❌ | ✅ WebAssembly decoder | | Documentation | Basic | ✅ Comprehensive API docs | | Build System | Webpack | ✅ ESBuild (faster) | | Package Size | Larger | ✅ Tree-shakable |
Migration from Original
If you're migrating from hikvision-isapi-client, the API is largely compatible:
// Original
const { Nvr } = require('hikvision-isapi-client');
// This version
import { Nvr } from 'hikvision-isapi-client';
// Same API, enhanced with TypeScript
const nvr = new Nvr(config);Quick Start
Basic Usage
import { Nvr, Camera } from 'hikvision-isapi-client';
// Create NVR instance
const nvr = new Nvr({
ip: '192.168.1.64',
user: 'admin',
password: 'your-password',
version: 2
});
// Connect and use
await nvr.connect();
const channels = await nvr.fetchChannels();
const users = await nvr.fetchUsers();Advanced Usage with Dependency Injection
import {
Nvr,
AxiosHttpClient,
ConsoleLogger,
DefaultConfigValidator
} from 'hikvision-isapi-client';
import axios from 'axios';
// Create custom HTTP client with timeout
const httpClient = new AxiosHttpClient(
axios.create({ timeout: 15000 })
);
// Create custom logger
const logger = new ConsoleLogger();
// Create NVR with custom dependencies
const nvr = new Nvr(
{
ip: '192.168.1.64',
user: 'admin',
password: 'your-password',
version: 2
},
httpClient,
logger,
new DefaultConfigValidator()
);Error Handling
import {
Nvr,
ConnectionError,
AuthenticationError,
ApiError
} from 'hikvision-isapi-client';
try {
const nvr = new Nvr(config);
await nvr.connect();
const deviceInfo = await nvr.deviceInfo();
} catch (error) {
if (error instanceof ConnectionError) {
console.error('Network connection failed:', error.message);
} else if (error instanceof AuthenticationError) {
console.error('Invalid credentials:', error.message);
} else if (error instanceof ApiError) {
console.error('API error:', error.message, 'Status:', error._statusCode);
}
}Camera Control
import { Camera } from 'hikvision-isapi-client';
const camera = new Camera({
ip: '192.168.1.100',
user: 'admin',
password: 'your-password'
});
await camera.connect();
// PTZ Control
await camera.direction(1, 0); // Move right
await camera.zoom(1); // Zoom in
await camera.focus(1); // Focus
// Auxiliary controls
await camera.light(true); // Turn on light
await camera.wiper(true); // Turn on wiperVideo Decoding
The library includes a WebAssembly-based video decoder for real-time streaming:
import { getDecodeWorker } from 'hikvision-isapi-client';
// Create decoder worker
const isBrowser = typeof window !== 'undefined';
const wasmUrl = '/path/to/decoder.wasm';
const workerCode = getDecodeWorker(isBrowser, wasmUrl);
// Create worker
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));
// Handle decoded frames
worker.onmessage = (event) => {
const { function: func, type, data, frameInfo } = event.data;
if (func === 'GetFrameData') {
if (type === 'videoType') {
// Handle YUV video frame
const yuvData = new Uint8Array(data);
renderFrame(yuvData, frameInfo.width, frameInfo.height);
} else if (type === 'audioType') {
// Handle PCM audio frame
const pcmData = new Uint8Array(data);
playAudio(pcmData);
}
}
};
// Initialize decoder
worker.postMessage({
command: 'SetStreamOpenMode',
data: 0 // Stream mode
});
// Open stream
worker.postMessage({
command: 'OpenStream',
data: streamHeader,
dataSize: streamHeader.length,
bufPoolSize: 1024 * 1024
});
// Input stream data
worker.postMessage({
command: 'InputData',
data: streamData,
dataSize: streamData.length
});API Reference
NVR Methods
// Connection
await nvr.connect();
await nvr.disconnect();
// Device Information
const info = await nvr.deviceInfo();
await nvr.updateDeviceInfo(newInfo);
// Channel Management
const channels = await nvr.fetchChannels();
const channelId = await nvr.addChannel(channelData);
await nvr.editChannel(channelId, newData);
await nvr.deleteChannel(channelId);
// User Management
const users = await nvr.fetchUsers();
await nvr.addUser(userData);
await nvr.updateUser(userData);
await nvr.deleteUser(userId);
// Storage
const storages = await nvr.getStorages();
await nvr.formatHdd(hddId, progressCallback);
// Recording
const records = await nvr.searchRecords(channelId, streamType, startTime, endTime, pageNo, pageSize);
const allRecords = await nvr.searchAllRecords(channelId, streamType, startTime, endTime);Configuration Options
interface BaseConfig {
ip: string; // Device IP address
port?: number; // Port (default: 80)
user: string; // Username
password: string; // Password
timeout?: number; // Request timeout (default: 10000ms)
proxy?: string; // Proxy URL for CORS
version?: number; // API version (1 or 2, default: 1)
userPassword?: string; // Default password for new users
}
interface NvrConfig extends BaseConfig {
wsPort?: number; // WebSocket port (default: 7681)
wasmUrl?: string; // WASM decoder URL
channelOffset?: number; // Channel offset (default: 32)
}Error Types
ConnectionError- Network connection issuesAuthenticationError- Invalid credentialsValidationError- Configuration validation errorsApiError- API request failuresTimeoutError- Request timeoutsDeviceNotFoundError- Device not reachable
Migration Guide
From v0.1.x to v0.2.x
The library now uses dependency injection for better testability and flexibility:
// Old way
const nvr = new Nvr(config);
// New way (backward compatible)
const nvr = new Nvr(config);
// New way with custom dependencies
const nvr = new Nvr(config, httpClient, logger, validator);Error handling is now more structured:
// Old way
try {
await nvr.connect();
} catch (error) {
console.error('Error:', error.message);
}
// New way
try {
await nvr.connect();
} catch (error) {
if (error instanceof AuthenticationError) {
// Handle auth error specifically
}
}Troubleshooting
Common Issues
Connection Timeout
// Increase timeout for slow networks
const nvr = new Nvr({
...config,
timeout: 30000 // 30 seconds
});CORS Issues in Browser
// Use proxy for browser environments
const nvr = new Nvr({
...config,
proxy: 'http://localhost:8080/proxy'
});Authentication Errors
// Ensure correct API version
const nvr = new Nvr({
...config,
version: 2 // Try version 1 if version 2 fails
});Memory Issues with Video Decoder
// Limit buffer pool size
worker.postMessage({
command: 'OpenStream',
data: streamHeader,
dataSize: streamHeader.length,
bufPoolSize: 512 * 1024 // Reduce buffer size
});Development
# Install dependencies
npm install
# Run tests
npm test
npm run test:watch
npm run test:coverage
# Build
npm run build
# Lint and format
npm run lint
npm run lint:fix
npm run format
# Type check
npm run type-check
# Quality check (all checks)
npm run quality:checkChangelog
v0.1.51
- ✨ Added scoped package name
hikvision-isapi-client - 🔧 Improved TypeScript types and error handling
- 📦 Updated .npmignore for cleaner package
- 🎥 Enhanced video decoder with better memory management
- ✅ Comprehensive test coverage improvements
v0.1.x
- 🚀 Initial release with basic NVR and Camera support
- 🔒 TypeScript support and type safety
- 🛡️ Custom error handling system
- 🔧 Dependency injection architecture
Contributing
We welcome contributions! Please follow these steps:
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Make your changes with proper tests
- Run quality checks (
npm run quality:check) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Guidelines
- Write tests for new features
- Follow TypeScript best practices
- Use conventional commit messages
- Update documentation for API changes
- Ensure all quality checks pass
Support
Acknowledgments
This project is built upon the foundation of hikvision-isapi-client by itskamol. We extend our gratitude for the original implementation and continue to build upon that excellent work.
Related Projects
- hikvision-isapi-client - Original JavaScript implementation
- hikvision-api - Alternative Hikvision clients
License
MIT License - see the LICENSE file for details.
Made with ❤️ by ChenLuo | Built upon itskamol's hikvision-isapi-client
