npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

hikvision-openapi-sdk

v1.0.1

Published

海康威视 OpenAPI Node.js SDK - 基于Artemis开放平台协议

Readme

海康威视 OpenAPI SDK for Node.js

一个功能完整的海康威视 OpenAPI Node.js SDK,基于海康威视开放平台协议文档实现。

🚀 特性

  • 完整的鉴权认证:基于HMAC-SHA256签名算法
  • 灵活的请求封装:支持GET/POST/PUT/DELETE等HTTP方法
  • 丰富的API封装:摄像头、区域、组织、事件、设备等常用接口
  • 完善的错误处理:分类错误处理和详细错误信息
  • 调试模式:详细的请求和响应日志
  • TypeScript友好:提供完整的类型定义
  • 高性能:支持连接池和请求重试
  • 易于扩展:模块化设计,方便添加新的API

📦 安装

npm install hikvision-openapi-sdk

🔧 快速开始

基本使用

const { HikvisionClient } = require('hikvision-openapi-sdk');

// 创建客户端实例
const client = new HikvisionClient({
  host: 'your-hikvision-platform.com',   // 海康威视平台地址
  port: 443,                             // 端口号
  protocol: 'https',                     // 协议
  appKey: 'your-app-key',                // 应用密钥
  appSecret: 'your-app-secret',          // 应用秘钥
  debug: true,                           // 开启调试模式
  timeout: 30000,                        // 请求超时时间
  rejectUnauthorized: false              // 忽略SSL证书验证
});

// 使用高级API
async function example() {
  try {
    // 获取摄像头列表
    const cameras = await client.api.getCameras({
      pageNo: 1,
      pageSize: 10
    });
    console.log('摄像头数量:', cameras.data.length);

    // 获取区域列表
    const regions = await client.api.getRegions();
    console.log('区域数量:', regions.data.length);

    // 获取OAuth Token
    const token = await client.api.getOAuthToken();
    console.log('Access Token:', token.access_token);

  } catch (error) {
    console.error('API调用失败:', error.message);
  }
}

低级API调用

// 直接使用HTTP客户端
async function lowLevelExample() {
  try {
    // POST请求
    const response = await client.post('/artemis/api/resource/v1/cameras', {
      pageNo: 1,
      pageSize: 100
    });
    
    // GET请求
    const getResponse = await client.get('/artemis/api/resource/v1/regions', {
      pageNo: 1,
      pageSize: 50
    });

    console.log('响应数据:', response.data);
  } catch (error) {
    console.error('请求失败:', error.message);
  }
}

📚 API 文档

客户端配置

| 参数 | 类型 | 必需 | 默认值 | 说明 | |------|------|------|--------|------| | host | string | ✅ | - | 海康威视平台地址 | | port | number | ❌ | 443 | 端口号 | | protocol | string | ❌ | 'https' | 协议类型 | | appKey | string|number | ✅ | - | 应用密钥 | | appSecret | string | ✅ | - | 应用秘钥 | | debug | boolean | ❌ | false | 是否开启调试模式 | | timeout | number | ❌ | 30000 | 请求超时时间(ms) | | rejectUnauthorized | boolean | ❌ | false | 是否验证SSL证书 |

常用API方法

摄像头管理

// 获取摄像头列表
const cameras = await client.api.getCameras({
  pageNo: 1,
  pageSize: 100,
  cameraName: '摄像头名称',  // 可选,模糊查询
  regionIndexCode: 'region001'  // 可选,区域编码
});

// 获取单个摄像头信息
const camera = await client.api.getCamera('camera-index-code');

// 获取摄像头预览地址
const previewUrl = await client.api.getCameraPreviewUrl({
  cameraIndexCode: 'camera-index-code',
  streamType: 0,      // 0-主码流,1-子码流,2-第三码流
  protocol: 'rtsp',   // rtsp, rtmp, hls等
  transmode: 1        // 0-UDP,1-TCP
});

区域管理

// 获取区域列表
const regions = await client.api.getRegions({
  pageNo: 1,
  pageSize: 100,
  treeCode: '0'  // 树节点编码
});

组织管理

// 获取组织列表
const organizations = await client.api.getOrganizations({
  pageNo: 1,
  pageSize: 100
});

设备管理

// 获取设备列表
const devices = await client.api.getDevices({
  pageNo: 1,
  pageSize: 100
});

// 获取设备在线状态
const deviceStatus = await client.api.getDeviceStatus({
  indexCodes: ['device001', 'device002']
});

事件管理

