0% found this document useful (0 votes)
611 views76 pages

NetSDK - Python - Programming Manual - V1.0.2

This document is the programming manual for NetSDK_Python. It describes the main function modules, interfaces, and calling relationships of NetSDK_Python and provides example codes. The manual is intended for SDK software development engineers, project managers, and product managers. It explains key terms used in the software and provides a table of contents that outlines the chapters and sections covering topics like SDK initialization, device search and initialization, real-time monitoring, playback, and more.

Uploaded by

miroslav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
611 views76 pages

NetSDK - Python - Programming Manual - V1.0.2

This document is the programming manual for NetSDK_Python. It describes the main function modules, interfaces, and calling relationships of NetSDK_Python and provides example codes. The manual is intended for SDK software development engineers, project managers, and product managers. It explains key terms used in the software and provides a table of contents that outlines the chapters and sections covering topics like SDK initialization, device search and initialization, real-time monitoring, playback, and more.

Uploaded by

miroslav
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 76

NetSDK_Python

Programming Manual

I
V1.0.2
Foreword

Purpose

Welcome to use NetSDK (hereinafter referred to be "SDK") programming manual (hereinafter referred
to be "the manual").
The manual describes the main function modules, interfaces and calling relationships, and provides
example codes.
The example codes provided in the manual are only for demonstrating the procedure and not
assured to copy for use.

Readers

 SDK software development engineers


 Project managers
 Product managers

Safety Instructions

The following categorized signal words with defined meaning might appear in the manual.
Signal Words Meaning

Indicates a high potential hazard which, if not avoided, will result in


DANGER death or serious injury.

Indicates a medium or low potential hazard which, if not avoided,


WARNING could result in slight or moderate injury.

Indicates a potential risk which, if not avoided, could result in


property damage, data loss, lower performance, or unpredictable
CAUTION result.

TIPS Provides methods to help you solve a problem or save you time.

Provides additional information as the emphasis and supplement to


NOTE the text.

I
Revision History

Version Revision Content Release Time

V1.0.2 Updated some descriptions. February 2023

Change the packing method of


V1.0.1 October 2020
package library to whl package.

V1.0.0 First release. May 2020

Privacy Protection Notice

As the device user or data controller, you might collect personal data of others such as face,
fingerprints, car plate number, email address, phone number, GPS and so on. You need to be in
compliance with the local privacy protection laws and regulations to protect the legitimate rights
and interests of other people by implementing measures include but not limited to: providing clear
and visible identification to inform data subject the existence of surveillance area and providing
related contact.

About the Manual

 The manual is for reference only. If there is inconsistency between the manual and the actual
product, the actual product shall prevail.
 We are not liable for any loss caused by the operations that do not comply with the manual.
 The manual would be updated according to the latest laws and regulations of related
jurisdictions. For detailed information, refer to the paper manual, CD-ROM, QR code or our
official website. If there is inconsistency between paper manual and the electronic version, the
electronic version shall prevail.
 All the designs and software are subject to change without prior written notice. The product
updates might cause some differences between the actual product and the manual. Please
contact the customer service for the latest program and supplementary documentation.
 There still might be deviation in technical data, functions and operations description, or errors
in print. If there is any doubt or dispute, we reserve the right of final explanation.
 Upgrade the reader software or try other mainstream reader software if the manual (in PDF
format) cannot be opened.
 All trademarks, registered trademarks and the company names in the manual are the properties
of their respective owners.
 Please visit our website, contact the supplier or customer service if there is any problem
occurring when using the device.

II
Glossary
This chapter provides the definitions to some of the terms that appear in the manual to help you
understand the function of each module.

Term Definition
A type of video stream that usually has better resolution and clarity and
Main Stream
provides a better experience if the network resource is not restricted.
A type of video stream that usually has lower resolution and clarity than
Sub Stream the main stream but demands less network resources. The user can
choose the stream type according to the particular scenes.
Resolution is consisted of display resolution and image resolution. Display
resolution refers to the quantity of pixels in unit area, and the image
Resolution
resolution refers to information quantity (the quantity of pixels per inch)
stored in the image.
An abstract concept of the communication and video stream
transmission between NetSDK and devices. For example, if a number of
cameras (SD, IPC) are mounted on a storage device (NVR), the storage
Video Channel
device manages the cameras as video channels which are numbered from
0. If NetSDK connects to the camera directly, the video channel is usually
numbered as 0.
Motion Detection When detecting a moving object on the image, an motion detection
Alarm alarm will be uploaded.

III
Table of Contents
Foreword ............................................................................................................................................................ I
Glossary ........................................................................................................................................................... III
1 Overview ........................................................................................................................................................ 1
1.1 General ........................................................................................................................................................................................... 1
1.2 Applicability ................................................................................................................................................................................. 2
1.3 Demo Running ............................................................................................................................................................................ 2
1.3.1 Installing whl File .......................................................................................................................................................... 2
1.3.2 Running Demo............................................................................................................................................................... 3
1.4 Project Configuration ............................................................................................................................................................... 4
1.4.1 Pycharm Configuration .............................................................................................................................................. 4
1.4.2 Adding Tool to Pycharm ............................................................................................................................................. 7
2 Function Modules ........................................................................................................................................ 12
2.1 SDK Initialization ......................................................................................................................................................................12
2.1.1 Introduction ..................................................................................................................................................................12
2.1.2 Interface Overview .....................................................................................................................................................12
2.1.3 Process ............................................................................................................................................................................13
2.1.4 Sample Code.................................................................................................................................................................13
2.1.5 Note .................................................................................................................................................................................14
2.2 Device Search and Initialization .........................................................................................................................................14
2.2.1 Introduction ..................................................................................................................................................................14
2.2.2 Interface Overview .....................................................................................................................................................15
2.2.3 Process ............................................................................................................................................................................16
2.2.4 Sample Code.................................................................................................................................................................18
2.3 Device Login ..............................................................................................................................................................................22
2.3.1 Introduction ..................................................................................................................................................................22
2.3.2 Interface Overview .....................................................................................................................................................22
2.3.3 Process ............................................................................................................................................................................23
2.3.4 Sample Code.................................................................................................................................................................24
2.3.5 Note .................................................................................................................................................................................24
2.4 Live View ......................................................................................................................................................................................25
2.4.1 Introduction ..................................................................................................................................................................25
2.4.2 Interface Overview .....................................................................................................................................................25
2.4.3 Process ............................................................................................................................................................................26
2.4.4 Sample Code.................................................................................................................................................................27
2.4.5 Notes for Process.........................................................................................................................................................27
2.5 Record Playback .......................................................................................................................................................................27
2.5.1 Introduction ..................................................................................................................................................................27
2.5.2 Interface Overview .....................................................................................................................................................28
2.5.3 Process ............................................................................................................................................................................28
2.5.4 Sample Code.................................................................................................................................................................30
2.6 Record Download ....................................................................................................................................................................32
2.6.1 Introduction ..................................................................................................................................................................32
2.6.2 Interface Overview .....................................................................................................................................................32

IV
2.6.3 Process ............................................................................................................................................................................32
2.6.4 Example Code ..............................................................................................................................................................34
2.7 Device Control...........................................................................................................................................................................36
2.7.1 Introduction ..................................................................................................................................................................36
2.7.2 Interface Overview .....................................................................................................................................................36
2.7.3 Process ............................................................................................................................................................................36
2.7.4 Sample Code.................................................................................................................................................................37
2.8 Remote Snapshot.....................................................................................................................................................................38
2.8.1 Introduction ..................................................................................................................................................................38
2.8.2 Interface Overview .....................................................................................................................................................38
2.8.3 Process ............................................................................................................................................................................39
2.8.4 Sample Code.................................................................................................................................................................40
2.9 Alarm Upload.............................................................................................................................................................................40
2.9.1 Introduction ..................................................................................................................................................................40
2.9.2 Interface Overview .....................................................................................................................................................40
2.9.3 Process ............................................................................................................................................................................41
2.9.4 Sample Code.................................................................................................................................................................42
2.10 Intelligent Traffic Event Upload ........................................................................................................................................43
2.10.1 Introduction ...............................................................................................................................................................43
2.10.2 Interface Overview ..................................................................................................................................................43
2.10.3 Process..........................................................................................................................................................................44
2.10.4 Sample Code ..............................................................................................................................................................45
3 Interface Definition ..................................................................................................................................... 48
3.1 SDK Initialization ......................................................................................................................................................................48
3.1.1 InitEx ................................................................................................................................................................................48
3.1.2 Cleanup ..........................................................................................................................................................................48
3.1.3 SetAutoReconnect .....................................................................................................................................................48
3.2 Device Search and Device Initialization...........................................................................................................................49
3.2.1 StartSearchDevicesEx ................................................................................................................................................49
3.2.2 SearchDevicesByIPs....................................................................................................................................................49
3.2.3 StopSearchDevices.....................................................................................................................................................50
3.2.4 InitDevAccount ............................................................................................................................................................50
3.3 Device Login ..............................................................................................................................................................................51
3.3.1 LoginWithHighLevelSecurity ..................................................................................................................................51
3.3.2 Logout .............................................................................................................................................................................51
3.4 Live View ......................................................................................................................................................................................52
3.4.1 RealPlayEx ......................................................................................................................................................................52
3.4.2 StopRealPlayEx ............................................................................................................................................................53
3.5 Record Playback .......................................................................................................................................................................53
3.5.1 SetDeviceMode ...........................................................................................................................................................53
3.5.2 QueryRecordFile ..........................................................................................................................................................54
3.5.3 PlayBackByTimeEx2....................................................................................................................................................54
3.5.4 StopPlayBack ................................................................................................................................................................55
3.5.5 PausePlayBack..............................................................................................................................................................55
3.6 Record Download ....................................................................................................................................................................56
3.6.1 DownloadByTimeEx ...................................................................................................................................................56
3.6.2 StopDownload .............................................................................................................................................................57

V
3.7 Device Control...........................................................................................................................................................................57
3.7.1 GetDevConfig...............................................................................................................................................................57
3.7.2 SetDevConfig ...............................................................................................................................................................58
3.7.3 RebootDev.....................................................................................................................................................................58
3.8 Remote Snapshot.....................................................................................................................................................................59
3.8.1 SetSnapRevCallBack ..................................................................................................................................................59
3.8.2 SnapPictureEx ..............................................................................................................................................................59
3.9 Alarm Upload.............................................................................................................................................................................60
3.9.1 SetDVRMessCallBackEx1 ..........................................................................................................................................60
3.9.2 StartListenEx .................................................................................................................................................................60
3.9.3 StopListen ......................................................................................................................................................................60
3.10 Intelligent Traffic Event Upload ........................................................................................................................................61
3.10.1 RealLoadPictureEx....................................................................................................................................................61
3.10.2 StopLoadPic................................................................................................................................................................61
4 Callback Definition ...................................................................................................................................... 63
4.1 fDisConnect ................................................................................................................................................................................63
4.2 fHaveReConnect .......................................................................................................................................................................63
4.3 fSearchDevicesCBEx ................................................................................................................................................................63
4.4 fSearchDevicesCB ....................................................................................................................................................................64
4.5 fDownLoadPosCallBack .........................................................................................................................................................64
4.6 fDataCallBack .............................................................................................................................................................................65
4.7 fTimeDownLoadPosCallBack ...............................................................................................................................................65
4.8 fAnalyzerDataCallBack ...........................................................................................................................................................66
4.9 fSnapRev......................................................................................................................................................................................66
4.10 fMessCallBackEx1 ..................................................................................................................................................................67
Appendix 1 Cybersecurity Recommendations ............................................................................................. 68

