imou-openapi-client
v1.1.0
Published
TypeScript client library for Imou Open API
Maintainers
Readme
Imou OpenAPI TypeScript Client
A comprehensive TypeScript client library for the Imou Open Platform API, providing complete access to Imou camera and IoT device management, recording, live streaming, and cloud storage.
Features
- Full TypeScript Support: Complete type definitions for all API responses and parameters
- Device Management: List, bind, unbind, control, and monitor Imou devices
- Web Interface: Complete web-based control panel with device addition/removal
- Sub-Account Management: Create and manage sub-accounts with granular permissions
- Live Streaming: Create, manage, and schedule live streams
- Recording Management: Access local and cloud recordings with download capabilities
- Cloud Storage: Manage cloud storage services and strategies
- PTZ Control: Pan, tilt, and zoom operations for supported cameras
- IoT Integration: Control IoT devices and read sensor data
- Local Storage: Download and save recordings to local file system (Node.js)
- Error Handling: Comprehensive error handling with specific exception types
- Automatic Token Management: Handles authentication and token refresh automatically
Installation
npm install imou-openapi-clientQuick Start
import { ImouClient } from 'imou-openapi-client';
// Initialize the client
const client = new ImouClient({
appId: 'your-app-id',
appSecret: 'your-app-secret',
apiUrl: 'openapi.easy4ip.com:443' // optional, uses default if not provided
});
// Initialize and get access token
await client.initialize();
// Get all devices
const devices = await client.deviceManager.getDevices();
console.log('Found devices:', devices.length);
// Control a camera
const device = devices[0];
const channel = device.getFirstChannel();
if (device.hasCapability('PTZ')) {
await client.deviceManager.movePTZUp(device.deviceId, channel.channelId, 1000);
}
// Create live stream
const liveStream = await client.liveStreamManager.createLiveStream({
deviceId: device.deviceId,
channelId: channel.channelId,
streamId: 0
});
console.log('Live stream URL:', liveStream.url);
// Get recordings
const recordings = await client.recordingManager.queryLocalRecords({
deviceId: device.deviceId,
channelId: channel.channelId,
beginTime: '2024-01-01 00:00:00',
endTime: '2024-01-01 23:59:59',
queryRange: '1-10'
});
console.log('Found recordings:', recordings.length);API Reference
ImouClient
Main client class that provides access to all functionality through specialized managers.
const client = new ImouClient({
appId: string;
appSecret: string;
apiUrl?: string;
timeout?: number;
});
// Available managers:
client.deviceManager // Device operations
client.subAccountManager // Sub-account management
client.liveStreamManager // Live streaming
client.recordingManager // Recording operations
client.cloudStorageManager // Cloud storage managementDevice Management
// Get devices with pagination
const devices = await client.deviceManager.getDevices({ page: 1, pageSize: 20 });
// Bind device to account
await client.deviceManager.bindDevice('DEVICE_SERIAL', 'device_password');
// Unbind device
await client.deviceManager.unbindDevice('DEVICE_SERIAL');
// Get device online status
const status = await client.deviceManager.getDeviceOnlineStatus(deviceId);
// Restart device
await client.deviceManager.restartDevice(deviceId);
// Get device storage info
const storage = await client.deviceManager.getDeviceStorage(deviceId);Sub-Account Management
// Create sub-account
const subAccount = await client.subAccountManager.createSubAccount('[email protected]');
// Grant device access to sub-account
await client.subAccountManager.grantDeviceAccess(
subAccount.openId,
deviceId,
channelId,
['Live', 'RecordReplay', 'Control']
);
// Get sub-account token
const tokenInfo = await client.subAccountManager.getSubAccountToken(subAccount.openId);
// List all sub-accounts
const subAccounts = await client.subAccountManager.listSubAccounts();
// Delete sub-account
await client.subAccountManager.deleteSubAccount(subAccount.openId);Live Streaming
// Create live stream
const liveStream = await client.liveStreamManager.createLiveStream({
deviceId,
channelId,
streamId: 0
});
// Set live stream schedule
await client.liveStreamManager.setLiveSchedule(
liveStream.token,
'09:00:00',
'18:00:00',
'Monday,Tuesday,Wednesday,Thursday,Friday'
);
// Enable/disable live stream
await client.liveStreamManager.enableLiveStream(liveStream.token);
await client.liveStreamManager.disableLiveStream(liveStream.token);
// Get all live streams for device
const streams = await client.liveStreamManager.getDeviceLiveStreams(deviceId, channelId);
// Check if stream is active
const isActive = await client.liveStreamManager.isLiveStreamActive(liveStream.token);Recording Management
// Query local recordings
const localRecords = await client.recordingManager.queryLocalRecords({
deviceId,
channelId,
beginTime: '2024-01-01 00:00:00',
endTime: '2024-01-01 23:59:59',
queryRange: '1-30'
});
// Query cloud recordings
const cloudRecords = await client.recordingManager.queryCloudRecords({
deviceId,
channelId,
beginTime: '2024-01-01 00:00:00',
endTime: '2024-01-01 23:59:59',
queryRange: '1-30'
});
// Download recording to local storage (Node.js)
const filePath = await client.recordingManager.downloadLocalRecording(
localRecords[0],
'/path/to/save/recording.mp4',
deviceId,
channelId
);
// Batch download recordings
const downloadedFiles = await client.recordingManager.batchDownloadRecordings(
localRecords.slice(0, 5),
'/path/to/recordings/',
deviceId,
channelId
);
// Set up continuous recording
await client.recordingManager.setupContinuousRecording(deviceId, channelId, 'main');
// Set up motion-triggered recording
await client.recordingManager.setupMotionRecording(deviceId, channelId, [
{ beginTime: '18:00:00', endTime: '06:00:00', weekDays: ['Monday', 'Tuesday'] }
]);Cloud Storage Management
// Get cloud storage status
const status = await client.cloudStorageManager.getCloudStorageStatus(deviceId);
// Setup cloud storage with automatic strategy selection
const strategy = await client.cloudStorageManager.setupCloudStorage(
deviceId,
channelId,
3 // preferred retention days
);
// Enable/disable cloud storage
await client.cloudStorageManager.enableDeviceCloudStorage(deviceId, channelId);
await client.cloudStorageManager.disableDeviceCloudStorage(deviceId, channelId);
// Get unused cloud storage options
const unusedStorage = await client.cloudStorageManager.getUnusedCloudStorageList();
// Get cloud storage statistics
const stats = await client.cloudStorageManager.getCloudStorageStats();PTZ Control
// Move camera
await client.deviceManager.movePTZUp(deviceId, channelId, 1000);
await client.deviceManager.movePTZDown(deviceId, channelId, 1000);
await client.deviceManager.movePTZLeft(deviceId, channelId, 1000);
await client.deviceManager.movePTZRight(deviceId, channelId, 1000);
// Or use the generic control method
await client.deviceManager.controlDevicePTZ({
deviceId,
channelId,
operation: PTZOperation.UP,
duration: 1000
});Device Settings
// Get/Set night vision mode
const nightVision = await client.deviceManager.getDeviceNightVisionMode(deviceId, channelId);
await client.deviceManager.setDeviceNightVisionMode({
deviceId,
channelId,
mode: 'Auto' // 'Auto' | 'Color' | 'BlackWhite'
});
// Get/Set device status
const status = await client.deviceManager.getDeviceStatus({
deviceId,
channelId,
enableType: 'motionDetect'
});
await client.deviceManager.setDeviceStatus({
deviceId,
channelId,
enableType: 'motionDetect',
enable: true
});Live Streaming
// Get existing stream URL
const streamInfo = await client.deviceManager.getStreamUrl(deviceId, channelId);
// Create new stream URL
const newStream = await client.deviceManager.createStreamUrl(deviceId, channelId, 0);
// Get device snapshot
const snapshot = await client.deviceManager.getDeviceSnap(deviceId, channelId);IoT Device Control
// Get IoT device properties
const properties = await client.deviceManager.getIoTDeviceProperties({
deviceId,
productId,
properties: ['battery', 'temperature']
});
// Set IoT device properties
await client.deviceManager.setIoTDeviceProperties({
deviceId,
productId,
properties: { light: true, volume: 50 }
});
// Control IoT device
await client.deviceManager.iotDeviceControl({
deviceId,
productId,
ref: '2300',
content: { action: 'restart' }
});Device Capabilities
The library includes comprehensive type definitions for device capabilities based on the Imou documentation:
- Class I Capabilities: Device-level capabilities (WLAN, CloudStorage, PTZ, etc.)
- Class II Capabilities: Channel-level capabilities (AlarmMD, FaceDetect, etc.)
- Class III Capabilities: Device or channel capabilities (AudioTalk, Electric, etc.)
// Check device capabilities
if (device.hasCapability('PTZ')) {
// Device supports PTZ control
}
if (device.hasCapability('FaceDetect')) {
// Device supports face detection
}
// Get all capabilities
const capabilities = device.getCapabilities();Error Handling
The library provides specific exception types for different error scenarios:
import {
ConnectFailedException,
RequestFailedException,
InvalidAppIdOrSecretException,
TokenExpiredException,
DeviceOfflineException
} from 'imou-openapi-client';
try {
await client.deviceManager.getDevices();
} catch (error) {
if (error instanceof InvalidAppIdOrSecretException) {
console.error('Invalid credentials:', error.message);
} else if (error instanceof DeviceOfflineException) {
console.error('Device is offline:', error.message);
} else if (error instanceof ConnectFailedException) {
console.error('Connection failed:', error.message);
}
}Configuration
Default Configuration
{
apiUrl: 'openapi.easy4ip.com:443',
timeout: 30000,
version: '1.0'
}Custom Configuration
const client = new ImouClient({
appId: 'your-app-id',
appSecret: 'your-app-secret',
apiUrl: 'custom-api-url.com:443',
timeout: 60000
});🎥 Complete Camera Control Panel
The library includes a complete web-based camera control panel with:
Features
- Live Preview: Real-time camera streaming
- PTZ Controls: Pan, tilt, zoom with adjustable duration
- Local Recording: Record directly to your server using FFmpeg
- Snapshots: Instant photo capture and download
- Device Settings: Night vision, motion detection controls
- File Management: Browse and download recordings/snapshots
Quick Start
- Setup Environment:
# Copy environment template
cp .env.example .env
# Edit with your Imou credentials
nano .env- Install and Run:
# Install dependencies
npm install
# Start the server (includes web interface)
./start.sh
# or
npm run server- Open Browser: Navigate to
http://localhost:3000
Architecture Flow
HTML Interface → Node.js Server → Imou API → Camera Device
↓ ↓ ↓ ↓
User Controls → REST Endpoints → Imou Cloud → Live Stream/Control
↓ ↓ ↓
Live Preview ← FFmpeg Recording ← ← ← ← ← Stream DataEnvironment Variables (.env)
IMOU_APP_ID=your_app_id_here
IMOU_APP_SECRET=your_app_secret_here
PORT=3000
RECORDINGS_DIR=./recordings
SNAPSHOTS_DIR=./snapshots
FFMPEG_PATH=/usr/local/bin/ffmpegSee setup.md for detailed installation instructions.
TypeScript Support
This library is written in TypeScript and provides complete type definitions:
import {
ImouDevice,
ImouChannel,
DeviceCapability,
PTZOperation,
NightVisionMode,
SubAccount,
LiveStreamInfo,
LocalRecord,
CloudRecord
} from 'imou-openapi-client';
// All API responses are fully typed
const devices: ImouDevice[] = await client.deviceManager.getDevices();
const device: ImouDevice = devices[0];
const channel: ImouChannel = device.getFirstChannel()!;
// Type-safe recording operations
const recordings: LocalRecord[] = await client.recordingManager.queryLocalRecords({
deviceId: device.deviceId,
channelId: channel.channelId,
beginTime: '2024-01-01 00:00:00',
endTime: '2024-01-01 23:59:59'
});License
MIT
Web Interface
The package includes a complete web-based control panel for managing your Imou devices:
Features
- Device Management: Add, remove, and select devices through an intuitive interface
- Live Preview: View real-time camera feeds with KitToken integration
- PTZ Controls: Pan, tilt, and zoom with on-screen controls
- Recording: Start/stop local recordings with FFmpeg integration
- Snapshots: Capture and save still images
- Device Storage: Monitor SD card status, usage, and format storage with visual progress bars
- Message Configuration: Set up webhook notifications for device events (alarm, device status, face analysis)
- Device Settings: Configure night vision modes, motion detection, camera status, and more
- Advanced Configuration:
- Zoom focus control with real-time adjustment
- Alarm sensitivity and detection region configuration
- Collection points management (create, delete, navigate to preset positions)
- WiFi network scanning and connection management
- OSD settings, frame reverse, fill light sensitivity
- Timezone and daylight saving time configuration
- Local recording plans and stream quality settings
- File Management: Browse and download recorded videos and snapshots
Access the Web Interface
- Start the server:
npm run server
# or
./start.shOpen your browser to
http://localhost:3000Use the "➕ Add Device" button to bind new devices to your account
For detailed device management instructions, see DEVICE_MANAGEMENT.md.
For device storage and message configuration, see DEVICE_STORAGE_AND_MESSAGING.md.
New API Endpoints
The server now includes comprehensive device configuration endpoints:
Device Storage:
GET /api/devices/:deviceId/storage- Get storage capacity with progress infoGET /api/devices/:deviceId/sdcard-status- Get SD card statusPOST /api/devices/:deviceId/format-sdcard- Format SD card
Message Configuration:
GET /api/message-callback- Get webhook configurationPOST /api/message-callback- Set webhook configuration
Device Settings:
GET /api/devices/:deviceId/channels/:channelId/night-vision- Get night vision modePOST /api/devices/:deviceId/channels/:channelId/night-vision- Set night vision modePOST /api/devices/:deviceId/channels/:channelId/motion-detection- Set motion detectionGET /api/devices/:deviceId/channels/:channelId/camera-status- Get camera statusPOST /api/devices/:deviceId/channels/:channelId/camera-status- Set camera status
Advanced Configuration:
GET /api/devices/:deviceId/zoom-focus- Get zoom focus levelPOST /api/devices/:deviceId/channels/:channelId/zoom-focus- Set zoom focus levelGET /api/devices/:deviceId/channels/:channelId/alarm-plan- Get alarm schedule planPOST /api/devices/:deviceId/channels/:channelId/alarm-plan- Set alarm schedule planGET /api/devices/:deviceId/channels/:channelId/alarm-param- Get alarm parametersPOST /api/devices/:deviceId/channels/:channelId/alarm-sensitivity- Set alarm sensitivityGET /api/devices/:deviceId/channels/:channelId/collections- Get collection pointsPOST /api/devices/:deviceId/channels/:channelId/collections- Create collection pointDELETE /api/devices/:deviceId/channels/:channelId/collections/:name- Delete collection pointPOST /api/devices/:deviceId/channels/:channelId/collections/:name/turn- Turn to collection point
WiFi Configuration:
GET /api/devices/:deviceId/wifi-around- Scan WiFi networks around devicePOST /api/devices/:deviceId/wifi-control- Connect device to WiFi networkGET /api/devices/:deviceId/wifi-current- Get current WiFi connection
Examples
The library includes comprehensive examples:
# Basic device operations
npm run example:basic
# IoT device control
npm run example:iot
# Comprehensive feature demonstration
npm run example:comprehensive
# Node.js server with recording capabilities
npm run serverSupported API Endpoints
The library supports 50+ API endpoints including:
Device Management: Device binding/unbinding, status monitoring, configuration
Sub-Accounts: Create, manage, and assign permissions to sub-accounts
Live Streaming: Create, schedule, and manage live streams
Recording: Query, download, and manage local/cloud recordings
Cloud Storage: Manage cloud storage services and strategies
Device Control: PTZ control, snapshots, device operations
IoT Integration: Control IoT devices and read sensor data
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
