hikvision-isapi-client
Version:
Enhanced TypeScript version of hikvision-isapi-client with modern features, type safety, and video decoding
459 lines (352 loc) • 11.8 kB
Markdown
# hikvision-isapi-client
A modern TypeScript toolkit for connecting and controlling Hikvision equipment with enhanced error handling, dependency injection, and type safety.
[](https://badge.fury.io/js/@chenluoi%2Fhikvision-api)
[](https://opensource.org/licenses/MIT)
[](https://www.typescriptlang.org/)
> **Note**: This is an enhanced TypeScript version with additional features. For the original JavaScript implementation, see [hikvision-isapi-client](https://github.com/itskamol/hikvision-api).
## 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
```bash
npm install hikvision-isapi-client
```
```bash
yarn add hikvision-isapi-client
```
```bash
pnpm add hikvision-isapi-client
```
## Why This Fork?
This project builds upon the excellent work from [hikvision-isapi-client](https://github.com/itskamol/hikvision-api) 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:
```typescript
// 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
```typescript
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
```typescript
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
```typescript
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
```typescript
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 wiper
```
### Video Decoding
The library includes a WebAssembly-based video decoder for real-time streaming:
```typescript
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
```typescript
// 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
```typescript
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 issues
- `AuthenticationError` - Invalid credentials
- `ValidationError` - Configuration validation errors
- `ApiError` - API request failures
- `TimeoutError` - Request timeouts
- `DeviceNotFoundError` - Device not reachable
## Migration Guide
### From v0.1.x to v0.2.x
The library now uses dependency injection for better testability and flexibility:
```typescript
// 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:
```typescript
// 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
```typescript
// Increase timeout for slow networks
const nvr = new Nvr({
...config,
timeout: 30000 // 30 seconds
});
```
#### CORS Issues in Browser
```typescript
// Use proxy for browser environments
const nvr = new Nvr({
...config,
proxy: 'http://localhost:8080/proxy'
});
```
#### Authentication Errors
```typescript
// Ensure correct API version
const nvr = new Nvr({
...config,
version: 2 // Try version 1 if version 2 fails
});
```
#### Memory Issues with Video Decoder
```typescript
// Limit buffer pool size
worker.postMessage({
command: 'OpenStream',
data: streamHeader,
dataSize: streamHeader.length,
bufPoolSize: 512 * 1024 // Reduce buffer size
});
```
## Development
```bash
# 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:check
```
## Changelog
### 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:
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Make your changes with proper tests
4. Run quality checks (`npm run quality:check`)
5. Commit your changes (`git commit -m 'Add some amazing feature'`)
6. Push to the branch (`git push origin feature/amazing-feature`)
7. 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
- 📖 [Documentation](https://github.com/ChenLuoi/hikvision-api#readme)
- 🐛 [Issues](https://github.com/ChenLuoi/hikvision-api/issues)
- 💬 [Discussions](https://github.com/ChenLuoi/hikvision-api/discussions)
## Acknowledgments
This project is built upon the foundation of [hikvision-isapi-client](https://github.com/itskamol/hikvision-api) by [itskamol](https://github.com/itskamol). We extend our gratitude for the original implementation and continue to build upon that excellent work.
### Related Projects
- [hikvision-isapi-client](https://github.com/itskamol/hikvision-api) - Original JavaScript implementation
- [hikvision-api](https://www.npmjs.com/search?q=hikvision-api) - Alternative Hikvision clients
## License
MIT License - see the [LICENSE](LICENSE) file for details.
---
Made with ❤️ by [ChenLuo](https://github.com/ChenLuoi) | Built upon [itskamol's hikvision-isapi-client](https://github.com/itskamol/hikvision-api)