VI
1 Overview

1.1 General

The following are the main functions:


Device login, live view, record playback, record download, remote snapshot, alarm upload, device
search, intelligent event upload and snapshot, device restart, device timing and more.

Table 1-1 Files of NetSDK library


Library Type Library File Name Library File Description
dhnetsdk.dll Library file
Function library
avnetsdk.dll Library file
Configuration library dhconfigsdk.dll Library file
Play (coding and dhplay.dll Play library
decoding auxiliary
fisheye.dll Fishereye correction
library
Infra.dll Base library
json.dll Json library
Dependent library of
NetFramework.dll Network base library
"avnetsdk.dll"
Stream.dll Media transmission structure package library
StreamSvr.dll Stream service
Auxiliary library of "
IvsDrawer.dll Image display library
dhnetsdk "

Table 1-2 Files of package project


File Name File Description
Call NetSDK library to package the interfaces as Python interfaces
NetSDK.py
which can be used by users.
SDK_Callback.py Store the callbacks used by the NetSDK library.
SDK_Enum.py Store the enumerations used by the NetSDK library.
SDK_Struct.py Store the structures used by the NetSDK library.

 The function library and configuration library are necessary libraries.


 The function library is the main body of SDK, which is used for interaction between client and
products, remotely controls device, queries device data, configures device data information, and
gets and handles the streams.
 NetSDK library is the base of the Python package project. In project, file NetSDK.py file defines
the reference path of the NetSDK library, and you need to put the NetSDK library under the
corresponding path when using it. Users can customize the reference path.
 All the externally used interfaces are defined in the NetClient class. Before using, you need to
define an object of the NetClient class, and then call the interfaces in the class by the object.

1
1.2 Applicability

 Recommended memory: No less than 512 M


 Python version: 3.7 version and later
 Operating system:
 Windows: Windows 10/Windows 8.1/Windows 7/2000 and Windows Server 2008/2003.
 Linux: General Linux systems such as Red Hat/SUSE.

1.3 Demo Running

 Download and unzip the Python version of NetSDK development kit, then find the .whl file in
the dist folder. The corresponding name might vary slightly with the system, such as
"NetSDK-2.0.0.1-py3-none-win_amd64.whl" or "NetSDK-2.0.0.1-py3-none-linux_i686.whl".
 This file is the python installation package of the NetSDK package library. After installing this file,
Demo can directly "import NetSDK" and use its content for easier development.

1.3.1 Installing whl File


Step 1 Install python3.7, and add the installation directory to the system environment variables.
Step 2 Start instruction terminal to run the following command to install pyqt5 and pyqt5-tools.
pip install pyqt5
pip install pyqt5-tools
Step 3 Open the command terminal in the directory where the whl file is saved, and then run the
following command to install the plug-in.
pip install NetSDK-2.0.0.1-py3-none-win_amd64.whl

Notes

 In Windows, the installation file is installed in the "NetSDK" folder in the "\Lib\site-packages"
directory of the Python installation directory. In Linux, the installation file is installed in the
"NetSDK" folder in the "site-packages" directory of the Python installation directory. If you need
to refer to or change the content, refer to the files in the directory. Plug-ins installed by users are
stored in the "site-packages" directory. The above mentioned PyQt is also in this directory.
 If you need to uninstall the plug-in, use the command "pip uninstall NetSDK".
 If both python2 and python3 exist in the system, replace "pip" in the command with "pip3".
 After installing whl, you can import NetSDK to develop relevant functions of SDK. Programs
developed by customers do not rely on PyQt.
 If the Internet does not work, the installation cannot be successful through running the above
command. Go to pypi module of python official website (https://pypi.org/) to download the
following plug-ins, install correct versions of plug-ins according to versions of the system and
python. The installation sequence is: python_dotenv, click, PyQt5-sip, PyQt5, pyqt5-tools,
PyQt5Designer.
 When installing plug-ins offline, open the command terminal in the plug-in directory, and then

2
run the command pip install xxx. When demonstrating locally, the commands used are as
follows.(Names of Linux plug-ins might be different, there are no difference from Windows.
pip install python_dotenv-0.10.1-py2.py3-none-any.whl
pip install Click-7.0-py2.py3-none-any.whl
pip install PyQt5_sip-4.19.13-cp37-none-win_amd64.whl
pip install PyQt5-5.11.3-5.11.2-cp35.cp36.cp37.cp38-none-win_amd64.whl
pip install pyqt5_tools-5.11.3.1.4-cp37-none-win_amd64.whl
pip install PyQt5Designer-5.10.1-cp37-none-win_amd64.whl

1.3.2 Running Demo


After the whl packager is installed, you can directly run Demo.
Take live view Demo as an example:
Open the "RealPlayDemo" folder, enable the command terminal, and run the command "python
RealPlayDemo.py" to start Demo.
In Windows, if the py file is opened by python, you can also directly double-click the
RealPlayDemo.py file to start the program.

Notes

 If both python2 and python3 exist in the system, replace the command "python
RealPlayDemo.py" with "python3 RealPlayDemo.py".
 In Windows, double-click the file to run Demo, and an additional console window will pop up at
the back. If you want to hide the console window when running the program, you can change
the suffix of RealPlayDemo.py to ".pyw" ("RealPlayDemo.pyw"), then double-click to run it.
 When using PyCharm for development, you only need to open each Demo directory in the
Demo folder, instead of the whole directory.

3
1.4 Project Configuration

1.4.1 Pycharm Configuration


Configure Interpreter, and then run the Demo project by pycharm.
Step 1 Open pycharm.
Step 2 Select File > Settings.
Figure 1-1 Select settings

Step 3 Configure Interpreter.


Information about PyQt5 related software is displayed.

4
Figure 1-2 Configure interpreter

Step 1 Configure Demo.


1) Select Run > Debug.
Figure 1-3 Configure Demo (1)

2) Select Edit Configurations.

5
Figure 1-4 Configure Demo (2)

3) Select + > Python.


Figure 1-5 Run Demo (3)

4) Set Demo configuration name and path of Demo.py.


 Name: Set Demo configuration name.
 Script path: Select path of Demo.py. Here takes PlayBackDemo.py as an example.
5) Click Debug to run Demo.
Figure 1-6 Run Demo configuration

6
1.4.2 Adding Tool to Pycharm
Add pyqt5designer and pyuic5 to pycharm.
 After adding pyqt5designer to pycharm, select the corresponding ui file and open qt designer.
Use the tool to design UI.
 After adding pyuic5 to pycharm, select the corresponding .ui file and create .py file. View the
defined variables through the py file.
Step 1 Select File > Settings.
Figure 1-7 Select external tools

Step 2 Add pyqt5designer. Select Tool > External Tools, and click + to configure parameters. Click
OK.

7
Figure 1-8 Add pyqt5designer

Table 1-3 Parameters of pyqt5designer


Paramater Description
Name Tool name which can be customized by users, such as QtDesigner.
Program Enter the path of pyqt5designer.exe which is in the file folder of Scripts.
Arguments $FileDir$\$FileName$
Working directory $FileDir$
Step 3 Add pyuic5. Click + to configure parameters, and then click OK.

8
Figure 1-9 Add pyuic5

Table 1-4 Parameters of pyuic5


Paramater Description
Name Tool name which can be customized by users, such as PyUI.
Program Enter the path of pyuic5.exe which is in the file folder of Scripts.
Arguments $FileName$ -o $FileNameWithoutExtension$.py
Working directory $FileDir$
Step 4 Use design interface of QtDesigner.
Select the corresponding .ui file, and right-click External Tools > QtDesigner to open
QtDesigner.

9
Figure 1-10 Open QtDesigner

Figure 1-11 Design interface

Step 5 Transform file from .ui format to.py format.


Click the corresponding file in .ui format, right click to open menu, and select External
Tools > pyuic5 to transform file format.

10
Figure 1-12 Transform file format from .ui to .py

11
2 Function Modules

2.1 SDK Initialization

2.1.1 Introduction
Initialization is the first step of SDK to conduct all the function modules. It does not have the
surveillance function but can set some parameters that affect the SDK overall functions.
 Initialization occupies some memory.
 Only the first initialization is valid within one process.
 After using this function, call cleanup interface to release SDK resource.
 The interfaces between InitEx and Cleanup are one-to-one corresponding. It is recommended
to call it only once when writing codes.

2.1.2 Interface Overview


Table 2-1 Interfaces of initialization
Interface Implication
_load_library Load dynamic library.
InitEx Initialize SDK.
SetAutoReconnect (Optional) Set reconnection callback.
Cleanup Release SDK sources.

12
2.1.3 Process
Figure 2-1 Process of initialization

Start

Load dynamic library


_load_library

Initialize SDK
InitEx

Configure reconnection
callback
SetAutoReconnect

Release SDK resources


Cleanup

Required
End
Optional

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call _load_library to load dynamic library.


Step 2 Call InitEx to initialize SDK and set disconnection callback.
Step 3 (Optional) Call SetAutoReconnect to set reconnection callback.
Step 4 Call Cleanup to release SDK resources. This function can be called after using NETSDK.

2.1.4 Sample Code


# state and initialize callback function
self.m_DisConnectCallBack = fDisConnect(self.DisConnectCallBack)
self.m_ReConnectCallBack = fHaveReConnect(self.ReConnectCallBack)

13
# get NetSDK object and initialize it
self.sdk = NetClient()
self.sdk.InitEx(self.m_DisConnectCallBack)
self.sdk.SetAutoReconnect(self.m_ReConnectCallBack)

# realize disconnection callback function


def DisConnectCallBack(self, lLoginID, pchDVRIP, nDVRPort, dwUser):
self.setWindowTitle("live view (RealPlay)-disconnection (OffLine)")

# realize reconnection callback function


def ReConnectCallBack(self, lLoginID, pchDVRIP, nDVRPort, dwUser):
self.setWindowTitle(' live view (RealPlay)-reconnection(OnLine)')

# release NetSDK resource


self.sdk.Cleanup()

2.1.5 Note
 InitEx only needed to be called before using NetSDK, which is at the beginning of running
Demo. Cleanuponly need to be called after all functions related to NetSDK has been used to
release NetSDK resources. These two interfaces do not need to be called each time the functions
are used.
 _load_library is an internal callback of the NetClient which will be auto called when the
NetClient class object is implemented. Here is just to remind users, if you need to change the
location of NetSDK library, or to change the method and timing of calling NetSDK library,
modify this function.
 Initialization: Call InitEx only once before using the SDK.
 Cleaning up: The interface Cleanup clears all the opened processes, such as login, live view, and
alarm subscription.
 Reconnection: NetSDK can set the reconnection function for the situations such as network
disconnection and power off. NetSDK will keep logging until succeeded. Only the live view,
playback, smart event subscription and alarm subscription modules will be resumed after the
connection is back.
 For callback details of example code, see "4 Callback Definition."

