c++调用海康摄像头云台完整代码
时间: 2023-07-28 13:13:26 浏览: 321
以下是 C++ 调用海康摄像头云台的完整代码:
```c++
#include <iostream>
#include <Windows.h>
#include "HCNetSDK.h"
#pragma comment(lib, "HCNetSDK.lib")
using namespace std;
// 登录设备
bool Login(HANDLE& hDev, char* IP, char* username, char* password)
{
NET_DVR_USER_LOGIN_INFO loginInfo;
memset(&loginInfo, 0, sizeof(loginInfo));
loginInfo.bUseAsynLogin = false; // 同步登录
strcpy(loginInfo.sDeviceAddress, IP);
strcpy(loginInfo.sUserName, username);
strcpy(loginInfo.sPassword, password);
NET_DVR_DEVICEINFO_V40 devInfo;
memset(&devInfo, 0, sizeof(devInfo));
hDev = NET_DVR_Login_V40(&loginInfo, &devInfo);
if (hDev < 0)
{
cout << "Login failed: " << NET_DVR_GetLastError() << endl;
return false;
}
return true;
}
// 云台控制
void PTZControl(HANDLE hDev, int cmd, int speed, int stopTime)
{
NET_DVR_PTZPOS pos;
memset(&pos, 0, sizeof(pos));
if (!NET_DVR_GetDVRConfig(hDev, NET_DVR_GET_PTZPOS, 1, &pos, sizeof(pos), NULL, 0))
{
cout << "Failed to get PTZ position: " << NET_DVR_GetLastError() << endl;
return;
}
NET_DVR_PTZ_CONTROL_CFG ptzCtrlCfg;
memset(&ptzCtrlCfg, 0, sizeof(ptzCtrlCfg));
ptzCtrlCfg.dwSize = sizeof(ptzCtrlCfg);
ptzCtrlCfg.byChannel = 1;
ptzCtrlCfg.byPTZCommand = cmd;
ptzCtrlCfg.dwStop = 0;
switch (cmd)
{
case PTZ_UP:
pos.wPanPos += speed;
break;
case PTZ_DOWN:
pos.wPanPos -= speed;
break;
case PTZ_LEFT:
pos.wTiltPos -= speed;
break;
case PTZ_RIGHT:
pos.wTiltPos += speed;
break;
}
if (!NET_DVR_SetDVRConfig(hDev, NET_DVR_SET_PTZPOS, 1, &pos, sizeof(pos)))
{
cout << "Failed to set PTZ position: " << NET_DVR_GetLastError() << endl;
return;
}
if (!NET_DVR_PTZControlWithSpeed(hDev, ptzCtrlCfg.byChannel, ptzCtrlCfg.byPTZCommand, ptzCtrlCfg.dwStop, speed, speed, speed))
{
cout << "PTZ control failed: " << NET_DVR_GetLastError() << endl;
return;
}
Sleep(stopTime);
ptzCtrlCfg.dwStop = 1;
if (!NET_DVR_PTZControlWithSpeed(hDev, ptzCtrlCfg.byChannel, ptzCtrlCfg.byPTZCommand, ptzCtrlCfg.dwStop, speed, speed, speed))
{
cout << "PTZ control failed: " << NET_DVR_GetLastError() << endl;
return;
}
}
// 注销登录
void Logout(HANDLE hDev)
{
if (hDev >= 0 && !NET_DVR_Logout(hDev))
{
cout << "Logout failed: " << NET_DVR_GetLastError() << endl;
}
}
int main()
{
HANDLE hDev = -1;
// 登录设备
if (!Login(hDev, "192.168.1.100", "admin", "password"))
{
return -1;
}
// 开始云台控制
PTZControl(hDev, PTZ_UP, 3, 2000); // 向上运动 3 个单位,持续 2 秒
PTZControl(hDev, PTZ_DOWN, 3, 2000); // 向下运动 3 个单位,持续 2 秒
PTZControl(hDev, PTZ_LEFT, 3, 2000); // 向左运动 3 个单位,持续 2 秒
PTZControl(hDev, PTZ_RIGHT, 3, 2000); // 向右运动 3 个单位,持续 2 秒
// 注销登录
Logout(hDev);
return 0;
}
```
需要注意的是,该代码使用海康 SDK 实现,需要在编译时链接 HCNetSDK.lib 静态库。同时,需要将海康摄像头的 IP、用户名和密码替换成实际的值,以及根据需要修改云台控制的参数。
阅读全文