官网文档地址
https://www.onvif.org/onvif/ver20/util/operationIndex.html
import subprocess
import time
import WSDiscovery
import zeep
from onvif import ONVIFCamera
from typing import List
def getTime(timedata, equation="%Y-%m-%d %H:%M:%S"):
"""
字符串转换为时间戳
"""
timeArray = time.strptime(timedata, equation)
# 转换为时间戳
timeStamp = int(time.mktime(timeArray))
return timeStamp
def getTimeStr(timdata, equation="%Y-%m-%d %H:%M:%S"):
# 转换成localtime
time_local = time.localtime(timdata)
# 转换成新的时间格式(2016-05-05 20:28:54)
dt = time.strftime(equation, time_local)
return dt
class CameraONVIF:
"""此类用于从该特定网络上发现的所有摄像机获取信息"""
def __init__(self, ip, user, password, port):
"""
ip (str): 摄像机的ip.
user (str): 摄像机的账号
password (str): 摄像机的密码
"""
self.cam_ip = ip
self.cam_user = user
self.cam_password = password
self.cam_port = port
def zeep_pythonvalue(self, xmlvalue): # 额外加的
return xmlvalue
def camera_start(self):
"""启动模块 """
mycam = ONVIFCamera(self.cam_ip, self.cam_port, self.cam_user, self.cam_password, no_cache=True)
media = mycam.create_media_service()
zeep.xsd.simple.AnySimpleType.pythonvalue = self.zeep_pythonvalue # 额外加的
media_profile = media.GetProfiles()[0]
self.mycam = mycam
self.camera_media = media
self.camera_media_profile = media_profile
devicemgmt = mycam.create_devicemgmt_service()
self.devicemgmt = devicemgmt
def get_hostname(self) -> str:
"""
查找摄像机的主机名
returns:
str: Hostname
"""
resp = self.mycam.devicemgmt.GetHostname()
print(resp)
return resp.Name
def get_manufacturer(self) -> str:
"""
查找制造商
returns:
str:Manufacturer.
"""
resp = self.mycam.devicemgmt.GetDeviceInformation()
return resp.Manufacturer
def get_model(self) -> str:
"""
查找型号
returns:
str: Model.
"""
resp = self.mycam.devicemgmt.GetDeviceInformation()
return resp.Model
def get_firmware_version(self) -> str:
"""
查找固件版本。
returns:
str: Firmware version.
"""
resp = self.mycam.devicemgmt.GetDeviceInformation()
return resp.FirmwareVersion
def get_mac_address(self) -> str:
"""
查找摄像头的序列号。
returns:
str: 序列号.
"""
resp = self.mycam.devicemgmt.GetDeviceInformation()
return resp.SerialNumber
def get_hardware_id(self) -> str:
"""
查找摄像头的硬件id
returns:
str: 硬件id
"""
resp = self.mycam.devicemgmt.GetDeviceInformation()
return resp.HardwareId
def get_resolutions_available(self) -> List:
"""
查找相机的所有分辨率。
returns:
tuple: 分辨率列表(Width, Height).
"""
request = self.camera_media.create_type('GetVideoEncoderConfigurationOptions')
request.ProfileToken = self.camera_media_profile.token
config = self.camera_media.GetVideoEncoderConfigurationOptions(request)
return [(res.Width, res.Height) for res in config.H264.ResolutionsAvailable]
def get_frame_rate_range(self) -> int:
"""
找到相机的帧速率范围。
returns:
int: FPS min.
int: FPS max.
"""
request = self.camera_media.create_type('GetVideoEncoderConfigurationOptions')
request.ProfileToken = self.camera_media_profile.token
config = self.camera_media.GetVideoEncoderConfigurationOptions(request)
return config.H264.FrameRateRange.Min, config.H264.FrameRateRange.Max
def is_ptz(self) -> bool:
"""
检查摄像头是否为云台。
returns:
bool: Is PTZ or not.
"""
resp = self.mycam.devicemgmt.GetCapabilities()
return bool(resp.PTZ)
def get_rtsp(self):
"""获取rtsp地址"""
obj = self.camera_media.create_type('GetStreamUri')
obj.StreamSetup = {'Stream': 'RTP-Unicast', 'Transport': {'Protocol': 'RTSP'}}
obj.ProfileToken = self.camera_media_profile.token
res_uri = self.camera_media.GetStreamUri(obj)['Uri']
return res_uri
def get_date(self) -> str:
"""
查找摄像机上配置的日期。
returns:
str: Date in string.
"""
datetime = self.mycam.devicemgmt.GetSystemDateAndTime()
print(datetime)
print("UTCDateTime", datetime["UTCDateTime"])
print("LocalDateTime", datetime["LocalDateTime"])
return datetime.UTCDateTime.Date
def get_time(self) -> str:
"""
查找摄像机上配置的本地时间
returns:
str: Hour in string.
"""
datetime = self.mycam.devicemgmt.GetSystemDateAndTime()
return datetime.UTCDateTime.Time
def set_datetime(self):
"""设置摄像机上配置的日期 时间"""
try:
# datetime1 = self.devicemgmt.SetSystemDateAndTime()
time_params = self.mycam.devicemgmt.create_type('SetSystemDateAndTime')
print(time_params)
time_params["DateTimeType"] = 'Manual'
time_params["DaylightSavings"] = True
time_params["TimeZone"] = {"TZ": "CST-8:00:00"}
UTCDateTime = getTimeStr(time.time() - (8 * 3600))
print("UTCDateTime", UTCDateTime)
Year = UTCDateTime[0:4]
Month = UTCDateTime[5:7]
Day = UTCDateTime[8:10]
Hour = UTCDateTime[11:13]
Minute = UTCDateTime[14:16]
Second = UTCDateTime[17:19]
time_params["UTCDateTime"] = {
"Time": {"Hour": Hour, "Minute": Minute, "Second": Second},
"Date": {"Year": Year, "Month": Month, "Day": Day},
}
self.mycam.devicemgmt.SetSystemDateAndTime(time_params)
return True
except Exception as e:
print(e)
return False
def get_gateway(self):
"""获取获取网络默认网关"""
try:
resGateway = self.devicemgmt.GetNetworkDefaultGateway()
return resGateway
except Exception as e:
print(e)
return False
def get_ip_filter(self):
"""获取ip地址过滤器"""
try:
resp = self.devicemgmt.GetIPAddressFilter()
return resp
except Exception as e:
print(e)
return False
def set_ip_filter(self):
"""设置ip地址过滤器"""
try:
# resp = self.devicemgmt.create_type('SetIPAddressFilter')
resp = self.mycam.devicemgmt.create_type('SetIPAddressFilter')
print(resp)
resp["IPAddressFilter"] = {
"Type": "Allow",
"IPv4Address": [{"Address": "192.168.1.123", "PrefixLength ": 24}]
}
self.mycam.devicemgmt.SetIPAddressFilter(resp)
return True
except Exception as e:
print(e)
return False
def get_dp(self):
"""获取DP地址"""
try:
resDP = self.devicemgmt.GetDPAddresses()
# print("GetDPAddresses", resDP)
return resDP
except Exception as e:
print(e)
return False
def get_dns(self):
"""获取DNS"""
try:
resDNS = self.devicemgmt.GetDNS()
# print("GetDNS", resDNS)
return resDNS
except Exception as e:
print(e)
return False
def get_ZeroConfig(self):
"""获取零配置"""
try:
resZeroConfig = self.devicemgmt.GetZeroConfiguration()
return resZeroConfig
except Exception as e:
print(e)
return False
def set_ZeroConfig(self):
"""设置零配置"""
try:
# resZeroConfig = self.devicemgmt.create_type('SetZeroConfiguration')
resZeroConfig = self.mycam.devicemgmt.create_type('SetZeroConfiguration')
print("SetZeroConfiguration", resZeroConfig)
resZeroConfig["InterfaceToken"] = "eth0"
resZeroConfig["Enabled"] = True
# self.devicemgmt.SetZeroConfiguration(resZeroConfig)
self.mycam.devicemgmt.SetZeroConfiguration(resZeroConfig)
return True
except Exception as e:
print(e)
return False
def get_network_interfaces(self):
"""获取网络接口"""
try:
resNetworkInterfaces = self.devicemgmt.GetNetworkInterfaces()
return resNetworkInterfaces
except Exception as e:
print(e)
return False
def set_network_interfaces(self):
"""设置网络接口 改ip"""
try:
resNetworkInterfaces = self.mycam.devicemgmt.create_type('SetNetworkInterfaces')
print("SetNetworkInterfaces", resNetworkInterfaces)
resNetworkInterfaces["InterfaceToken"] = "eth0"
resNetworkInterfaces["NetworkInterface"] = {
"IPv4": {
"Enabled": True,
"Manual": [{'Address': '192.168.1.102', 'PrefixLength': 24}],
"DHCP": False
}
}
self.mycam.devicemgmt.SetNetworkInterfaces(resNetworkInterfaces)
return True
except Exception as e:
print(e)
return False
def get_wsdl_url(self):
"""获取用户 GetWsdlUrl"""
try:
resGetWsdlUrl = self.devicemgmt.GetWsdlUrl()
return resGetWsdlUrl
except Exception as e:
print(e)
return False
def get_users(self):
"""获取用户"""
try:
resGetUsers = self.devicemgmt.GetUsers()
print("GetUsers", resGetUsers[0].Username)
print(e)
return resGetUsers
except Exception as e:
print(e)
return False
def get_remote_users(self):
"""获取远程用户"""
try:
# resRemoteUsers = self.devicemgmt.GetRemoteUser()
resRemoteUsers = self.mycam.devicemgmt.GetRemoteUser()
# print("GetRemoteUser", resRemoteUsers)
return resRemoteUsers
except Exception as e:
print(e)
return False
def set_users(self):
"""设置用户"""
try:
resSetUser = self.mycam.devicemgmt.create_type('SetUser')
print("SetUser", resSetUser)
resSetUser["User"] = {
"Username": "chengxi",
"Password": "cx890808",
"UserLevel": "Administrator",
"Extension": None
}
self.mycam.devicemgmt.SetUser(resSetUser)
return True
except Exception as e:
print(e)
return False
def configCamVideo(ip="192.168.1.102"):
"""修改摄像头分辨率"""
try:
mycam = ONVIFCamera(ip, 80, 'admin', 'Barneye111')
media2_service = mycam.create_media_service()
configurations = media2_service.GetVideoEncoderConfigurations()
for configuration in configurations:
if configuration['Name'] == 'VideoEncoder001':
if configuration['Encoding'].lower() == 'h264' or configuration['Encoding'].lower() == 'h265':
width = configuration['Resolution']['Width']
height = configuration['Resolution']['Height']
configuration['Resolution']['Width'] = 704
configuration['Resolution']['Height'] = 576
configuration['RateControl']['FrameRateLimit'] = 1
configuration['RateControl']['BitrateLimit'] = 448
configuration['GovLength'] = 1
print(configuration)
response = media2_service.SetVideoEncoderConfiguration(configuration)
return True
except Exception as e:
print(e)
return False
if __name__ == '__main__':
# ip_list = ws_discovery()
o = CameraONVIF(ip="192.168.1.102", user="admin", password="123456", port="80")
# o = CameraONVIF(ip="192.168.1.102", user="xxxxxx", password="123456", port="80")
o.camera_start()
print("查找摄像机的主机名", o.get_hostname()) # localhost
# print("查找制造商", o.get_manufacturer())
# print("查找型号", o.get_model())
# print("查找固件版本", o.get_firmware_version())
# print("查找摄像头的序列号", o.get_mac_address())
# print("查找摄像头的硬件id", o.get_hardware_id())
# print("查找相机的所有分辨率", o.get_resolutions_available())
# print("找到相机的帧速率范围", o.get_frame_rate_range())
# print("检查摄像头是否为云台", o.is_ptz()) # False
# print("获取rtsp地址", o.get_rtsp())
# rtsp://192.168.1.102:554/Streaming/Channels/101?transportmode=unicast&profile=Profile_1
print("获取DP地址", o.get_dp())
print("获取DNS", o.get_dns())
print("查找摄像机上配置的日期", o.get_date())
print("查找摄像机上配置的本地时间", o.get_time())
# print("设置摄像机上配置的日期 时间", o.set_datetime()) # 改日期-时间 成功
print("获取ip地址过滤器", o.get_ip_filter())
# print("设置ip地址过滤器", o.set_ip_filter()) # 失败
print("获取获取网络默认网关", o.get_gateway())
print("获取零配置", o.get_ZeroConfig())
# print("设置零配置", o.set_ZeroConfig()) # 有ip 但不能改
print("获取网络接口", o.get_network_interfaces())
# print("设置网络接口", o.set_network_interfaces()) # TODO 改ip 成功
print("获取WsdlUrl", o.get_wsdl_url())