2.2 Device Search and Initialization

2.2.1 Introduction
Device search is mainly used to help user to get device info from network. Device search can work
with login function. Device search interface can find relevant devices and login interface can login
these devices.

14
Device search is classified into the following two types by whether crossing segment or not:
 Async same-segment device search: Search for device info within current segment.
 Sync cross-segment device search: According to user-set segment info, searching for device in
corresponding segment.

2.2.2 Interface Overview


Table 2-2 Interface of device search and initialization
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.

StartSearchDevicesEx Asynchronously search for devices within the same networksegment.

Stop asynchronously searching for devices within the same


StopSearchDevices
networksegment.
SearchDevicesByIPs Stop asynchronously searching for devices in cross-segment.
InitDevAccount Initialize device.
GetLastError Get error codes of interfaces that fail to be called.

15
2.2.3 Process

2.2.3.1 Async Searching within Same Segment

Figure 2-2 Process of async device searching and initialization

Start

Initialize SDK
InitEx

Async search device


StartSearchDevicesEx

User async search for device to


callback functions fSearchDevicesCBEx
, and get and save device info

Judge byInitStatus field,


bo Whether the device is untialized?

Yes
According to byPwdResetWay field,
judge whether the device support
password resetting (mobile or email)

Stop async search


Initialize account
StopSearchDevices
InitDevAccount

Release SDK resource


Cleanup

End

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called for every function.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call StartSearchDevicesEx to search for devices.
Step 3 Find the uninitialized devices by search callback fSearchDevicesCBEx. Check that the
device is uninitialized according to byInitStatus filed. Check that the password can be reset
by cellphone or email according to byPwdResetWay field which is also required in interface
initialization.

16
Step 4 Call InitDevAccount to initialize device.
Step 5 Call StopSearchDevices to stop searching.
Step 6 Call Cleanup to release SDK resource.

2.2.3.2 Sync Searching in Cross-segment

Figure 2-3 Process of sync search and initialization

Begin

Initialize SDK
InitEx

Sync search for devices in


Get and save device info by
corss-segment
fSearchDevicesCB
SearchDevicesByIPs

Release SDK resources


Cleanup

End

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call SearchDevicesByIPs to search for devices. Get device info by fSearchDevicesCB.
Step 3 Call Cleanup to release SDK resource.

17
2.2.4 Sample Code

2.2.4.1 Async Searching within Same Segment and Device Initialization

Code Path
Demo\SearchDeviceDemo\ SearchDeviceDemo.py

Sample Code
# multicast and broadcast search
def start_search_device(self ):
# get local IP, search under taking multiple NIC
# call searching interfaces for the number of NICs times
IPList = self.getIPAddrs()
nSuccess = 0
for i in range(IPList.__len__()):
startsearch_in = NET_IN_STARTSERACH_DEVICE()
startsearch_in.dwSize = sizeof(NET_IN_STARTSERACH_DEVICE)
startsearch_in.emSendType =
EM_SEND_SEARCH_TYPE.MULTICAST_AND_BROADCAST
startsearch_in.cbSearchDevices = search_device_callback
startsearch_in.szLocalIp = IPList[i].encode()
startsearch_out = NET_OUT_STARTSERACH_DEVICE()
startsearch_out.dwSize = sizeof(NET_OUT_STARTSERACH_DEVICE)
lSearchHandle = self.sdk.StartSearchDevicesEx(startsearch_in, startsearch_out)
if lSearchHandle != 0:
nSuccess += 1
self.lSearchHandle_list.append(lSearchHandle)
if(IPList.__len__() > 0):
del IPList
if(nSuccess > 0):
return True
else:
return False

# stop searching. Use with start_search_device


def stop_search_device(self ):
for i in range(self.lSearchHandle_list.__len__()):
result = self.sdk.StopSearchDevices(self.lSearchHandle_list[i])