// 获取事件列表
const events = await client.api.getEvents({
  startTime: '2024-01-01T00:00:00Z',
  endTime: '2024-01-31T23:59:59Z',
  eventTypes: ['motion_detection', 'line_crossing'],
  pageNo: 1,
  pageSize: 100
});

// 订阅事件
const subscription = await client.api.subscribeEvents({
  eventTypes: ['motion_detection'],
  eventDest: 'http://your-server.com/events'
});

人员管理

// 获取人员列表
const persons = await client.api.getPersons({
  pageNo: 1,
  pageSize: 100
});

// 添加人员
const newPerson = await client.api.addPerson({
  personName: '张三',
  orgIndexCode: 'org001'
});

门禁管理

// 获取门禁点列表
const accessPoints = await client.api.getAccessControlPoints();

// 获取读卡器列表
const cardReaders = await client.api.getCardReaders();

// 获取门列表
const doors = await client.api.getDoors();

🔍 错误处理

SDK 提供了多种错误类型,方便进行针对性处理:

const { ApiError, AuthError, NetworkError, ParameterError } = require('hikvision-openapi-sdk');

try {
  const result = await client.api.getCameras();
} catch (error) {
  if (error instanceof AuthError) {
    console.log('认证失败:', error.message);
    // 处理认证错误,如重新获取凭证
  } else if (error instanceof ApiError) {
    console.log('API错误:', error.message);
    console.log('错误代码:', error.errorCode);
    console.log('状态码:', error.statusCode);
  } else if (error instanceof NetworkError) {
    console.log('网络错误:', error.message);
    // 处理网络错误,如重试机制
  } else if (error instanceof ParameterError) {
    console.log('参数错误:', error.message);
    console.log('错误参数:', error.parameterName);
  } else {
    console.log('未知错误:', error.message);
  }
}

⚡ 高级功能

重试机制

const { Utils } = require('hikvision-openapi-sdk/lib/utils');

// 自动重试失败的操作
const result = await Utils.retry(async () => {
  return await client.api.getCameras();
}, 3, 1000); // 重试3次,间隔1秒

批量操作

// 并行获取多种资源
const [cameras, regions, devices] = await Promise.all([
  client.api.getCameras({ pageSize: 50 }),
  client.api.getRegions({ pageSize: 50 }),
  client.api.getDevices({ pageSize: 50 })
]);

分页遍历

async function getAllCameras() {
  let allCameras = [];
  let pageNo = 1;
  const pageSize = 100;
  let hasMore = true;

  while (hasMore) {
    const result = await client.api.getCameras({ pageNo, pageSize });
    
    if (result.data && result.data.length > 0) {
      allCameras.push(...result.data);
      pageNo++;
      hasMore = result.data.length === pageSize;
    } else {
      hasMore = false;
    }
  }

  return allCameras;
}

性能监控

const startTime = Date.now();
const result = await client.api.getCameras({ pageSize: 100 });
const duration = Date.now() - startTime;

console.log(`请求耗时: ${duration}ms`);
console.log(`数据量: ${JSON.stringify(result).length} 字节`);

🔧 调试模式

开启调试模式可以查看详细的请求和响应信息:

const client = new HikvisionClient({
  host: 'your-host',
  appKey: 'your-key',
  appSecret: 'your-secret',
  debug: true  // 开启调试模式
});

// 调试输出示例:
// [DEBUG 2024-01-15T10:30:45.123Z] 认证信息生成
// {
//   "method": "POST",
//   "url": "/artemis/api/resource/v1/cameras",
//   "timestamp": "1705315845123",
//   "nonce": "550e8400-e29b-41d4-a716-446655440000",
//   "signatureData": "POST\napplication/json\n...",
//   "signature": "xxxxxxxxxxxxx",
//   "headers": { ... }
// }

📝 示例代码

🔐 配置说明

在使用SDK之前,您需要:

  1. 在海康威视开放平台注册账号
  2. 创建应用并获取 appKeyappSecret
  3. 确保您的应用具有相应的API访问权限
  4. 配置正确的平台地址和端口

📄 许可证

本项目基于海康威视开放平台协议文档实现,仅供学习和开发使用。

🤝 贡献

欢迎提交 Issue 和 Pull Request 来改进这个项目。

📞 支持

如果您在使用过程中遇到问题,可以:

  1. 查看海康威视开放平台文档
  2. 提交 Issue 描述问题
  3. 联系海康威视技术支持

🔗 相关链接


注意: 使用本SDK需要有效的海康威视开放平台账号和API凭证。请确保您的appKey和appSecret是有效的,并且具有相应的API访问权限。