18
nUpdateNum = 0
self.lSearchHandle_list.clear()
self.device_info_list.clear()
self.device_mac_list.clear()
self.tableWidget.clear()
self.row = 0
self.column = 0
device_queue.queue.clear()
if(not device_queue.empty()):
device_queue.task_done()
self.tableWidget.setHorizontalHeaderLabels(['(No.)', '(Status)', 'IP(IP Version)', '(IP Address)',
(Port)', ' (Subnet Mask)', ' (Gateway)', ' (Mac Address)', '(Device Type)', '(Detail Type)', 'Http(Http)'])
return

def Init_Btn(self ):
# get selected ip and initialization info
currentRow = self.tableWidget.currentRow()
if((len(self.device_info_list) ==0)or((self.device_info_list[currentRow][0]&3) != 1)):
QMessageBox.about(self, '(prompt)', " (Please select not initialized device)")
else:
result = self.init_device_accout(self.device_info_list[currentRow])
if result == True:
QMessageBox.about(self, ' (prompt)', "(Initialize Success)")
item = QTableWidgetItem("(Initialize)")
self.device_info_list[currentRow][0] = 2
self.tableWidget.setItem(currentRow, 1, item)
self.tableWidget.update()
self.tableWidget.viewport().update()

# initialize account
def init_device_accout(self, device_info:list):
child = QDialog()
child_ui = Ui_InitDevAccount()
child_ui.setupUi(child)
if (1 == (device_info[3] & 1)):
# mobile phone
child_ui.way_lineEdit.setText('(Phone)')
elif (1 == (device_info[3] >> 1 & 1)):
# email
child_ui.way_lineEdit.setText('Mail)')

19
value = child.exec()
if (value == 0):
return False
init_Account_In = NET_IN_INIT_DEVICE_ACCOUNT()
init_Account_In.dwSize = sizeof(init_Account_In)
init_Account_In.szMac = device_info[2]
username = child_ui.username_lineEdit.text()
password = child_ui.password_lineEdit.text()
confirm_password = child_ui.confirm_password_lineEdit.text()
if(password != confirm_password):
QMessageBox.about(self, '(prompt)', "(Confirm password is wrong , please input
again)")
return
init_Account_In.szUserName = username.encode()
init_Account_In.szPwd = password.encode()
init_Account_In.szCellPhone = child_ui.reset_way_lineEdit.text().encode()
if (1 == (device_info[3] & 1)):
# mobile phone
init_Account_In.szCellPhone = child_ui.reset_way_lineEdit.text().encode()
elif(1 == (device_info[3] >> 1 & 1)):
# email
init_Account_In.szMail = child_ui.reset_way_lineEdit.text().encode()
init_Account_In.byPwdResetWay = device_info[3]
init_Account_Out = NET_OUT_INIT_DEVICE_ACCOUNT()
init_Account_Out.dwSize = sizeof(init_Account_Out)

result = self.sdk.InitDevAccount(init_Account_In, init_Account_Out, 5000, device_info[4])


if result:
return True
else:
QMessageBox.about(self, '(prompt)', 'error:' + str(self.sdk.GetLastError()))

return False

2.2.4.2 Sync Searching in Cross-segment

Code Path
Demo\SearchDeviceDemo\ SearchDeviceDemo.py

20
Sample Code
# unicast search
def start_search_device_byIP(self, start_IP, end_IP): #pay attention to validity of each IP address
startsearchbyIp_in = DEVICE_IP_SEARCH_INFO()
startsearchbyIp_in.dwSize = sizeof(DEVICE_IP_SEARCH_INFO)
start = struct.unpack("!I", socket.inet_aton(start_IP))[0] # network sequence transformed
to byte-order
end = struct.unpack("!I", socket.inet_aton(end_IP))[0]
if (end - start > 255):
QMessageBox.about(self, '(prompt)', "256(Number of IP addresses exceeds the upper
limit 256.)")
return False

startsearchbyIp_in.nIpNum = end - start + 1

for i in range(startsearchbyIp_in.nIpNum):
ip = DEVICE_IP_SEARCH_INFO_IP()
ip.IP = socket.inet_ntoa(struct.pack("!I", start + i)).encode()
startsearchbyIp_in.szIP[i] = ip

wait_time = int(wnd.Searchtime_lineEdit.text())
# get local IP, search under multiple NICs
# Call searching interface according the number of NICs
IPList = self.getIPAddrs()
nSuccessNum = 0
for i in range(IPList.__len__()):
result = self.sdk.SearchDevicesByIPs(startsearchbyIp_in, search_devie_byIp_callback, 0,
IPList[i].encode(), wait_time)
if result:
nSuccessNum =+ 1
if (IPList.__len__() > 0):
del IPList
if(nSuccessNum > 0):
return True
else:
return False

21
2.3 Device Login

2.3.1 Introduction
Device login, also called user authentication, is the precondition of all the other function modules.
You will obtain a unique login ID upon log in to the device and should introduce login ID before
using other SDK interfaces. The login ID becomes invalid once logged out.

2.3.2 Interface Overview


Table 2-3 Interfaces of device login
Interface Implication
InitEx Initialize SDK.
SetAutoReconnect Set reconnection callback.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
Logout Log out.

22
2.3.3 Process
Figure 2-4 Process of login

Start

Initialize SDK
InitEx

Set reconnectioncallback
SetAutoReconnect

Log in to device
LoginWithHighLevelSecurity

Particular function module

Log out of the device


Logout

Release SDK resources


Cleanup

Required
End Optional

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call SetAutoReconnect to set reconnection callback.
Step 3 Call LoginWithHighLevelSecurity to log in to the device.
Step 4 Implement the required function modules.
Step 5 Call Logout to log out of the device.
Step 6 Call Cleanup to release SDK resources.

23
2.3.4 Sample Code
# log in to the device to get login handle and device info. If failed, error info will be displayed
stuInParam = NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY()
stuInParam.dwSize = sizeof(NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY)
stuInParam.szIP = ip.encode()
stuInParam.nPort = port
stuInParam.szUserName = username.encode()
stuInParam.szPassword = password.encode()
stuInParam.emSpecCap = EM_LOGIN_SPAC_CAP_TYPE.TCP
stuInParam.pCapParam = None

stuOutParam = NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY()
stuOutParam.dwSize = sizeof(NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY)

self.loginID, device_info, error_msg = self.sdk.LoginWithHighLevelSecurity(stuInParam, stuOutParam)


if self.loginID != 0:
for i in range(int(device_info.nChanNum)):
self.Channel_comboBox.addItem(str(i)) # display channels of the device
else:
QMessageBox.critical(self, '(prompt)', error_msg, QMessageBox.Ok, QMessageBox.No) #
display error info of the login interface

# log out
result = self.sdk.Logout(self.loginID)
if result:
self.loginID = 0

2.3.5 Note
 Login handle: When the login is successful, the returned value is not 0 (even the handle is
smaller than 0, the login is also successful). One device can login multiple times with different
handles at each login. If there is no special function module, it is suggested to login only once.
The login handle can be repeatedly used on other function modules.
 Duplicate handles: It is normal that the login handle is the same as the existed handle. For
example, log in to device A and get handle loginIDA. However, if you log out of loginIDA and
then log in, you may get LoginIDA again. But the duplicate handles do not occur throughout the
lifetime of the handle.
 Logout: The interface will release the opened functions internally, but it is not suggested to rely
on the cleaning up function of lougout. For example, if you opened the live view function, you
should call the interface that stops the live viewg function when it is no longer required.

24
 Use login and logout in pairs: The login consumes some memory and socket information and
release sources once logout.
 Login failure: It is suggested to check the failure through return parameter error_msg. for more
details, see the error code list in LoginWithHighLevelSecurity.
 After reconnection, the original login ID will be invalid. After the device is auto reconnected, the
login ID will take effect again.

2.4 Live View

2.4.1 Introduction
Live view obtains the real-time stream from the storage device or front-end device, which is an
important part of the surveillance system.
SDK can get the main stream and sub stream from the device once it logged.
 Supports calling the window handle for SDK to directly decode and play the stream (Windows
system only).
 Supports calling the real-time stream to you to perform independent treatment.
 Supports saving the real-time record to the specific file though saving the callback stream or
calling the SDK interface.

2.4.2 Interface Overview


Table 2-4 Interfaces of live view
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
Logout Log out.
RealPlayEx Start live view extension interface.
StopRealPlayEx Stop live view extension interface.
GetLastError Get error codes of interfaces that fail to be called.
GetLastErrorMessage Get error info of interfaces that fail to be called.

25
2.4.3 Process
Figure 2-5 Process of live view

Start

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Start live view


RealPlayEx

Stop live view


StopRealPlayEx

Log out of the device


Logout

Release SDK resources


Cleanup

End

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 Call RealPlayEx to start live view.
Step 4 Call StopRealPlayEx to stop live view.
Step 5 Call Logout to log out of the device.

26
Step 6 Call Cleanup to release SDK resources.

2.4.4 Sample Code


#Start live view
channel = self.Channel_comboBox.currentIndex() # channel No.
if self.StreamTyp_comboBox.currentIndex() == 0:
stream_type = SDK_RealPlayType.Realplay # main streaam
else:
stream_type = SDK_RealPlayType.Realplay_1 # sun stream
self.playID = self.sdk.RealPlayEx(self.loginID, channel, self.PlayWnd.winId(), stream_type)
if self.playID != 0:
self.play_btn.setText("(Stop)")
self.StreamTyp_comboBox.setEnabled(False)
else:
QMessageBox.critical(self, ' (prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

# Stop live view


result = self.sdk.StopRealPlayEx(self.playID)
if result:
self.playID = 0
self.PlayWnd.repaint()

2.4.5 Notes for Process


 GetLastError is the interface used to get the error codes when failed to call NetSDK interfaces.
GetLastErrorMessage is the interface to get error information.
 It is recommended to call GetLastErrorMessage to get error information to identify the cause
of the error.

2.5 Record Playback

2.5.1 Introduction
Record playback function plays the videos of a particular period in some channels to find the target
videos for check.
The playback includes the following functions: Start playback, pause Playback, resume playback, and
stop playback.

27
2.5.2 Interface Overview
Table 2-5 Interfaces of record playback
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
Logout Log out.
PlayBackByTimeEx2 Extension interface of playback by time.
StopPlayBack Stop playback.
PausePlayBack Stop or resume playback.
SetDeviceMode Set device mode.
QueryRecordFile Query for all the record files within a period.

2.5.3 Process
After SDK initialization, you need to input channel number, start time, stop time, and valid window
handle to realize the playback of the required record.

28
Figure 2-6 Process of record playback

Start

Initialize SDK
InitEX

Log in to device
LoginWithHighLevelSecurity

Set stream type for playback


SetDeviceMode

Check whether there is a record


QueryRecordFile

Start record playback


PlayBackByTimeEx2

Pause playback (the second


parameter is True)
PausePlayBack

Resume playback (the second


parameter is False)
PausePlayBack

Stop record playback


StopPlayBack

Log out of the device


Logout

Release SDK resources


Cleanup
Required

Optional
End

29
Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 Call SetDeviceMode to set the stream type.
Step 4 Call QueryRecordFile to check whether there is a record in the selected period.
Step 5 Call PlayBackByTimeEx2 to start playback.
Step 6 (Optional) Call PausePlayBack. The playback will pause when the second parameter is True.
Step 7 (Optional) Call PausePlayBack. The playback will resume when the second parameter is
False.
Step 8 Call StopPlayBack to stop playback.
Step 9 Call Logout to log out of the device.
Step 10 Call Cleanup to release SDK resources.

2.5.4 Sample Code


# configure stream type for playback. Main stream is configured here.
stream_type = c_int(0)
result = self.sdk.SetDeviceMode(self.loginID, int(EM_USEDEV_MODE.RECORD_STREAM_TYPE),
stream_type)
if not result:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

# query record file


result, fileCount, infos = self.sdk.QueryRecordFile(self.loginID, 0, int(EM_QUERY_RECORD_TYPE.ALL),
startTime, endTime, None, 5000, False)

# Enable video playback


inParam = NET_IN_PLAY_BACK_BY_TIME_INFO()
inParam.hWnd = self.PlayBackWnd.winId()
inParam.cbDownLoadPos = DownLoadPosCallBack
inParam.dwPosUser = 0
inParam.fDownLoadDataCallBack = DownLoadDataCallBack
inParam.dwDataUser = 0
inParam.nPlayDirection = 0
inParam.nWaittime = 5000
inParam.stStartTime.dwYear = start_time.dwYear
inParam.stStartTime.dwMonth = start_time.dwMonth
inParam.stStartTime.dwDay = start_time.dwDay
inParam.stStartTime.dwHour = start_time.dwHour
inParam.stStartTime.dwMinute = start_time.dwMinute
inParam.stStartTime.dwSecond = start_time.dwSecond

30
inParam.stStopTime.dwYear = end_time.dwYear
inParam.stStopTime.dwMonth = end_time.dwMonth
inParam.stStopTime.dwDay = end_time.dwDay
inParam.stStopTime.dwHour = end_time.dwHour
inParam.stStopTime.dwMinute = end_time.dwMinute
inParam.stStopTime.dwSecond = end_time.dwSecond
outParam = NET_OUT_PLAY_BACK_BY_TIME_INFO()

nchannel = self.Channel_comboBox.currentIndex()
self.playbackID = self.sdk.PlayBackByTimeEx2(self.loginID, nchannel, inParam, outParam)
if self.playbackID != 0:
self.PlayBack_pushbutton.setText("(Stop)")
self.Pause_pushbutton.setEnabled(True)
self.Channel_comboBox.setEnabled(False)
self.StreamTyp_comboBox.setEnabled(False)
self.Channel_comboBox.repaint()
self.StreamTyp_comboBox.repaint()
self.PlayBackWnd.repaint()
else:
QMessageBox.critical(self, ‘(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

# Pause video playback


result = self.sdk.PausePlayBack(self.playbackID, True)

# resume video playback


result = self.sdk.PausePlayBack(self.playbackID, False)

# stop playback
result = self.sdk.StopPlayBack(self.playbackID)
if result:
self.playbackID = 0
if not result:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

31
2.6 Record Download

2.6.1 Introduction
Video surveillance system widely applies to city, airport, metro, bank and factory. When any event
occurs, you need to download the video records and report to the leaders, public security bureau, or
mass media. Therefore, record download is an important function.
The record download function helps you obtain the records saved on the device through SDK and
save into the local. It allows you to download from the selected channels and export to the local disk
or external USB flash drive. The downloaded files are in the format of Dahua which requires Dahua
player or integrated Dahua playsdk to play.

2.6.2 Interface Overview


Table 2-6 Interfaces of record download
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
Logout Log out.
SetDeviceMode Set device mode.
DownloadByTimeEx Download by time.
StopDownload Stop record download..

2.6.3 Process
You can import the start time and end time of download. SDK can download the specified record file
and save it to the required place.
You can also provide a callback pointer to SDK which calls back the specified record file to you.

32
Figure 2-7 Process of download by time

Begin

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Set stream type for query time


SetDeviceMode

Set callback
Download by time fTimeDownLoadPosCallBack
DownloadByTimeEx fDataCallBack

Stop download
StopDownload

Log out of the device


Logout

Release SDK resources


Cleanup

End

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 Call SetDeviceMode to set the download stream type.
Step 4 Call DownloadByTimeEx to start downloading by time.
Step 5 Call StopDownload to stop download.
Step 6 (Optional) Call fTimeDownLoadPosCallBack to update the download progress.
Step 7 Call Logout to log out of the device.
Step 8 Call Cleanup to release SDK resources.

33
2.6.4 Example Code
# configure stream type for download. Main stream is configured here.
stream_type = c_int(0)
result = self.sdk.SetDeviceMode(self.loginID, int(EM_USEDEV_MODE.RECORD_STREAM_TYPE),
stream_type)
if not result:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

# enable video download


start_date = self.Start_dateTimeEdit.date()
start_time = self.Start_dateTimeEdit.time()
startDateTime = NET_TIME()
startDateTime.dwYear = start_date.year()
startDateTime.dwMonth = start_date.month()
startDateTime.dwDay = start_date.day()
startDateTime.dwHour = start_time.hour()
startDateTime.dwMinute = start_time.minute()
startDateTime.dwSecond = start_time.second()

end_date = self.End_dateTimeEdit.date()
end_time = self.End_dateTimeEdit.time()
enddateTime = NET_TIME()
enddateTime.dwYear = end_date.year()
enddateTime.dwMonth = end_date.month()
enddateTime.dwDay = end_date.day()
enddateTime.dwHour = end_time.hour()
enddateTime.dwMinute = end_time.minute()
enddateTime.dwSecond = end_time.second()

save_file_name = 'D:\savedata.dav'# folder path and name of files saved


nchannel = self.Channel_comboBox.currentIndex()
self.downloadID = self.sdk.DownloadByTimeEx(self.loginID, nchannel,
int(EM_QUERY_RECORD_TYPE.ALL), startDateTime, enddateTime, save_file_name,
TimeDownLoadPosCallBack, 0, DownLoadDataCallBack, 0)
if self.downloadID:
self.Download_pushButton.setText("(Stop)")
else:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

34
# Stop video download
result = self.sdk.StopDownload(self.downloadID)
if result:
self.downloadID = 0

#callback function
@WINFUNCTYPE(None, c_longlong, c_ulong, POINTER(c_ubyte), c_ulong, c_longlong)
def DownLoadDataCallBack(lPlayHandle, dwDataType, pBuffer, dwBufSize, dwUser):
pass

@WINFUNCTYPE(None, c_longlong, c_ulong, c_ulong, c_int, POINTER(NET_RECORDFILE_INFO),


c_ulong)
def TimeDownLoadPosCallBack(lPlayHandle, total_size, download_size, index, recordfileinfo,
dwUser):
try:
# display progress
if download_size == 0xffffffff:
self.downloadID = 0
self.Download_progressBar.setValue(0)
self.sdk.StopDownload(self.downloadID)
self.Download_pushButton.setText("download)")
self.Message_label.setText("Download End!")
elif download_size == 0xfffffffe:
self.downloadID = 0
self.Download_progressBar.setValue(0)
self.Download_pushButton.setText(" (download)")
self.Message_label.setText("Download Failed!")
else:
if download_size >= total_size:
self.Download_progressBar.setValue(100)
else:
percentage = int(download_size * 100 / total_size)
self.Download_progressBar.setValue(percentage)
except Exception as e:
print(e)
except Exception as e:
print(e)

35
2.7 Device Control

2.7.1 Introduction
Get and set device time, and restart device remotely.

2.7.2 Interface Overview


Table 2-7 Interfaces of device control
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
Logout Log out.
GetDevConfig Query configuration info.
SetDevConfig Set configuration info.
RebootDev Restart device.

2.7.3 Process
Figure 2-8 Process of device control

Start

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Get device Set device Restart device


GetDevConfig SetDevConfig RebootDev

Log out of the device


Logout

Release SDK resources


Cleanup

End

36
Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 (Optional) Call GetDevConfig to get device time.
Step 4 (Optional) Call SetDevConfig to set device time.
Step 5 (Optional) Call RebootDev to restart device.
Step 6 Call Logout to log out of the device.
Step 7 Call Cleanup to release SDK resources.

2.7.4 Sample Code


# get device time
time = NET_TIME()
result = self.sdk.GetDevConfig(self.loginID, int(EM_DEV_CFG_TYPE.TIMECFG), -1, time,
sizeof(NET_TIME))
if not result:
QMessageBox.critical(self, ' (prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.Ok,
QMessageBox.No)
else:
get_time = QDateTime(time.dwYear, time.dwMonth, time.dwDay, time.dwHour, time.dwMinute,
time.dwSecond)
self.Time_dateTimeEdit.setDateTime(get_time)

#configure device time


device_date = self.Time_dateTimeEdit.date()
device_time = self.Time_dateTimeEdit.time()
deviceDateTime = NET_TIME()
deviceDateTime.dwYear = device_date.year()
deviceDateTime.dwMonth = device_date.month()
deviceDateTime.dwDay = device_date.day()
deviceDateTime.dwHour = device_time.hour()
deviceDateTime.dwMinute = device_time.minute()
deviceDateTime.dwSecond = device_time.second()

result = self.sdk.SetDevConfig(self.loginID, int(EM_DEV_CFG_TYPE.TIMECFG), -1, deviceDateTime,


sizeof(NET_TIME))
if not result:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.Ok,
QMessageBox.No)

# restart the device

37
result = self.sdk.RebootDev(self.loginID)
if not result:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.Ok,
QMessageBox.No)

2.8 Remote Snapshot

2.8.1 Introduction
Call NetSDK interface to send snapshot command. Device will capture images from live view and
send them to NetSDK, and then NetSDK will return the image data to you.

2.8.2 Interface Overview


Table 2-8 Interfaces of remote snapshot
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
SetSnapRevCallBack Set remote snapshot callback.
SnapPictureEx Snapshot extension interface.
Logout Log out.
GetLastError Get error codes of interfaces that failed to be called.

38
2.8.3 Process
Figure 2-9 Process of remote snapshot

Begin

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Get and save snapshot info


Set video snapshot callback
by fSnapRev which is the
SetSnapRevCallBack
video snapshot data callback

Send snapshot command to


device
SnapPictureEx

Log out of device


Logout

Release SDK resources


Cleanup

End

Notes for Process

 Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish to release SDK resources. These two
interfaces do not need to be called with every function.
 The time interval for snapshot should be more than 1 second. 3 seconds are recommended.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 Call SetSnapRevCallBack to set snapshot callback. When NetSDK receives image data sent
from device, NetSDK will call fSnapRev to send image info and image data to you.
Step 4 Call SnapPictureEx to send snapshot command. Wait for the returned image info in
fSnapRev.
Step 5 Call Logout to log out of the device.
Step 6 Call Cleanup to release SDK resources.

39
2.8.4 Sample Code

Code Path
Demo\CapturePicture\CaptureDemo.py

Sample Code
def capture_btn_onclick(self ):
# configure snapshot callback
dwUser = 0
self.sdk.SetSnapRevCallBack(CaptureCallBack, dwUser)
channel = self.Channel_comboBox.currentIndex()
snap = SNAP_PARAMS()
snap.Channel = channel
snap.Quality = 1
snap.mode = 0
# snapshot
self.sdk.SnapPictureEx(self.loginID, snap)

2.9 Alarm Upload

2.9.1 Introduction
Alarm upload, that is, the device sends an alarm to the platform to inform when the events to be set
have occurred. The platform can receive information such as external alarms, video signal loss alarms,
privacy masking alarms, and motion detection alarms,
Alarm upload can be realized by NetSDK active login device and subscription of the alarm function
to the device, which will send the detected alarm event to NetSDK.

2.9.2 Interface Overview


Table 2-9 Interfaces of alarm upload
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
SetDVRMessCallBackEx1 Set alarm callback.
StartListenEx Alarm susbscribtion extension interface.
StopListen Stop alarm susbscribtion.
Logout Log out.
GetLastError Get error codes of interfaces that fail to be called.

40
2.9.3 Process
Figure 2-10 Process of alarm upload

Start

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Set alarm callback Alarm callback


SetDVRMessCallBackEx1 fMessCallBackEx1

Subscribe alarm to device


StartListenEx

Stop subscribtion
StopListen

Log out of the device


Logout

Release SDK resources


Cleanup

End

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call InitEx to initialize SDK.


Step 2 Call LoginWithHighLevelSecurity to log in to the device.
Step 3 Call SetDVRMessCallBackEx1 to set alarm callback before alarm subscription.

41
Step 4 Call StartListenEx to subscribe to alarm from device. Then the uploaded event will be sent
to you by fMessCallBackEx1.
Step 5 Call StopListen to stop subscribtion.
Step 6 Call Logout to log out of the device.
Step 7 Call Cleanup to release SDK resources.

2.9.4 Sample Code

Code path
Demo\AlarmListen\ AlarmListenDemo.py

Sample Code
def __init__(self ):
super(StartListenWnd, self ).__init__()
self.setupUi(self )
# interface initialization
self.init_ui()

# NetSDK variables and callbacks used


self.loginID = C_LLONG()
self.m_DisConnectCallBack = fDisConnect(self.DisConnectCallBack)
self.m_ReConnectCallBack = fHaveReConnect(self.ReConnectCallBack)

#get NetSDK object and initialize it


self.sdk = NetClient()
self.sdk.InitEx(self.m_DisConnectCallBack)
self.sdk.SetAutoReconnect(self.m_ReConnectCallBack)
#Configure alarm callback function
self.sdk.SetDVRMessCallBackEx1(MessCallback,0)

def attach_btn_onclick(self):
self.row = 0
self.column = 0
self.Alarmlisten_tableWidget.clear()
self.Alarmlisten_tableWidget.setHorizontalHeaderLabels(['(No.)',(Time)', '(Channel)', '(Alarm Type)',
'(Status)'])
result = self.sdk.StartListenEx(self.loginID)
if result:
QMessageBox.about(self, '(prompt)', "(Subscribe alarm success)")
self.Stopalarmlisten_pushButton.setEnabled(True)
self.Alarmlisten_pushButton.setEnabled(False)
else:
QMessageBox.about(self, '(prompt)', 'error:' + str(self.sdk.GetLastError()))

def detach_btn_onclick(self):

42
if (self.loginID > 0):
self.sdk.StopListen(self.loginID)
self.Stopalarmlisten_pushButton.setEnabled(False)
self.Alarmlisten_pushButton.setEnabled(True)

2.10 Intelligent Traffic Event Upload

2.10.1 Introduction
Intelligent traffic event upload is the function to analyze real-time stream from intelligent traffic
devices. According to the pre-defined rules, SDK will check whether to upload events and carry
images.

2.10.2 Interface Overview


Table 2-10 Interfaces of intelligent traffic event upload
Interface Implication
InitEx Initialize SDK.
Cleanup Clean up SDK.
LoginWithHighLevelSecurity Log in with high level security.
RealLoadPictureEx Intelligent image alarm subscribtion interface.
StopLoadPic Stop uploading intelligent analysis data-image.
Logout Log out.
GetLastError Get error codes of interfaces that fail to be called.

43
2.10.3 Process
Figure 2-11 Process of intelligent traffic event upload

Begin

Initialize SDK
InitEx

Log in to device
LoginWithHighLevelSecurity

Subscribe to intelligent
image alarm Get and save alarm info and
RealLoadPictureEx image by fAnalyzerDataCallBack

Stop subscribtion
StopLoadPic

Log out of the device


Logout

Release SDK resources


Cleanup

End

Notes for Process

Call InitEx only once before using the SDK during the entire Demo running process. And call
Cleanup once when all SDK-related functions finish, to release SDK resources. These two interfaces
do not need to be called with every function.

Process Description

Step 1 Call InitEx to initialize SDK..


Step 2 Call LoginWithHighLevelSecurity to log in to the device.

44
Step 3 Call RealLoadpictureEx to subscribe to alarm from device, and the dwAlarmType should
correspond to the enumeration values of EM_EVENT_IVS_TYPE. After the subscription, the
uploaded event will be sent to you by callback which is be set in fAnalyzerDataCallBack. The
main use of callback is to display and save events.
Step 4 Call StopLoadPic to stop subscription of intelligent traffic event.
Step 5 Call Logout to log out of the device.
Step 6 Call Cleanup to release SDK resources.

2.10.4 Sample Code

2.10.4.1 Intelligent Traffic Junction

Code Path
\Demo\IntelligentTrafficDemo

Sample Code
# Intelligent traffic checkpoint event subscription
def attach_btn_onclick(self):
self.Attach_tableWidget.setHorizontalHeaderLabels(['(Time)', '(Event)', '(Plate No.)', '(Plate Color)',
' (Vehicle Type)', '(Vehicle Color)'])
channel = self.Channel_comboBox.currentIndex()
bNeedPicFile = 1
dwUser = 0
self.attachID = self.sdk.RealLoadPictureEx(self.loginID, channel,
EM_EVENT_IVS_TYPE.TRAFFICJUNCTION, bNeedPicFile, AnalyzerDataCallBack, dwUser, None)
if not self.attachID:
QMessageBox.about(self, '(prompt)', 'error:' + str(self.sdk.GetLastError()))
else:
self.Attach_pushButton.setEnabled(False)
self.Detach_pushButton.setEnabled(True)
QMessageBox.about(self, '(prompt)', " (Subscribe success)")

# cancel subscrpption
def detach_btn_onclick(self):
if (self.attachID == 0):
return
self.sdk.StopLoadPic(self.attachID)
self.attachID = 0
self.Attach_pushButton.setEnabled(True)
self.Detach_pushButton.setEnabled(False)
self.Attach_tableWidget.clear()
self.row = 0
self.column = 0
self.Attach_tableWidget.viewport().update()

45
self.Attach_tableWidget.setHorizontalHeaderLabels([(Time)', '(Event)', '(Plate No.)', '(Plate Color)',
' (Vehicle Type)', '(Vehicle Color)'])

2.10.4.2 Target Recognition Event

Code Path
Demo\TargetRecognitionDemo\TargetRecognitionDemo.py

Sample Code
def listenevent_btn_onclick(self):
if not self.realloadID:
channel = self.Channel_comboBox.currentIndex()
self.realloadID = self.sdk.RealLoadPictureEx(self.loginID, channel, EM_EVENT_IVS_TYPE.ALL,
True, self.m_AnalyzerDataCallBack)
if self.realloadID != 0:
self.ListenEvent_pushButton.setText(" (Detach Listen)")
else:
QMessageBox.critical(self, ' (prompt)', self.sdk.GetLastErrorMessage(),
QMessageBox.No)
else:
result = self.sdk.StopLoadPic(self.realloadID)
if result:
self.ListenEvent_pushButton.setText("(Listen Event)")
self.realloadID = 0
else:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

def AnalyzerDataCallBack(self, lAnalyzerHandle, dwAlarmType, pAlarmInfo, pBuffer, dwBufSize,


dwUser, nSequence, reserved):
if lAnalyzerHandle == self.realloadID:
if dwAlarmType == EM_EVENT_IVS_TYPE.FACERECOGNITION:
alarm_info = cast(pAlarmInfo,
POINTER(DEV_EVENT_FACERECOGNITION_INFO)).contents
self.show_recognition_info(alarm_info, pBuffer, dwBufSize)

2.10.4.3 Target Detection Event

Code Path
Demo\ TargetRecognitionDemo\ TargetRecognitionDemo.py

46
Sample Code
def listenevent_btn_onclick(self):
if not self.realloadID:
channel = self.Channel_comboBox.currentIndex()
self.realloadID = self.sdk.RealLoadPictureEx(self.loginID, channel, EM_EVENT_IVS_TYPE.ALL,
True, self.m_AnalyzerDataCallBack)
if self.realloadID != 0:
self.ListenEvent_pushButton.setText(" (Detach Listen)")
else:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)
else:
result = self.sdk.StopLoadPic(self.realloadID)
if result:
self.ListenEvent_pushButton.setText("(Listen Event)")
self.realloadID = 0
else:
QMessageBox.critical(self, '(prompt)', self.sdk.GetLastErrorMessage(), QMessageBox.No)

def AnalyzerDataCallBack(self, lAnalyzerHandle, dwAlarmType, pAlarmInfo, pBuffer, dwBufSize,


dwUser, nSequence, reserved):
if lAnalyzerHandle == self.realloadID:
if dwAlarmType == EM_EVENT_IVS_TYPE.FACEDETECT:
alarm_info = cast(pAlarmInfo, POINTER(DEV_EVENT_FACEDETECT_INFO)).contents
self.show_detect_info(alarm_info, pBuffer, dwBufSize)

47
3 Interface Definition

3.1 SDK Initialization

3.1.1 InitEx
Table 3-1 Initialize SDK
Item Description
Name Initialize SDK.
def InitEx(cls,
call_back: fDisConnect = None,
Function user_data: C_LDWORD = 0,
init_param: NETSDK_INIT_PARAM = NETSDK_INIT_PARAM()
) -> int
[in] call_back Disconnection callback.
Parameter [in] user_data User parameter of disconnection callback.
[in] init_param Initialzie parameters.
 Success: 1.
Return value
 Failure: 0.
It is the precondition for calling other function modules.
If the callback is set as None, the callback will not be sent to the user after the
device is disconnected.
Note
The parameter user_data passed in by InitEx will be returned in the same field
user_data of fDisConnect. User_data is not processed inside NetSDK, and is only
used to carry user data into the callback.

3.1.2 Cleanup
Table 3-2 Clean up SDK
Item Description
Name Clean up SDK.
Function def Cleanup(cls)
Parameter None.
Return value None.
Note Call the SDK cleanup interface before the process ends.

3.1.3 SetAutoReconnect
Table 3-3 Set reconnection callback
Item Description
Name Set auto reconnection callback.

48
Item Description
def SetAutoReconnect(cls,
call_back: fHaveReConnect,
Function
user_data: C_LDWORD = None
)
[in] call_back Reconnection callback.
Parameter
[in] user_data User parameter of disconnection callback.
Return value None.
Set the reconnection callback interface. If the callback is set as None, it will not
Note
connect automatically.

3.2 Device Search and Device Initialization

3.2.1 StartSearchDevicesEx
Table 3-4 Async device search
Item Description
Name Async device search.
def StartSearchDevicesEx(cls,
pInBuf: NET_IN_STARTSERACH_DEVICE,
Function
pOutBuf: NET_OUT_STARTSERACH_DEVICE
) -> C_LLONG
[in] pInBuf Async device searching input structure.
Parameter
[out] pOutBuf Async device searching output structure.
 Success: Search handle.
Return value  Failure: 0.
 Call GetLastError to get error codes.
Only support searching for devices within the same network segment. The
number of calls to the search interface is the same as the number of network
cards. After the device searching is successful, bind the search handle to the IP.
Note
After the callback search result is returned, find the corresponding local IP
through the search handle, and pass in the local IP when initializing the device
account.

3.2.2 SearchDevicesByIPs
Table 3-5 Search for device in cross-segment
Item Description
Name Search for device IP in cross-segemt.
def SearchDevicesByIPs(cls,
pIpSearchInfo: DEVICE_IP_SEARCH_INFO,
Function cbSearchDevices: fSearchDevicesCB,
dwUserData: C_LDWORD,
szLocalIp: c_char_p = None,

49
Item Description
dwWaitTime: C_DWORD = 5000
) -> c_int:
[in] pIpSearchInfo Search device info.
Search device callback. When a device response
packet returns, NetSDK parses the response packet
[in] cbSearchDevices into valid information and notifies users by the
callback. For details, see the description of
fSearchDevicesCB. Callback cannot be null.
User data. NetSDK returns the data to users by
Parameter [in] dwUserData
fSearchDevicesCB whichis the device search callback.
Local IP. The default value is None. And no value
[in] szLocalIp
enrtered is allowed.
Search time expected by users.
Se the parameters as nedded. This interfacre is a
[in] dwWaitTime
synchronous interface, so it only returns when the
waiting time of search is finished.
 Success: 1.
Return value
 Failure: 0.
This interfacre is a synchronous interface, so it only returns when the waiting
Note time of search is finished. Enter the search time according to own network
situations.

3.2.3 StopSearchDevices
Table 3-6 Stop async searching
Item Description
Stop searching for devices with the same network segment, such as IPC and
Name
NVS.
def StopSearchDevices(cls,
Function lSearchHandle: C_LLONG
) -> c_int
Async search for device ID. Return value of async
Parameter [in] lSearchHandle
search interfaces, such as StartSearchDevicesEx.
 Success: 1.
Return value
 Failure: 0.
Note Use with StartSearchDevicesEx in pairs.

3.2.4 InitDevAccount
Table 3-7 Initialize device
Item Description
Name Initialize device account.

50
Item Description
def InitDevAccount(cls,
pInitAccountIn: NET_IN_INIT_DEVICE_ACCOUNT,
pInitAccountOut: NET_OUT_INIT_DEVICE_ACCOUNT,
Function
dwWaitTime: int = 5000,
szLocalIp: c_char_p = None
) -> c_int
[in] pInitAccountIn Input structure of decive initialization.
[out]pInitAccountOut Output structure of decive initialization.
Parameter [in] dwWaitTime Waiting time. The unit is ms.
Local IP. Should be the same with szLocalIp filed of
[in] szLocalIp
pInBuf of StartSearchDevicesEx.
 Success: 1.
Return value
 Failure: 0.
If the PC has several network cards, you need to call StartSearchDevicesEx for
several times. After the search is successful, the search handle is bound to the IP.
Note
When searching for callback information, find the corresponding local IP by the
search handle. During initialization, szLocalIp should be the local IP.

3.3 Device Login

3.3.1 LoginWithHighLevelSecurity
Table 3-8 Log in
Item Description
Name Log in to the device.
def LoginWithHighLevelSecurity(cls,
stuInParam: NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY,
Function
stuOutParam: NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY
) -> tuple
[in] stuInParam Input parameter structure.
[out] stuOutParam Output parameter structure.
Parameter
[out] device_info Device info.
[out] error_message Error info of login interfece.
 Success: Non-0.
Return value
 Failure: 0.
Note None.

3.3.2 Logout
Table 3-9 Log out
Item Description
Name Log out of the device.

51
Item Description
def Logout(cls,
Function login_id: int
) -> int
Parameter [in]login_id Return value of LoginWithHighLevelSecurity.
 Success: 1.
Return value
 Failure: 0.
Note None.

3.4 Live View

3.4.1 RealPlayEx
Table 3-10 Start preview live ivew
Item Description
Name Start live view.
def RealPlayEx(cls,
login_id: int,
channel: int,
Function
hwnd: int,
play_type=SDK_RealPlayType.Realplay
) -> C_LLONG
[in] login_id Return value of LoginWithHighLevelSecurity.
[in] channel Video channel No. is a round No., starting from 0.
Parameter
[in] hwnd Window handle valid only under Windows system.
[in] play_type Live type.
 Success: Non-0.
Return value
 Failure: 0
Windows system:
 When hWnd is valid, the corresponding window displays picture.
Note
 When hWnd is None, get the video data through setting a callback and
send to user for handle.

Table 3-11 Live type and meaning


Live type Meaning
Realplay Real-time live
Multiplay Multi-picture live
Realplay_0 Live view—main stream, equivalent to Realplay
Realplay_1 Live view—sub stream 1
Realplay_2 Live view—sub stream 2
Realplay_3 Live view—sub stream 3
Multiplay_1 Multi-picture live—1 picture
Multiplay_4 Multi-picture live—4 pictures
Multiplay_8 Multi-picture live—8 pictures

52
Live type Meaning
Multiplay_9 Multi-picture live—9 pictures
Multiplay_16 Multi-picture live—16 pictures
Multiplay_6 Multi-picture live—6 pictures
Multiplay_12 Multi-picture live—12 pictures
Multiplay_25 Multi-picture live—25 pictures
Multiplay_36 Multi-picture live—36 pictures

3.4.2 StopRealPlayEx
Table 3-12 Stop live view
Item Description
Name Stop the live view.
def StopRealPlayEx(cls,
Function realplay_id: int
) -> int
Parameter [in] realplay_id Return value of RealPlayEx.
 Success: 1.
Return value
 Failure: 0.
Note None.

3.5 Record Playback

3.5.1 SetDeviceMode
Table 3-13 Set working mode
Item Description
Name Set working mode.
def SetDeviceMode(cls,
login_id: int,
Function emType: int,
value: c_void_p
) -> c_int
[in] login_id Return value of LoginWithHighLevelSecurity.
Parameter [in] emType Working mode enumeration.
[in] value Structure correspondes to working mode.
 Success: 1.
Return value
 Failure: 0.
Note None.

Table 3-14 Working mode and corresponding structure


emType Enumeration Meaning Structure
Set the record stream type to query
RECORD_STREAM_TYPE and playback by time. None
0: Main and sub stream

53
emType Enumeration Meaning Structure
1: Main stream
2: Sub stream
Set the record file type to playback
RECORD_TYPE EM_RECORD_TYPE
and download by time.

3.5.2 QueryRecordFile
Table 3-15 Query for all the record files within a period
Item Description
Name Query for all the record files within a period.
def QueryRecordFile(cls,
login_id: int,
channel_id: int,
recordfile_type: int,
start_time: NET_TIME,
Function
end_time: NET_TIME,
card_id: str,
wait_time:int,
is_querybytime:bool
) -> tuple
[in] login_id Return value of LoginWithHighLevelSecurity.
[in] channel_id Device channel.
[in] recordfile_type Query type. Refer to EM_QUERY_RECORD_TYPE.
[in] start_time Start time.
[in] end_time End time.
Parameter [in] card_id Card ID.
[in] wait_time Waiting time.
[in] is_querybytime Whether to query by time.
[out] file_count Returned file number.
File info of returned records. The strcture group of
[out] recordfile_infos
NET_RECORDFILE_INFO.
 Success: 1.
Return value
 Failure: 0.
Before playback, call this interface to query the video records. When the info of
searched record within the entered time is greater than the defined buffer size,
Note
SDK only returns the records that can be stored in the buffer. You can continue
to query as needed.

3.5.3 PlayBackByTimeEx2
Table 3-16 Playback by time
Item Description
Name Playback by time.

54
Item Description
def PlayBackByTimeEx2(cls,
login_id: int,
channel_id: int,
Function
in_param: NET_IN_PLAY_BACK_BY_TIME_INFO,
out_param: NET_OUT_PLAY_BACK_BY_TIME_INFO
) -> int:
[in] login_id Return value of LoginWithHighLevelSecurity.
[in] channel_id Device channel No..
Parameter
[in] in_param Query input condition.
[out] out_param Query output information.
 Success: Non-0.
Return value
 Failure: 0.
For the callback declaration cbDownLoadPos and fDownLoadDataCallBack in
NET_IN_PLAY_BACK_BY_TIME_INFO, see "4 Callback Definition."
Note
The parameters hWnd and fDownLoadDataCallBack in pstNetIn cannot be None
at the same time; otherwise, the interface calling will be failed returned.

3.5.4 StopPlayBack
Table 3-17 Stop playback
Item Description
Name Stop playback.
def StopPlayBack(cls,
Function playback_id: int
) -> int
Parameter [in] playback_id Playback handle. Return value of PlayBackByTimeEx2.
 Success: 1.
Return value
 Failure: 0.
Note None.

3.5.5 PausePlayBack
Table 3-18 Pause or resume playback
Item Description
Name Pause or resume playback.
def PausePlayBack(cls,
playback_id: int,
Function
is_pause: bool
) -> int:
[in] playback_id Playback handle. Return value of PlayBackByTimeEx2.
Parameter
[in] is_pause Pause or resume. True: pause; False: resume.
 Success: 1.
Return value
 Failure: 0.
Note None.

55
3.6 Record Download

3.6.1 DownloadByTimeEx
Table 3-19 Download by time
Item Description
Name Download by time.
def DownloadByTimeEx(cls,
login_id: int,
channel_id: int,
recordfile_type: int,
start_time: NET_TIME,
end_time: NET_TIME,
Function save_filename: str,
callback_timedownloadpos: fTimeDownLoadPosCallBack,
time_UserData: C_LDWORD,
callback_timedownloaddata: fDataCallBack,
data_UserData: C_LDWORD,
pReserved: int = 0
) -> int
[in] login_id Return value of LoginWithHighLevelSecurity.
[in] channel_id Device channel No., starting from 0.
[in] recordfile_type Record file type.
[in] start_time Start time.
[in] end_time End time.
[in] save_filename Record file name to be save. Full path.
Parameter
[in] callback_timedownloadpos Download progress callback.
Customized data of download progress
[in] time_UserData
callback.
[in] callback_timedownloaddata Download data callback.
[in] data_UserData Customized data of download data callback.
[in] pReserved Reserved parameter.
 Success: Non-0.
Return value
 Failure: 0.
For callback declaration of callback_timedownloadpos and
callback_timedownloaddata, see "4 Callback Definition."
sSavedFileName is not blank, and the record data is input into the file
Note
corresponding with the path.
fDownLoadDataCallBack is not blank, and the record data is returned through
callback.

56
3.6.2 StopDownload
Table 3-20 Stop record download
Item Description
Name Stop record download.
def StopDownload(cls,
Function download_id: int
) -> int
Parameter [in] download_id Return value of DownloadByTimeEx.
 Success: 1.
Return value
 Failure: 0.
Stop downloading after it is completed or partially completed according to
Note
particular situation.

3.7 Device Control

3.7.1 GetDevConfig
Table 3-21 Get device configuration info
Item Description
Name Get device configuration info.
def GetDevConfig(cls,
login_id: C_LLONG,
cfg_type: C_DWORD,
channel_id: C_LONG,
Function
out_buffer: C_LLONG,
outbuffer_size: C_DWORD,
wait_time: int = 5000
) -> int
[in] login_id Return value of LoginWithHighLevelSecurity.
Query time. For details, see the EM_DEV_CFG_TYPE
[in] cfg_type
enumeration in the SDK_Enum.py file.
Parameter [in] channel_id Quey channel No..
[out] out_buffer Obtained strcture data.
[in] outbuffer_size Data length of out_buffer.
[in] wait_time Timeout.
 Success: 1.
Return value
 Failure: 0.
Note None.

Table 3-22 Configuration type enumeration


emType Enumeration Description
Time configuration. GetDevConfig and SetDevConfig are used
TIMECFG
together.

57
3.7.2 SetDevConfig
Table 3-23 Set device configuration info
Item Description
Name Set device configuration info.
def SetDevConfig(cls,
login_id: C_LLONG,
cfg_type: C_DWORD,
Function channel_id: C_LONG,
in_buffer: C_LLONG,
inbuffer_size: C_DWORD,
wait_time: int = 5000) -> int
[in] login_id Return value of LoginWithHighLevelSecurity.
Query type. For details, see the EM_DEV_CFG_TYPE
[in] cfg_type
enumeration in the SDK_Enum.py file.
Parameter [in] channel_id Quey channel No..
[in] in_buffer Imported strcture data.
[in] inbuffer_size Data length of in_buffer.
[in] wait_time Timeout.
 Success: 1.
Return value
 Failure: 0.
Note None.

3.7.3 RebootDev
Table 3-24 Restart device
Item Description
Name Restart device.
def RebootDev(cls,
Function login_id: int
) -> int:
Parameter [in] login_id Return value of LoginWithHighLevelSecurity.
 Success: 1.
Return value
 Failure: 0.
Note None.

58
3.8 Remote Snapshot

3.8.1 SetSnapRevCallBack
Table 3-25 Set remote snapshot callback
Item Description
Name Set snapshot callback.
def SetSnapRevCallBack(cls,
OnSnapRevMessage: fSnapRev,
Function
dwUser: C_LDWORD
) -> None
[in] OnSnapRevMessage Remote snapshot callback.
Parameter User data. SDK will return data to users by
[in] dwUser
fSnapRev.
Return value None.
Note Call SetSnapRevCallBack before calling SnapPictureEx.

3.8.2 SnapPictureEx
Table 3-26 Snapshot command intension interface
Item Description
Name Snapshot command intension interface.
def SnapPictureEx(cls,
lLoginID:C_LLONG,
Function par:SNAP_PARAMS,
reserved=0
)->c_int
[in] lLoginID Return value of LoginWithHighLevelSecurity.
Snapshot parameters. For detalis, see
Parameter [in] par
SNAP_PARAMS structure.
[in] reserved Picture format.
 Success: 1.
Return value
 Failure: 0.
Note None.

59
3.9 Alarm Upload

3.9.1 SetDVRMessCallBackEx1
Table 3-27 Set alarm callback
Item Description
Name Set alarm callback.
def SetDVRMessCallBackEx1(cls,
cbMessage:fMessCallBackEx1,
Function
dwUser:C_LDWORD
)->None
[in] cbMessage Alarm callback. For details, see fMessCallBackEx1.
Parameter User data. SDK will return data to users by
[in] dwUser
fMessCallBackEx1.
Return value None.
Note Call StartListenEx before calling SetDVRMessCallBackEx1.

3.9.2 StartListenEx
Table 3-28 Start alarm subscription
Item Description
Name Extension interface of device alarm subscribtion.
def StartListenEx(cls,
Function lLoginID:C_LLONG
)->c_int
Parameter [in] lLoginID Return value of LoginWithHighLevelSecurity.
 Success: 1.
Return value
 Failure: 0.
All alarm evnets of devices are fed back by callback set in
Note
SetDVRMessCallBackEx1

3.9.3 StopListen
Table 3-29 Stop alarm subscription
Item Description
Name Stop alarm subscribtion.
def StopListen(cls,
Function lLoginID:C_LLONG
)->c_int
Parameter [in] lLoginID Return value of LoginWithHighLevelSecurity.
 Success: 1.
Return value
 Failure: 0.
Note None.

60
3.10 Intelligent Traffic Event Upload

3.10.1 RealLoadPictureEx
Table 3-30 Intelligent image alarm subscription
Item Description
Name Intelligent image alarm subscription.
def RealLoadPictureEx(cls,
lLoginID: C_LLONG,
nChannelID: c_int,
dwAlarmType: c_ulong,
Function bNeedPicFile: c_int,
cbAnalyzerData: fAnalyzerDataCallBack,
dwUser: C_LDWORD = 0,
reserved: c_void_p = None
) -> C_LLONG
[in] lLoginID Return value of LoginWithHighLevelSecurity.
Channel No. of intelligent image alarm subscribtion,
[in] nChannelID
starting from 0.
Alarm event type expected to subscribe. Refer to
[in] dwAlarmType
EM_EVENT_IVS_TYPE.
Subscribe to image file or not?
[in] bNeedPicFile 1: Subscribe to image.
Parameter
0: Not subscribe to image.
Callback of intelligent event. When there is intelligent
[in]cbAnalyzerData image alarm be uploaded, NetSDK will returns data to
users.
User data. SDK will return data to users by
[in] dwUser
fAnalyzerDataCallBack.
[in] reserved Reserved parameter.
 Success: ID of Intelligent image alarm subscription.
Return value
 Failure: 0, and it will be the parameter of StopLoadPic.
If you need to subscribe to several events on one channel, set the evnt type as
Note EM_EVENT_IVS_ALL to subscribe to all event types when calling
RealLoadPictureEx, and then process the evnets you need.

3.10.2 StopLoadPic
Table 3-31 Stop subscription of intelligent event
Item Description
Name Stop subscribtion of intelligent event.
def StopLoadPic(cls,
Function lAnalyzerHandle:C_LLONG
)->c_int

61
Item Description
Parameter [in] lAnalyzerHandle Return value of RealLoadPictureEx.
 Success: 1.
Return value
 Failure: 0.
Note None.

62
4 Callback Definition

4.1 fDisConnect

Table 4-1 Disconnection callback


Item Description
Name Disconnection callback.
Precondition None.
Function fDisConnect = WINFUNCTYPE(None, C_LLONG, c_char_p, c_long, C_LDWORD)
lLoginID Login handle.
pchDVRIP IP address.
Parameter
nDVRPort Port.
dwUser User data.
Return value None.
Be triggered when the device is disconnected.
Note It is not recommended to call any NetSDK interface in this callback. If the
callback in the Demo calls, then you can follow and call.

4.2 fHaveReConnect

Table 4-2 Reconnection callback


Item Description
Name Reconnection callback.
Precondition None.
fHaveReConnect = WINFUNCTYPE(None, C_LLONG, c_char_p, c_long,
Function
C_LDWORD)
lLoginID Login handle.
pchDVRIP IP address.
Parameter
nDVRPort Port.
dwUser User data.
Return value None.
Be triggered when the device is disconnected.
Note It is not recommended to call any NetSDK interface in this callback. If the
callback in the Demo calls, then you can follow and call.

4.3 fSearchDevicesCBEx
Table 4-3 Async device search callback
Item Description
Name Device search callback prototype.

63
Item Description
Precondition None.
fSearchDevicesCBEx = WINFUNCTYPE(None, C_LLONG,
Function
POINTER(DEVICE_NET_INFO_EX2), c_void_p)
lSearchHandle Search handle.
Parameter pDevNetInfo Device info.
pUserData User data info.
Return value None.
Device search callback.
It is not recommended to call any NetSDK interface in this callback. If the
Note callback in the Demo calls, then you can follow and call.
Set the callback by StartSearchDeviceEx. When a device is searched, the SDK will
call this callback.

4.4 fSearchDevicesCB
Table 4-4 Device search callback
Item Description
Name Device search callback prototype.
Precondition None.
fSearchDevicesCB = WINFUNCTYPE(None, POINTER(DEVICE_NET_INFO_EX),
Function
c_void_p)
pDevNetInfo Info.
Parameter
pUserData User data info.
Return value None.
Device search callback.
It is not recommended to call any NetSDK interface in this callback. If the
Note callback in the Demo calls, then you can follow and call.
Set the callback by SearchDevicesByIPs. When a device is searched, the SDK will
call this callback.

4.5 fDownLoadPosCallBack
Table 4-5 Playback progress callback
Item Description
Name Playback progress callback.
Precondition None.
fDownLoadPosCallBack = WINFUNCTYPE(None, C_LLONG, C_DWORD, C_DWORD,
Function
C_LDWORD)
lPlayHandle Return handel of PlayBackByTimeEx.
Parameter
dwTotalSize Total size of download.

64
Item Description
The size that has been downloaded..
 -1: Current download or playback has been
dwDownLoadSize finished.
 -2: The user does not have permission to
download or playback.
dwUser User data.
Return value None.
Playback progress callback.
Note It is not recommended to call any NetSDK interface in this callback. If the callback
in the Demo calls, then you can follow and call.

4.6 fDataCallBack
Table 4-6 Playback data callback
Item Description
Name Playback data callback.
Precondition None.
fDataCallBack = WINFUNCTYPE(c_int, C_LLONG, C_DWORD, POINTER(c_ubyte),
Function
C_DWORD, C_LDWORD)
lPlayHandle Playback data handle.
dwDataType Data type.
Parameter pBuffer Data buffer. Memory is released internally by NetSDK.
dwBufSize Data buffer size.
dwUser User data.
1: Succeed to call back.
Return value
0: Failed to call back. The next callback will return the subsequent data.
Data callback of downloading records..
Note It is not recommended to call any NetSDK interface in this callback. If the
callback in the Demo calls, then you can follow and call.

4.7 fTimeDownLoadPosCallBack
Table 4-7 Callback of download by time callback
Item Description
Name Callback of download by time.
Precondition None.
fTimeDownLoadPosCallBack = WINFUNCTYPE(None, C_LLONG, C_DWORD,
Function
C_DWORD, c_int, NET_RECORDFILE_INFO, C_LDWORD)
lPlayHandle Return handel of DownloadByTimeEx.
dwTotalSize Total size of download.
Parameter dwDownLoadSize The size that has been downloaded..
Index Index.
Recordfileinfo Record file information.

65
Item Description
dwUser User data.
Return value None.
Download progress callback.
Note It is not recommended to call any NetSDK interface in this callback. If the callback
in the Demo calls, then you can follow and call.

4.8 fAnalyzerDataCallBack
Table 4-8 Intelligent image alarm callback
Item Description
Name Intelligent image alarm callback.
Precondition None.
fAnalyzerDataCallBack = WINFUNCTYPE(None, C_LLONG, C_DWORD, c_void_p,
Function
POINTER(c_ubyte), C_DWORD, C_LDWORD, c_int, c_void_p)
lAnalyzerHandle Return handel of RealLoadPictureEx.
dwAlarmType Event type of EM_EVENT_IVS_TYPE.
pAlarmInfo Event info.
pBuffer Image data buffer.
dwBufSize Image data buffer size.
dwUser User data info entered by RealLoadPictureEx..
Situation of the same uploaded image.
Parameter  0: First time to appear.
nSequence
 1: Same image will appear from this time on.
 2: Last time to appear or only once.
Indicate the status of current called back data when int
nState = (int)reserved.
Reserved  0: Current data is real-time data.
 1: Current data is offline data.
 2: Offline data transmission ends.
Return value None.
Intelligent image alarm callback.
It is not recommended to call any NetSDK interface in this callback. If the callback
in the Demo calls, then you can follow and call.
Note
Set the callback by RealLoadPictureEx. When an intelligent image event is
uploaded, the SDK will call this callback.
The dwAlarmType value varies according to different data type of pAlarmInfo.

4.9 fSnapRev

Table 4-9 Snapshot callback


Item Description
Name Snapshot callback prototype.

66
Item Description
Precondition None.
fSnapRev = WINFUNCTYPE(None, C_LLONG, POINTER(c_ubyte), c_uint, c_uint,
Function
C_DWORD, C_LDWORD)
lLoginID Login handle.
pBuf Image buffer.
RevLen Image size.
Encode type:
Parameter
EncodeType  10: Jpeg image.
 0: I frame of mpeg4.
CmdSerial Command serial No..
dwUser User data entered by SetSnapRevCallBack.
Return value None.
Snapshot callback function.
It is not recommended to call any NetSDK interface in this callback. If the
Note callback in the Demo calls, then you can follow and call.
Set this callback by SetSnapRevCallBack. When the snapshot data is sent, the
SDK will call this callback.

4.10 fMessCallBackEx1
Table 4-10 Alarm upload callback
Item Description
Name Alarm upload callback prototype.
Precondition None.
fMessCallBackEx1 = WINFUNCTYPE(None, c_long, C_LLONG, POINTER(c_char),
Function
C_DWORD, POINTER(c_char), c_long, c_int, c_long, C_LDWORD)
lCommand Alarm type.
lLoginID Login handle.
pBuf Alarm info.
dwBufLen Alarm info size.
pchDVRIP IP address.
Parameter nDVRPort Port.
 1: The event can be confirmed.
bAlarmAckFlag
 0: The event cannot be confirmed.
Used to assign values to the input parameters of the
nEventID
AlarmAck. hen bAlarmAckFlag is 1, the data is valid.
dwUser User data entered by SetDVRMessCallBackEx1.
Return value None.
All registered devices use one alarm upload callback.
You can identify the uploaded device by parameter lLoginI.D.
Note Data type of pBuf varies according to lCommand value.
It is not recommended to call any NetSDK interface in this callback. If the
callback in the Demo calls, then you can follow and call.

67
Appendix 1 Cybersecurity Recommendations

Cybersecurity is more than just a buzzword: it’s something that pertains to every device that is
connected to the internet. IP video surveillance is not immune to cyber risks, but taking basic steps
toward protecting and strengthening networks and networked appliances will make them less
susceptible to attacks. Below are some tips and recommendations on how to create a more secured
security system.
Mandatory actions to be taken for basic equipment network security:
1. Use Strong Passwords
Please refer to the following suggestions to set passwords:
 The length should not be less than 8 characters;
 Include at least two types of characters; character types include upper and lower case
letters, numbers and symbols;
 Do not contain the account name or the account name in reverse order;
 Do not use continuous characters, such as 123, abc, etc.;
 Do not use overlapped characters, such as 111, aaa, etc.;
2. Update Firmware and Client Software in Time
 According to the standard procedure in Tech-industry, we recommend to keep your
equipment (such as NVR, DVR, IP camera, etc.) firmware up-to-date to ensure the system is
equipped with the latest security patches and fixes. When the equipment is connected to
the public network, it is recommended to enable the “auto-check for updates” function to
obtain timely information of firmware updates released by the manufacturer.
 We suggest that you download and use the latest version of client software.
"Nice to have" recommendations to improve your equipment network security:
1. Physical Protection
We suggest that you perform physical protection to equipment, especially storage devices. For
example, place the equipment in a special computer room and cabinet, and implement
well-done access control permission and key management to prevent unauthorized personnel
from carrying out physical contacts such as damaging hardware, unauthorized connection of
removable equipment (such as USB flash disk, serial port), etc.
2. Change Passwords Regularly
We suggest that you change passwords regularly to reduce the risk of being guessed or cracked.
3. Set and Update Passwords Reset Information Timely
The equipment supports password reset function. Please set up related information for
password reset in time, including the end user’s mailbox and password protection questions. If
the information changes, please modify it in time. When setting password protection questions,
it is suggested not to use those that can be easily guessed.
4. Enable Account Lock
The account lock feature is enabled by default, and we recommend you to keep it on to
guarantee the account security. If an attacker attempts to log in with the wrong password
several times, the corresponding account and the source IP address will be locked.
5. Change Default HTTP and Other Service Ports
We suggest you to change default HTTP and other service ports into any set of numbers
between 1024~65535, reducing the risk of outsiders being able to guess which ports you are
using.

68
6. Enable HTTPS
We suggest you to enable HTTPS, so that you visit Web service through a secure communication
channel.
7. MAC Address Binding
We recommend you to bind the IP and MAC address of the gateway to the equipment, thus
reducing the risk of ARP spoofing.
8. Assign Accounts and Privileges Reasonably
According to business and management requirements, reasonably add users and assign a
minimum set of permissions to them.
9. Disable Unnecessary Services and Choose Secure Modes
If not needed, it is recommended to turn off some services such as SNMP, SMTP, UPnP, etc., to
reduce risks.
If necessary, it is highly recommended that you use safe modes, including but not limited to the
following services:
 SNMP: Choose SNMP v3, and set up strong encryption passwords and authentication
passwords.
 SMTP: Choose TLS to access mailbox server.
 FTP: Choose SFTP, and set up strong passwords.
 AP hotspot: Choose WPA2-PSK encryption mode, and set up strong passwords.
10. Audio and Video Encrypted Transmission
If your audio and video data contents are very important or sensitive, we recommend that you
use encrypted transmission function, to reduce the risk of audio and video data being stolen
during transmission.
Reminder: encrypted transmission will cause some loss in transmission efficiency.
11. Secure Auditing
 Check online users: we suggest that you check online users regularly to see if the device is
logged in without authorization.
 Check equipment log: By viewing the logs, you can know the IP addresses that were used
to log in to your devices and their key operations.
12. Network Log
Due to the limited storage capacity of the equipment, the stored log is limited. If you need to
save the log for a long time, it is recommended that you enable the network log function to
ensure that the critical logs are synchronized to the network log server for tracing.
13. Construct a Safe Network Environment
In order to better ensure the safety of equipment and reduce potential cyber risks, we
recommend:
 Disable the port mapping function of the router to avoid direct access to the intranet
devices from external network.
 The network should be partitioned and isolated according to the actual network needs. If
there are no communication requirements between two sub networks, it is suggested to
use VLAN, network GAP and other technologies to partition the network, so as to achieve
the network isolation effect.
 Establish the 802.1x access authentication system to reduce the risk of unauthorized access
to private networks.
 Enable IP/MAC address filtering function to limit the range of hosts allowed to access the
device.

69

You might also like