def media_profile_configuration(): ''' A media profile consists of configuration entities such as video/audio source configuration, video/audio encoder configuration, or PTZ configuration. This use case describes how to change one configuration entity which has been already added to the media profile. ''' # Create the media service # mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345') mycam = ONVIFCamera('10.9.6.49', 80, 'admin', '12345', 'C:\onvif\wsdl\\') media_service = mycam.create_media_service() profiles = media_service.GetProfiles() # Use the first profile and Profiles have at least one token = profiles[0]._token # Get all video encoder configurations configurations_list = media_service.GetVideoEncoderConfigurations() # Use the first profile and Profiles have at least one video_encoder_configuration = configurations_list[0] # Get video encoder configuration options options = media_service.GetVideoEncoderConfigurationOptions({'ProfileToken':token}) # Setup stream configuration video_encoder_configuration.Encoding = 'H264' # Setup Resolution video_encoder_configuration.Resolution.Width = \ options.H264.ResolutionsAvailable[0].Width video_encoder_configuration.Resolution.Height = \ options.H264.ResolutionsAvailable[0].Height # Setup Quality video_encoder_configuration.Quality = options.QualityRange.Max # Setup FramRate video_encoder_configuration.RateControl.FrameRateLimit = \ options.H264.FrameRateRange.Max # Setup EncodingInterval video_encoder_configuration.RateControl.EncodingInterval = \ options.H264.EncodingIntervalRange.Max # Setup Bitrate video_encoder_configuration.RateControl.BitrateLimit = \ options.Extension.H264[0].BitrateRange[0].Min[0] # Create request type instance request = media_service.create_type('SetVideoEncoderConfiguration') request.Configuration = video_encoder_configuration # ForcePersistence is obsolete and should always be assumed to be True request.ForcePersistence = True # Set the video encoder configuration media_service.SetVideoEncoderConfiguration(request)
def rotate_image_180(): ''' Rotate the image ''' # Create the media service mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345') media_service = mycam.create_media_service() profiles = media_service.GetProfiles() # Use the first profile and Profiles have at least one token = profiles[0]._token # Get all video source configurations configurations_list = media_service.GetVideoSourceConfigurations() # Use the first profile and Profiles have at least one video_source_configuration = configurations_list[0] # Enable rotate video_source_configuration.Extension[0].Rotate[0].Mode[0] = 'OFF' # Create request type instance request = media_service.create_type('SetVideoSourceConfiguration') request.Configuration = video_source_configuration # ForcePersistence is obsolete and should always be assumed to be True request.ForcePersistence = True # Set the video source configuration media_service.SetVideoSourceConfiguration(request)
def __init__(self, hass, config): """Initialize a ONVIF camera.""" from onvif import ONVIFCamera, exceptions super().__init__() self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._input = None camera = None try: _LOGGER.debug("Connecting with ONVIF Camera: %s on port %s", config.get(CONF_HOST), config.get(CONF_PORT)) camera = ONVIFCamera( config.get(CONF_HOST), config.get(CONF_PORT), config.get(CONF_USERNAME), config.get(CONF_PASSWORD) ) media_service = camera.create_media_service() stream_uri = media_service.GetStreamUri( {'StreamSetup': {'Stream': 'RTP-Unicast', 'Transport': 'RTSP'}} ) self._input = stream_uri.Uri.replace( 'rtsp://', 'rtsp://{}:{}@'.format( config.get(CONF_USERNAME), config.get(CONF_PASSWORD)), 1) _LOGGER.debug( "ONVIF Camera Using the following URL for %s: %s", self._name, self._input) except Exception as err: _LOGGER.error("Unable to communicate with ONVIF Camera: %s", err) raise try: self._ptz = camera.create_ptz_service() except exceptions.ONVIFError as err: self._ptz = None _LOGGER.warning("Unable to setup PTZ for ONVIF Camera: %s", err)
def __deviceProc(self): res = url.urlparse(self.__xaddr) print(res) tmp = res[1].split(':') ip = tmp[0] if len(tmp) > 1: port = tmp[1] else: port = 80 num, matrix = read_anno_config('./Elec_Solution2/config/anno0.json') # get camera instance cam = ONVIFCamera(ip, port, '', '') # create media service media_service = cam.create_media_service() token = '000' # set video configuration configurations_list = media_service.GetVideoEncoderConfigurations() video_encoder_configuration = configurations_list[0] options = media_service.GetVideoEncoderConfigurationOptions({'ProfileToken':token}) video_encoder_configuration.Encoding = 'H264' video_encoder_configuration.Resolution = options.H264.ResolutionsAvailable[0] request = media_service.create_type('SetVideoEncoderConfiguration') request.Configuration = video_encoder_configuration request.ForcePersistence = True media_service.SetVideoEncoderConfiguration(request) # get video stream streamSetup = { 'StreamSetup': { 'Stream': 'RTP-Unicast', 'Transport': { 'Protocol': 'TCP' } }, 'ProfileToken': token } res = media_service.GetStreamUri(streamSetup) self.__rtsp = cv2.VideoCapture(res.Uri) reporter = context.getContext().reporter # capture and detect while self.__rtsp.isOpened(): print('%s capture start...' % ip) start = time.time() print('start: %d' % start) ret, frame = self.__rtsp.read() print('capture: %d' % time.time()) # img = cv2.cvtColor(numpy.asarray(frame),cv2.COLOR_RGB2BGR) print('convert: %d' % time.time()) tmp = self.__urn.split('-') name = tmp[-1] + '.jpg' cv2.imwrite(name, frame) detect_result = entry_detect(frame, num, matrix) print(detect_result) print('%s capture end %d. duration:%d' % (ip, time.time(), time.time() - start)) reporter.publish('hm_test', detect_result) time.sleep(10)
def __init__(self, ip_address, login=None, password=None, port=80): self.cam = ONVIFCamera(ip_address, port, login, password) self.media = self.cam.create_media_service() self.media_profile = self.media.GetProfiles()[0] self.ptz = self.cam.create_ptz_service() request = self.ptz.create_type("GetConfigurationOptions") request.ConfigurationToken = self.media_profile.PTZConfiguration.token ptz_configuration_options = self.ptz.GetConfigurationOptions(request) self.continuous_move = self.ptz.create_type("ContinuousMove") self.continuous_move.ProfileToken = self.media_profile.token self.continuous_move.Velocity = self.ptz.GetStatus({ "ProfileToken": self.media_profile.token }).Position self.continuous_move.Velocity.PanTilt.space = ( ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0]. URI) self.continuous_move.Velocity.Zoom.space = ( ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[0].URI ) self.XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Max self.XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Min self.YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Max self.YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Min
async def setup_move(): mycam = ONVIFCamera(IP, PORT, USER, PASS) await mycam.update_xaddrs() # Create media service object media = mycam.createService('media') # Create ptz service object global ptz ptz = mycam.createService('ptz') # Get target profile media_profile = await media.GetProfiles()[0] # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration.token ptz_configuration_options = await ptz.GetConfigurationOptions(request) global moverequest moverequest = ptz.create_type('ContinuousMove') moverequest.ProfileToken = media_profile.token if moverequest.Velocity is None: moverequest.Velocity = await ptz.GetStatus({'ProfileToken': media_profile.token}).Position # Get range of pan and tilt # NOTE: X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Min
def get_current_preset(self): mycam = ONVIFCamera(CAMERA_IP, CAMERA_CONTROL_PORT, CAMERA_USER_NAME, CAMERA_PASSWORD, '/etc/onvif/wsdl/') # Create media service object media = mycam.create_media_service() print("setup_move {} {}", mycam, media) # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] profileToken = media_profile.token # GetStatus print("GetStatus") self.status = ptz.GetStatus({'ProfileToken': profileToken}) print('status {} {} {} ? => {}'.format( self.status.Position.PanTilt.x, self.status.Position.PanTilt.y, self.status.Position.Zoom.x, self.status.MoveStatus.PanTilt)) min_dist = 100 current_prest = None for preset in self.presets: position = preset['PTZPosition'] dist = pow( (self.status.Position.PanTilt.x - position.PanTilt.x), 2) + pow( (self.status.Position.PanTilt.y - position.PanTilt.y), 2) if dist < min_dist: min_dist = dist current_prest = preset # snapshot = media.GetSnapshotUri({'ProfileToken': profileToken}) # print('snapshot uri {}'.format(snapshot)) return current_prest, self.status.MoveStatus.PanTilt
def __init__(self, ip, port, login, password): #соединение с камерой self.my_cam = ONVIFCamera(ip, port, login, password) # Создание медиа сервиса self.media_service = self.my_cam.create_media_service() self.profiles = self.media_service.GetProfiles() self.media_profile = self.profiles[0] # создание ptz сервиса self.ptz = self.my_cam.create_ptz_service() self.request_absolute_move = self.ptz.create_type("AbsoluteMove") self.request_absolute_move.ProfileToken = self.media_profile.token self.request_stop = self.ptz.create_type("Stop") self.request_stop.ProfileToken = self.media_profile.token # создание imaging сервиса self.imaging = self.my_cam.create_imaging_service() self.request_focus_change = self.imaging.create_type("Move") self.request_focus_change.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken self.stop()
class MegapixelDomeCamera: def __init__(self, host, port=8999, user="******", password="******"): self.__camera = ONVIFCamera(host, port, user, password, "wsdl/") self.__mediaService = self.__camera.create_media_service() self.__ptzService = self.__camera.create_ptz_service() self.__mediaProfileToken = self.__mediaService.GetProfiles()[0].token self.__ptzNodeToken = self.__ptzService.GetNodes()[0].token def getSnapshot(self): response = self.__mediaService.GetSnapshotUri(self.__mediaProfileToken) return response.Uri def getRotationStatus(self): return self.__ptzService.GetStatus(self.__mediaProfileToken) # def move(self): # vector = 10 # speed = 5 # return self.__ptzService.RelativeMove(self.__mediaProfileToken, vector) def getPositionPresets(self): return self.__ptzService.GetPresets(self.__mediaProfileToken) def moveToPositionPreset(self, presetToken): p = self.__ptzService.create_type("GotoPreset") p.ProfileToken = self.__mediaProfileToken p.PresetToken = presetToken self.__ptzService.GotoPreset(p)
def continuous_move(): ip = '192.168.1.108' port = 80 user = '******' passwd = 'ufro_ufro_ufro' cam = ONVIFCamera(ip, port, user, passwd, '/home/victor/collarvacas/camara/python-onvif/wsdl') media = cam.create_media_service() ptz = cam.create_ptz_service() media_profile = media.GetProfiles()[0] # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) # Get range of pan and tilt # NOTE: X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Min return [ptz, request]
def __init__(self): self.current_image = None self.current_pos = 0 self.__file_folder = "test" self.__camera_position = [] self.__spots_list = [] self.__current_coordinate_list = None self.__svm_model = None self.__lr_model = None self.__usesvm = False self.__uselr = True pkl = open('LR.pkl', 'rb') self.thetaFinal = pickle.load(pkl) pkl.close() #initialize camera setting self.streamURL = "rtsp://bigbrother.winlab.rutgers.edu/stream1" self.mycam = ONVIFCamera('192.168.204.111', 80, 'admin', 'admin', 'C:/Users/basis_000/Anaconda2/wsdl/') self.pos = [{ '_x': -0.2, '_y': 0.5 }, { '_x': -0.03, '_y': 0.55 }, { '_x': 0.07, '_y': 0.6 }]
def connect(self, ip, port, username, password): global ptz, img # Connect to ONVIF camera logger.info('IP camera initialization...') if os.path.exists(SYSPATH): path = SYSPATH else: path = HOMEPATH mycam = ONVIFCamera(ip, port, username, password, path) host = mycam.devicemgmt.GetHostname() logger.info(' Connected to ONVIF camera ' + str(host.Name)) # Create media service object logger.info(' Creating media service...') media = mycam.create_media_service() logger.info(' Creating media service... Done.') # Get media profile (first element if we don't have multiple profiles) media_profiles = media.GetProfiles() media_profile_h264 = media_profiles[0] # media_profile_jpg = media_profiles[1] # Get video sources # video_source = media.GetVideoSources()[0] # We need the profile token token = media_profile_h264._token # PTZ # Create ptz service object logger.info(' Creating PTZ service...') ptz = mycam.create_ptz_service() logger.info(' Creating PTZ service... Done.') # Next we want to automatically define all functions, in requesting those from the ptz-service self.define_requests(token)
def __init__(self, ip, port, login, password): # Connecting to the camera self.my_cam = ONVIFCamera(ip, port, login, password) # Creating media service self.media_service = self.my_cam.create_media_service() # Getting profiles self.profiles = self.media_service.GetProfiles() self.media_profile = self.profiles[0] # Creating PTZ service self.ptz = self.my_cam.create_ptz_service() # Getting ptz move options self.request_absolute_move = self.ptz.create_type("AbsoluteMove") self.request_absolute_move.ProfileToken = self.media_profile._token self.request_continuous_move = self.ptz.create_type("ContinuousMove") self.request_continuous_move.ProfileToken = self.media_profile._token self.request_relative_move = self.ptz.create_type("RelativeMove") self.request_relative_move.ProfileToken = self.media_profile._token self.request_stop = self.ptz.create_type("Stop") self.request_stop.ProfileToken = self.media_profile._token # Creating imaging service self.imaging = self.my_cam.create_imaging_service() # Getting imaging move options self.request_focus_change = self.imaging.create_type("Move") self.request_focus_change.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken self.stop()
def __init__(self, ip, port, login, password, client_address): self.ip = ip self.port = port self.client_address = client_address try: self.mycam = ONVIFCamera(ip, int(port), login, password) except onvif.exceptions.ONVIFError as inst: self.mycam = None x = inst.args string = get_time( ) + f' Client {client_address} cannot connect to camera ({self.ip}, {self.port}) ' + str( x) print(string) add_in_log(string) else: self.media = self.mycam.create_media_service() self.media_profile = self.media.GetProfiles()[0] self.ptz = self.mycam.create_ptz_service() self.request = self.ptz.create_type('ContinuousMove') self.request.ProfileToken = self.media_profile.token self.request.Velocity = self.ptz.GetStatus({ 'ProfileToken': self.media_profile.token }).Position self.request_ = self.ptz.create_type('Stop') self.request_.ProfileToken = self.media_profile.token
def continuous_move(): global x1 global x2 global y2 global y1 mycam = ONVIFCamera('192.168.0.4', 5000, 'admin', '') # Create media service object media = mycam.create_media_service() # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] # print (media_profile) # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token while True: print 1 move_up(ptz=ptz, request=request) time.sleep(1) move_right(ptz=ptz, request=request) time.sleep(1) move_left(ptz=ptz, request=request) time.sleep(1) move_down(ptz=ptz, request=request) time.sleep(1)
def photo(): # Set up the camera object using the ONVIF port. mycam = ONVIFCamera( '192.168.1.108', 80, 'admin', '10iLtxyh', '/home/coovi/pCloudDrive/Projects/Jane/Amigos/III/amigos/amigos/onvif/wsdl' ) media = mycam.create_media_service() allProfiles = media.GetProfiles() mainProfile = media.GetProfile({'ProfileToken': allProfiles[0]._token}) snapshot = media.GetSnapshotUri({'ProfileToken': mainProfile._token}) # print (dir(media)) # snapShot_url = snapshot.Uri # url = snapshot.Uri #making the url downloadable # To get the current datetime use: dt = str(datetime.datetime.now()) username = '******' # The cameras user name password = '******' # the cameras password # bypass the username and password authentication response = requests.get(snapshot.Uri, auth=HTTPDigestAuth(username, password)) f = open('pic.jpg', 'wb') # opening newname = 'file_' + dt + '.jpg' # Write the file to the time stamp os.rename('pic.jpg', newname) f.write(response.content) f.close()
class PtzCam(): def __init__(self,host,port,user,password,wsdl): self.mycam = ONVIFCamera(host, port, user, password, wsdl) self.media = self.mycam.create_media_service() self.media_profile = self.media.GetProfiles()[0] self.ptz = self.mycam.create_ptz_service() self.requests = self.ptz.create_type('Stop') self.requests.ProfileToken = self.media_profile._token self.requestc = self.ptz.create_type('ContinuousMove') self.requestc.ProfileToken = self.media_profile._token self.requestg = self.ptz.create_type('GotoPreset') self.requestg.ProfileToken = self.media_profile._token self.stop() def stop(self): self.requests.PanTilt = True self.requests.Zoom = True self.ptz.Stop(self.requests) def get_presets(self): self.ptzPresetsList = self.ptz.GetPresets(self.requestc) return self.ptzPresetsList def goto_preset(self, preset_token): self.requestg.PresetToken = preset_token self.ptz.GotoPreset(self.requestg)
def __init__(self, hass, config): """Initialize an ONVIF camera.""" super().__init__() _LOGGER.debug("Importing dependencies") _LOGGER.debug("Setting up the ONVIF camera component") self._username = config.get(CONF_USERNAME) self._password = config.get(CONF_PASSWORD) self._host = config.get(CONF_HOST) self._port = config.get(CONF_PORT) self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._profile_index = config.get(CONF_PROFILE) self._ptz_service = None self._input = None _LOGGER.debug( "Setting up the ONVIF camera device @ '%s:%s'", self._host, self._port ) self._camera = ONVIFCamera( self._host, self._port, self._username, self._password, "{}/wsdl/".format(os.path.dirname(onvif.__file__)), )
def __init__(self, hass, config): """Initialize an ONVIF camera.""" super().__init__() _LOGGER.debug("Importing dependencies") _LOGGER.debug("Setting up the ONVIF camera component") self._username = config.get(CONF_USERNAME) self._password = config.get(CONF_PASSWORD) self._host = config.get(CONF_HOST) self._port = config.get(CONF_PORT) self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._profile_index = config.get(CONF_PROFILE) self._ptz_service = None self._input = None self._snapshot = None self.stream_options[CONF_RTSP_TRANSPORT] = config.get( CONF_RTSP_TRANSPORT) self._mac = None _LOGGER.debug("Setting up the ONVIF camera device @ '%s:%s'", self._host, self._port) session = async_get_clientsession(hass) transport = AsyncTransport(None, session=session) self._camera = ONVIFCamera( self._host, self._port, self._username, self._password, "{}/wsdl/".format(os.path.dirname(onvif.__file__)), transport=transport, )
def continuous_move(): mycam = ONVIFCamera('192.168.13.12', 80, 'admin', 'Supervisor') media = mycam.create_media_service() ptz = mycam.create_ptz_service() media_profile = media.GetProfiles()[0] request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) for i in range(1, 50): move(ptz, request, 0.01 * i, 0.01 * i, 0.1 * i / 20, 0.15) print i for i in range(1, 50): move(ptz, request, 0.50 - 0.01 * i, -(0.50 - 0.01 * i), 0.25 - 0.1 * i / 20, 0.15) print i for i in range(1, 50): move(ptz, request, -0.01 * i, -0.01 * i, 0.50 - 0.01 * i, 0.15) for i in range(1, 50): move(ptz, request, -(0.50 - 0.01 * i), 0.50 - 0.01 * i, 0.1 * i / 20, 0.15) print i stop(ptz, request)
def getPresets(): #mycam = ONVIFCamera('192.168.0.139',1018,'admin','8146dpr','/home/visionstudio/Desktop/wsdl') global mycam, media, ptz, media_profile, request, ptz_configuration_options mycam = ONVIFCamera(ip, port, user, password, wsdl_dir) media = mycam.create_media_service() media_profile = media.GetProfiles()[0] ptz = mycam.create_ptz_service() request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) #ver presets ptzPresetsList = ptz.GetPresets(request) print len(ptzPresetsList) for preset in ptzPresetsList: print preset._token if preset.Name == '': print '-' else: print preset.Name
def movimiento_continuo(): ip = '192.168.1.109' port = 80 user = '******' passwd = 'ufro_ufro_ufro' cam = ONVIFCamera(ip, port, user, passwd, '/home/victor/collarvacas/camara/python-onvif/wsdl') media = cam.create_media_service() ptz = cam.create_ptz_service() media_profile = media.GetProfiles()[0] # profile peticion = ptz.create_type('GetConfigurationOptions') peticion.ConfigurationToken = media_profile.PTZConfiguration._token ptz_config = ptz.GetConfigurationOptions(peticion) peticion = ptz.create_type('ContinuousMove') peticion.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) # rangos de la camara XMAX = ptz_config.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Max XMIN = ptz_config.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Min YMAX = ptz_config.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Max YMIN = ptz_config.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Min mov_arriba(ptz, YMAX, peticion, 1)
def continuous_move(): mycam = ONVIFCamera('10.11.12.175', 80, 'admin', 'admin') # Create media service object media = mycam.create_media_service() # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) # Get range of pan and tilt # NOTE: X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Min # Move up move_up(ptz, request)
def setup_move(): mycam = ONVIFCamera(IP, PORT, USER, PASS) # Create media service object media = mycam.create_media_service() # Create ptz service object global ptz ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration.token ptz_configuration_options = ptz.GetConfigurationOptions(request) global moverequest moverequest = ptz.create_type('ContinuousMove') moverequest.ProfileToken = media_profile.token if moverequest.Velocity is None: moverequest.Velocity = ptz.GetStatus({'ProfileToken': media_profile.token}).Position moverequest.Velocity.PanTilt.space = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].URI moverequest.Velocity.Zoom.space = ptz_configuration_options.Spaces.ContinuousZoomVelocitySpace[0].URI # Get range of pan and tilt # NOTE: X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Min move_left(ptz, moverequest) move_right(ptz, moverequest)
def get_presets(self): mycam = ONVIFCamera(IP, PORT, USER, PASS, '../wsdl/') # Create media service object media = mycam.create_media_service() print("setup_move {} {}", mycam, media) # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] profileToken = media_profile.token # Get presets print("Get Presets...") gp = ptz.create_type('GetPresets') gp.ProfileToken = profileToken self.presets = ptz.GetPresets(gp) for preset in self.presets: if (hasattr(preset, "Name")): name = preset.Name else: name = "" position = preset['PTZPosition'] print("preset {} => ({}, {}, {})".format(name, position.PanTilt.x, position.PanTilt.y, position.Zoom.x)) return self.presets
def __init__(self, addr, login, pwd, wsdl_path): common.check_addr(addr) logger.info(f'Initializing camera {addr}') self.cam = ONVIFCamera(addr[0], addr[1], login, pwd, wsdl_path) self.media = self.cam.create_media_service() self.ptz = self.cam.create_ptz_service() self.profile = self.media.GetProfiles()[0] self.request = {k: self.ptz.create_type(k) for k in ['ContinuousMove', 'GotoHomePosition', 'AbsoluteMove', 'RelativeMove']} for _, r in self.request.items(): r.ProfileToken = self.profile.token self.stop() self.config = self.__get_configurations() self.status = self.ptz.GetStatus({'ProfileToken': self.profile.token}) self.node = self.__get_node(self.config.NodeToken) self.request['ContinuousMove'].Velocity = self.status.Position for _, r in self.request.items(): r.ProfileToken = self.profile.token self.request_move_copy = deepcopy(self.request['ContinuousMove']) logging.info(f'Initialized camera at {addr} successfully')
def continuous_move(): mycam = ONVIFCamera('192.168.13.12', 80, 'admin', 'Supervisor') media = mycam.create_media_service() ptz = mycam.create_ptz_service() media_profile = media.GetProfiles()[0]
def continuous_move(): mycam = ONVIFCamera('192.168.15.42', 80, 'admin', 'Supervisor', 'C:\Users\komar\Documents\python-onvif-master\wsdl') # Create media service object media = mycam.create_media_service() # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0] print media_profile # Get PTZ configuration options for getting continuous move range of Pan and Tilt request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) # Get range of Pan and Tilt # X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[ 0].YRange.Min # Creating continuous move request with media_profile token request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token # Stops all other movement ptz.Stop({'ProfileToken': media_profile._token}) # custom move custom_move(ptz, request, -0.1, -0.2, -0.05, 2, 1, 0.5) sleep(3) # custom move custom_move(ptz, request, 0.1, 0.2, 0.05, 2, 3, 2) sleep(3) # move right move_right(ptz, request, 1) sleep(2) # move left move_left(ptz, request, 1) sleep(2) # Move up move_up(ptz, request, 1) sleep(2) # move down move_down(ptz, request, 1) sleep(2)
def __init__(self, ip, port, usr, pswd, wsdl_path): # Monkey coded to pass error self.cam = ONVIFCamera(ip, port, usr, pswd, wsdl_path) if debug_mode: self.print_trace("Camera information : " + str(self.cam.devicemgmt.GetDeviceInformation())) self.print_trace("Camera hostname :" + str(self.cam.devicemgmt.GetHostname().Name)) self.media_service = self.cam.create_media_service() self.media_profile = self.media_service.GetProfiles()[0] if debug_mode: self.print_trace("Media service profiles : " + str(self.media_service.GetProfiles())) self.ptz = self.cam.create_ptz_service() if debug_mode: req = self.ptz.create_type('GetServiceCapabilities') ser_cap = self.ptz.GetServiceCapabilities(req) self.print_trace("Service capabilities: " + str(ser_cap)) req = self.ptz.create_type('GetConfigurationOptions') req.ConfigurationToken = self.media_profile.PTZConfiguration.token ptz_opt = self.ptz.GetConfigurationOptions(req) self.print_trace("Configuration options : " + str(ptz_opt)) self.absolute_move = self.ptz.create_type('AbsoluteMove') self.absolute_move.ProfileToken = self.media_profile.token self.relative_move = self.ptz.create_type('RelativeMove') self.relative_move.ProfileToken = self.media_profile.token self.continous_move = self.ptz.create_type('ContinuousMove') self.continous_move.ProfileToken = self.media_profile.token self.req_stop = self.ptz.create_type('Stop') self.req_stop.ProfileToken = self.media_profile.token self.imaging = self.cam.create_imaging_service() if debug_mode: req = self.imaging.create_type('GetServiceCapabilities') ser_cap = self.ptz.GetServiceCapabilities(req) self.print_trace("Imaging service cap : " + str(ser_cap)) status = self.imaging.GetStatus({ 'VideoSourceToken': self.media_profile.VideoSourceConfiguration.SourceToken }) self.print_trace("Status" + str(status)) self.focus = self.imaging.create_type("Move") self.focus.VideoSourceToken = self.media_profile.VideoSourceConfiguration.SourceToken self.action_timeout = 3
def __init__(self, ip, port, user, passw): self.ip = ip self.port = port self.user = user self.passw = passw self.cam = ONVIFCamera(self.ip, self.port, self.user, self.passw) self.event_service = self.cam.create_events_service() self.media = self.cam.create_media_service()
def get_access_policy(camera): mycam = ONVIFCamera(camera['hostname'], camera['port'], camera['username'], camera['password']) # Get List of Services devicemgmt_service = mycam.create_devicemgmt_service() accesspolicy = devicemgmt_service.GetAccessPolicy() logging.debug("Services : {}".format(accesspolicy))
def __init__(self, address, user, password): self.dvrip = DVRIPCam(address, user, password) loginok = self.dvrip.login() if not loginok: raise ValueError('Login failed') self.onvif = ONVIFCamera(address, 8899, user, password, '../venv/lib/python3.7/site-packages/wsdl/') self.onvif_media = self.onvif.create_media_service()
def __init__(self, ip, port, username, password): self.ip = ip self.port = port self.username = username self.password = password if sys.platform == 'win32': wsdl_path = os.path.join(os.path.dirname(onvif.__file__), os.path.pardir, "wsdl") self.camera = ONVIFCamera(ip, port, username, password, wsdl_path) else: self.camera = ONVIFCamera(ip, port, username, password)
def __init__(self, hass, config): """Initialize an ONVIF camera.""" super().__init__() _LOGGER.debug("Importing dependencies") import onvif from onvif import ONVIFCamera _LOGGER.debug("Setting up the ONVIF camera component") self._username = config.get(CONF_USERNAME) self._password = config.get(CONF_PASSWORD) self._host = config.get(CONF_HOST) self._port = config.get(CONF_PORT) self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._profile_index = config.get(CONF_PROFILE) self._ptz_service = None self._input = None _LOGGER.debug("Setting up the ONVIF camera device @ '%s:%s'", self._host, self._port) self._camera = ONVIFCamera(self._host, self._port, self._username, self._password, '{}/wsdl/' .format(os.path.dirname(onvif.__file__)))
def setup(self, args): ''' `args`: Instance of `argparse.ArgumentParser` ''' # Create onvif camera client self.client = ONVIFCamera(args.host, args.port, args.user, args.password, args.wsdl, encrypt=args.encrypt) # Create cmd argument parser self.create_cmd_parser()
def __init__(self, hass, config): """Initialize a ONVIF camera.""" from onvif import ONVIFCamera, exceptions super().__init__() self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._input = None camera = None try: _LOGGER.debug("Connecting with ONVIF Camera: %s on port %s", config.get(CONF_HOST), config.get(CONF_PORT)) camera = ONVIFCamera( config.get(CONF_HOST), config.get(CONF_PORT), config.get(CONF_USERNAME), config.get(CONF_PASSWORD) ) media_service = camera.create_media_service() self._profiles = media_service.GetProfiles() self._profile_index = config.get(CONF_PROFILE) if self._profile_index >= len(self._profiles): _LOGGER.warning("ONVIF Camera '%s' doesn't provide profile %d." " Using the last profile.", self._name, self._profile_index) self._profile_index = -1 req = media_service.create_type('GetStreamUri') # pylint: disable=protected-access req.ProfileToken = self._profiles[self._profile_index]._token self._input = media_service.GetStreamUri(req).Uri.replace( 'rtsp://', 'rtsp://{}:{}@'.format( config.get(CONF_USERNAME), config.get(CONF_PASSWORD)), 1) _LOGGER.debug( "ONVIF Camera Using the following URL for %s: %s", self._name, self._input) except Exception as err: _LOGGER.error("Unable to communicate with ONVIF Camera: %s", err) raise try: self._ptz = camera.create_ptz_service() except exceptions.ONVIFError as err: self._ptz = None _LOGGER.warning("Unable to setup PTZ for ONVIF Camera: %s", err)
def connect(camera): # connects to camera after pressing the connect button import settings global token, ptz zeep.xsd.simple.AnySimpleType.pythonvalue = zeep_pythonvalue ip = settings.net + '.' + str(camera) cameraList = settings.cameras for i in range(len(cameraList)): if camera == cameraList[i]: index = i portList = settings.ports port = portList[index] login = '******' password = '******' cam = ONVIFCamera(ip, port, login, password) media = cam.create_media_service() profile = media.GetProfiles()[0] token = profile.token ptz = cam.create_ptz_service() print('connected')
def continuous_move(): mycam = ONVIFCamera('192.168.0.112', 80, 'admin', '12345') # Create media service object media = mycam.create_media_service() # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0]; # Get PTZ configuration options for getting continuous move range request = ptz.create_type('GetConfigurationOptions') request.ConfigurationToken = media_profile.PTZConfiguration._token ptz_configuration_options = ptz.GetConfigurationOptions(request) request = ptz.create_type('ContinuousMove') request.ProfileToken = media_profile._token ptz.Stop({'ProfileToken': media_profile._token}) # Get range of pan and tilt # NOTE: X and Y are velocity vector global XMAX, XMIN, YMAX, YMIN XMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Max XMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].XRange.Min YMAX = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Max YMIN = ptz_configuration_options.Spaces.ContinuousPanTiltVelocitySpace[0].YRange.Min # move right move_right(ptz, request) # move left move_left(ptz, request) # Move up move_up(ptz, request) # move down move_down(ptz, request)
def get_event_srv(): mycam = ONVIFCamera('192.168.1.10', 8899, 'admin', 'admin', wsdl_dir) #, no_cache=True) #print mycam.devicemgmt.GetServices() event_service = mycam.create_events_service() return event_service
def __init__(self, host, port ,user, passwd): ONVIFCamera.__init__(self, host, port, user, passwd) self.mediaService = self.create_media_service() self.deviceService = self.create_devicemgmt_service() self.capture = None
class ONVIFCLI(Cmd): prompt = 'ONVIF >>> ' client = None cmd_parser = None def setup(self, args): ''' `args`: Instance of `argparse.ArgumentParser` ''' # Create onvif camera client self.client = ONVIFCamera(args.host, args.port, args.user, args.password, args.wsdl, encrypt=args.encrypt) # Create cmd argument parser self.create_cmd_parser() def create_cmd_parser(self): # Create parser to parse CMD, `params` is optional. cmd_parser = ThrowingArgumentParser(prog='ONVIF CMD', usage='CMD service operation [params]') cmd_parser.add_argument('service') cmd_parser.add_argument('operation') cmd_parser.add_argument('params', default='{}', nargs=REMAINDER) self.cmd_parser = cmd_parser def do_cmd(self, line): '''Usage: CMD service operation [parameters]''' try: args = self.cmd_parser.parse_args(line.split()) except ValueError as err: return error(err) # Check if args.service is valid if args.service not in SUPPORTED_SERVICES: return error('No Service: ' + args.service) args.params = ''.join(args.params) # params is optional if not args.params.strip(): args.params = '{}' # params must be a dictionary format string match = re.match(r"^.*?(\{.*\}).*$", args.params) if not match: return error('Invalid params') try: args.params = dict(literal_eval(match.group(1))) except ValueError as err: return error('Invalid params') try: # Get ONVIF service service = self.client.get_service(args.service) # Actually execute the command and get the response response = getattr(service, args.operation)(args.params) except MethodNotFound as err: return error('No Operation: %s' % args.operation) except Exception as err: return error(err) if isinstance(response, (Text, bool)): return success(response) # Try to convert instance to dictionary try: success(ONVIFService.to_dict(response)) except ONVIFError: error({}) def complete_cmd(self, text, line, begidx, endidx): # TODO: complete service operations # service.ws_client.service._ServiceSelector__services[0].ports[0].methods.keys() if not text: completions = SUPPORTED_SERVICES[:] else: completions = [ key for key in SUPPORTED_SERVICES if key.startswith(text) ] return completions def emptyline(self): return '' def do_EOF(self, line): return True
def __init__(self): # reading config path = os.getcwd() + '/engine/utils/config.py' try: d = open(path, 'r') print('opening config successful') except IOError: print('error while opening config, loading default config') d = open(os.getcwd() + '/engine/utils/defaultConfig.py', 'r') dconfig = d.read() config = literal_eval(dconfig) # dont touch this zeep.xsd.simple.AnySimpleType.pythonvalue = self.zeep_pythonvalue # getting ip-port-log-pass-orientation-zoom from config ip = config.get('IP') port = config.get('port') login = config.get('login') password = config.get('password') self.UseRightThird = config.get('right') #zoom = config.get('zoom') """ if code above doesnt work this the hardcoded version ip = '192.168.11.43' port = 80 login = '******' password = '******' self.UseRightThird = False """ mycam = ONVIFCamera(ip, port, login, password) media = mycam.create_media_service() profiles = media.GetProfiles() createP = True profileNo = None for i in range(len(profiles)): profile = profiles[i] if profile.Name == 'trackingProfile': createP = False profileNo = i print('Profile already exists') if createP: print('Profile not found, creating new profile') media.CreateProfile('trackingProfile') self.profile = media.GetProfiles()[len(media.GetProfiles())-1] #adding video source configuration to the profile vidsrc = media.GetVideoSourceConfigurations()[0] addVidSrc = media.create_type('AddVideoSourceConfiguration') addVidSrc.ProfileToken = self.profile.token addVidSrc.ConfigurationToken = vidsrc.token media.AddVideoSourceConfiguration(addVidSrc) print('Video source config set') #adding video analytics configuration to the profile try: vidan = media.GetVideoAnalyticsConfigurations()[0] addVidAn = media.create_type('AddVideoAnalyticsConfiguration') addVidAn.ProfileToken = self.profile.token addVidAn.ConfigurationToken = vidan.token media.AddVideoAnalyticsConfiguration(addVidAn) print('Video analytics config set') except: print('Couldnt set video analytics') #adding PTZ configuration to the profile self.ptz = mycam.create_ptz_service() ptzc = self.ptz.GetConfigurations()[0] addPTZ = media.create_type('AddPTZConfiguration') addPTZ.ProfileToken = self.profile.token addPTZ.ConfigurationToken = ptzc.token media.AddPTZConfiguration(addPTZ) print('PTZ config set') #adding video encoder configuration to the profile vEncoderConfig = media.GetVideoEncoderConfigurations()[len(media.GetVideoEncoderConfigurations())-1] options = media.GetVideoEncoderConfigurationOptions() try: if options.JPEG: print('JPEG encoding exists') vEncoderConfig.Encoding = 'JPEG' opIndex = None for count in range(len(options.JPEG.ResolutionsAvailable)): if options.JPEG.ResolutionsAvailable[count].Width == 1280 and options.JPEG.ResolutionsAvailable[count].Height == 720: opIndex = count if opIndex == None: for count in range(len(options.JPEG.ResolutionsAvailable)): if options.JPEG.ResolutionsAvailable[count].Width > 700 and options.JPEG.ResolutionsAvailable[count].Width <1281: opIndex = count break if opIndex == None: opIndex = len(options.JPEG.ResolutionsAvailable)-1 vEncoderConfig.Resolution.Width = options.JPEG.ResolutionsAvailable[opIndex].Width vEncoderConfig.Resolution.Height = options.JPEG.ResolutionsAvailable[opIndex].Height print('Width = ', vEncoderConfig.Resolution.Width, '; Height = ', vEncoderConfig.Resolution.Height) vEncoderConfig.RateControl.FrameRateLimit = 4 vEncoderConfig.Quality = options.QualityRange.Max print('after quality setting') except: print('JPEG encoding doesnt exist') vEncoderConfig.Resolution.Width = 1280 vEncoderConfig.Resolution.Height = 720 vEncoderConfig.RateControl.FrameRateLimit = 4 vEncoderConfig.Quality = options.QualityRange.Max setVideoEncode = media.create_type('SetVideoEncoderConfiguration') print('type created') setVideoEncode.ForcePersistence = True setVideoEncode.Configuration = vEncoderConfig print('setvideoencode ready for setting') #media.SetVideoEncoderConfiguration(setVideoEncode) print('setvideoencoder success') addVideoEncode = media.create_type('AddVideoEncoderConfiguration') addVideoEncode.ProfileToken = self.profile.token addVideoEncode.ConfigurationToken = vEncoderConfig.token # not setting the video encoder because of broken onvif python3 implementation #media.AddVideoEncoderConfiguration(addVideoEncode) print('Video encoder set') else: self.profile = media.GetProfiles()[profileNo] print('Profile selected') print(self.profile.Name) # get height - width of the frame to use in move module self.width = self.profile.VideoEncoderConfiguration.Resolution.Width print('Got width = ', self.width) self.height = self.profile.VideoEncoderConfiguration.Resolution.Height print('Codec = ', self.profile.VideoEncoderConfiguration.Encoding) print('FPS = ', self.profile.VideoEncoderConfiguration.RateControl.FrameRateLimit) self.token = self.profile.token self.ptz = mycam.create_ptz_service() # getting current absolute pantilt coordinates #currentStatus = self.ptz.GetStatus(self.token) #absX = currentStatus.Position.PanTilt.x #absY = currentStatus.Position.PanTilt.y # setting the specified zoom #zoomRequest = {'Position': {'Zoom': {'space': '', 'x': zoom}, 'PanTilt': {'space': '', 'y': absY, 'x': absX}}, 'ProfileToken': self.token} #self.ptz.AbsoluteMove(zoomRequest) # gets url in a struct streamURIStruct = media.GetStreamUri({'StreamSetup': {'Stream': 'RTP-Unicast', 'Transport': 'UDP'}, 'ProfileToken': self.token}) # the url itself self.streamURL = 'rtsp://' + ip + ':554' + '/Streaming/Channels/2' print(self.streamURL)
class onvif_host: ''' onvif device class info ''' def __init__(self, ip, port, username, password): self.ip = ip self.port = port self.username = username self.password = password if sys.platform == 'win32': wsdl_path = os.path.join(os.path.dirname(onvif.__file__), os.path.pardir, "wsdl") self.camera = ONVIFCamera(ip, port, username, password, wsdl_path) else: self.camera = ONVIFCamera(ip, port, username, password) def __check_user_exist__(self, username, users = None): user_lists = self.camera.devicemgmt.GetUsers() if users is None: users = dict() users.clear() user_name_lists = list() for user_item in user_lists: user_name_lists.append(user_item.Username) if not users.has_key(user_item.Username) and user_item.Username == username: if hasattr(user_item, 'Username'): users['Username'] = user_item.Username if hasattr(user_item, 'Password'): users['Password'] = user_item.Password if hasattr(user_item, 'UserLevel'): users['UserLevel'] = user_item.UserLevel if username not in user_name_lists: return False else: return True def get_stream_url(self, out_data=None): media_capability_name ='Meda' media_info = self.camera.devicemgmt.GetCapabilities({'Categroy':media_capability_name}) if out_data is None: out_data = list() if media_info.Media.StreamingCapabilities.RTP_RTSP_TCP or media_info.Media.StreamingCapabilities.RTP_TCP: media_service = self.camera.create_media_service() profiles = media_service.GetProfiles() url_nodes = ET.Element('stream_url_lists') for item in profiles: stream = {'StreamSetup':{'StreamType':'RTP_unicast','Transport':'RTSP'}, 'ProfileToken':item._token} stream_url = media_service.GetStreamUri(stream) url_node = ET.SubElement(url_nodes,'stream_url') url_node.text = stream_url.Uri if type(out_data) == list: out_data.append(ET.tostring(url_nodes)) elif type(out_data) == str: out_data.join(ET.tostring(url_nodes)) def get_device_status(self, out_data, out_data_type): """get device current status""" return 0 def add_user(self, out_data, username, password, level=None): """add a user to device""" logger.debug(locals()) if level is None: level = 'Operator' user = {'User':{'Username':username, 'Password':password, 'UserLevel':level}} user_lists_node = ET.Element('user_lists') user_content = ET.SubElement(user_lists_node, 'user') user_content.set('name', username) if self.__check_user_exist__(username): user_content.text = 'False' user_content.set('error_message', 'user exist') else: try: out_response = self.camera.devicemgmt.CreateUsers(user) user_content.text = 'True' except: user_content.text = 'False' out_data.append(ET.tostring(user_lists_node)) def del_user(self, out_data, username): """ delete a device user.""" logger.debug(locals()) user = {'Username':username} user_lists_node = ET.Element('user_lists') user_content = ET.SubElement(user_lists_node, 'user') user_content.set('name', username) if self.__check_user_exist__(username): out_response = self.camera.devicemgmt.DeleteUsers(user) user_content.text = 'True' else: user_content.text = 'False' user_content.set('error_message', 'user not exist') if type(out_data) == types.ListType: out_data.append(ET.tostring(user_lists_node)) def alter_user(self, out_data, username, level, password=None): """alter device user info""" logger.debug(locals()) users = dict() user_lists_node = ET.Element('user_lists') user_content = ET.SubElement(user_lists_node, 'user') user_content.set('name', username) if self.__check_user_exist__(username, users): if password is None: user = {'User':{'Username':username, 'UserLevel':level}} self.camera.devicemgmt.SetUser(user) else: user = {'User':{'Username':username, 'UserLevel':level, 'Password':password}} self.camera.devicemgmt.SetUser(user) user_content.text = 'True' else: logger.warning("user %s not exitst", username) user_content.text = 'False' out_data.append(ET.tostring(user_lists_node)) def reboot_device(self, out_data): """device reboot""" logger.debug(locals()) response = self.camera.devicemgmt.SystemReboot() logger.debug(response)
from __future__ import absolute_import, division, print_function, unicode_literals import sys from time import sleep from onvif import ONVIFCamera if __name__ == "__main__" : if len( sys.argv) < 8 : print( "USAGE: python3 {} [ip] [port] [user] [wsdl dir] [x] [y] [sec] [pass (optional)]".format( sys.argv[0])) sys.exit( 1) mycam = ONVIFCamera( sys.argv[1], int( sys.argv[2]), sys.argv[3], None if len( sys.argv) == 8 else sys.argv[8], wsdl_dir = sys.argv[4] ) vel_x = float( sys.argv[5]) vel_y = float( sys.argv[6]) seconds = float( sys.argv[7]) # Create ptz service. ptz_svc = mycam.create_ptz_service() # Get ptz configuration. # mycam.ptz.GetConfigurations() # Another way ptz_conf = ptz_svc.GetConfigurations() print( 'conf num :{:2d}.'.format( len( ptz_conf)))
# -*- coding: utf-8 -*- """ Created on Sat Oct 24 14:49:21 2015 @author: Lily """ from onvif import ONVIFCamera #import time mycam = ONVIFCamera('10.2.1.49', 80, 'admin', '12345', 'C:\onvif\wsdl\\') #mycam = ONVIFCamera('10.2.1.49', 80, 'admin', '12345', 'C:\onvif\wsdl\\') # Create media service object media = mycam.create_media_service() # Create ptz service object ptz = mycam.create_ptz_service() # Get target profile media_profile = media.GetProfiles()[0]; #media = mycam.create_media_service() #device = mycam.create_devicemgmt_service() # Get target profile #print mycam.devicemgmt.GetServices({'IncludeCapability': False }) #print media.GetStreamUri()
# -*- coding: utf-8 -*- """ Created on Mon Jan 18 20:34:19 2016 @author: Lily """ from onvif import ONVIFCamera #mycam = ONVIFCamera('10.9.6.49', 80, 'admin', '12345', 'C:\onvif\wsdl\\') mycam = ONVIFCamera('10.2.1.49', 80, 'admin', '12345', 'C:\onvif\wsdl\\') # Create media service object media_service = mycam.create_media_service() profiles = media_service.GetProfiles() token = profiles[0]._token # Get all video encoder configurations configurations_list = media_service.GetVideoEncoderConfigurations() # Use the first profile and Profiles have at least one video_encoder_configuration = configurations_list[0] # Get video encoder configuration options options = media_service.GetVideoEncoderConfigurationOptions({'ProfileToken':token}) # Setup stream configuration video_encoder_configuration.Encoding = 'H264'
class ONVIFHassCamera(Camera): """An implementation of an ONVIF camera.""" def __init__(self, hass, config): """Initialize an ONVIF camera.""" super().__init__() _LOGGER.debug("Importing dependencies") import onvif from onvif import ONVIFCamera _LOGGER.debug("Setting up the ONVIF camera component") self._username = config.get(CONF_USERNAME) self._password = config.get(CONF_PASSWORD) self._host = config.get(CONF_HOST) self._port = config.get(CONF_PORT) self._name = config.get(CONF_NAME) self._ffmpeg_arguments = config.get(CONF_EXTRA_ARGUMENTS) self._profile_index = config.get(CONF_PROFILE) self._ptz_service = None self._input = None _LOGGER.debug("Setting up the ONVIF camera device @ '%s:%s'", self._host, self._port) self._camera = ONVIFCamera(self._host, self._port, self._username, self._password, '{}/wsdl/' .format(os.path.dirname(onvif.__file__))) async def async_initialize(self): """ Initialize the camera. Initializes the camera by obtaining the input uri and connecting to the camera. Also retrieves the ONVIF profiles. """ from aiohttp.client_exceptions import ClientConnectorError from homeassistant.exceptions import PlatformNotReady from zeep.exceptions import Fault import homeassistant.util.dt as dt_util try: _LOGGER.debug("Updating service addresses") await self._camera.update_xaddrs() _LOGGER.debug("Setting up the ONVIF device management service") devicemgmt = self._camera.create_devicemgmt_service() _LOGGER.debug("Retrieving current camera date/time") system_date = dt_util.utcnow() device_time = await devicemgmt.GetSystemDateAndTime() if device_time: cdate = device_time.UTCDateTime cam_date = dt.datetime(cdate.Date.Year, cdate.Date.Month, cdate.Date.Day, cdate.Time.Hour, cdate.Time.Minute, cdate.Time.Second, 0, dt_util.UTC) _LOGGER.debug("Camera date/time: %s", cam_date) _LOGGER.debug("System date/time: %s", system_date) dt_diff = cam_date - system_date dt_diff_seconds = dt_diff.total_seconds() if dt_diff_seconds > 5: _LOGGER.warning("The date/time on the camera is '%s', " "which is different from the system '%s', " "this could lead to authentication issues", cam_date, system_date) _LOGGER.debug("Obtaining input uri") await self.async_obtain_input_uri() _LOGGER.debug("Setting up the ONVIF PTZ service") if self._camera.get_service('ptz', create=False) is None: _LOGGER.warning("PTZ is not available on this camera") else: self._ptz_service = self._camera.create_ptz_service() _LOGGER.debug("Completed set up of the ONVIF camera component") except ClientConnectorError as err: _LOGGER.warning("Couldn't connect to camera '%s', but will " "retry later. Error: %s", self._name, err) raise PlatformNotReady except Fault as err: _LOGGER.error("Couldn't connect to camera '%s', please verify " "that the credentials are correct. Error: %s", self._name, err) return async def async_obtain_input_uri(self): """Set the input uri for the camera.""" from onvif import exceptions _LOGGER.debug("Connecting with ONVIF Camera: %s on port %s", self._host, self._port) try: _LOGGER.debug("Retrieving profiles") media_service = self._camera.create_media_service() profiles = await media_service.GetProfiles() _LOGGER.debug("Retrieved '%d' profiles", len(profiles)) if self._profile_index >= len(profiles): _LOGGER.warning("ONVIF Camera '%s' doesn't provide profile %d." " Using the last profile.", self._name, self._profile_index) self._profile_index = -1 _LOGGER.debug("Using profile index '%d'", self._profile_index) _LOGGER.debug("Retrieving stream uri") req = media_service.create_type('GetStreamUri') req.ProfileToken = profiles[self._profile_index].token req.StreamSetup = {'Stream': 'RTP-Unicast', 'Transport': {'Protocol': 'RTSP'}} stream_uri = await media_service.GetStreamUri(req) uri_no_auth = stream_uri.Uri uri_for_log = uri_no_auth.replace( 'rtsp://', 'rtsp://<user>:<password>@', 1) self._input = uri_no_auth.replace( 'rtsp://', 'rtsp://{}:{}@'.format(self._username, self._password), 1) _LOGGER.debug( "ONVIF Camera Using the following URL for %s: %s", self._name, uri_for_log) except exceptions.ONVIFError as err: _LOGGER.error("Couldn't setup camera '%s'. Error: %s", self._name, err) return async def async_perform_ptz(self, pan, tilt, zoom): """Perform a PTZ action on the camera.""" from onvif import exceptions if self._ptz_service is None: _LOGGER.warning("PTZ actions are not supported on camera '%s'", self._name) return if self._ptz_service: pan_val = 1 if pan == DIR_RIGHT else -1 if pan == DIR_LEFT else 0 tilt_val = 1 if tilt == DIR_UP else -1 if tilt == DIR_DOWN else 0 zoom_val = 1 if zoom == ZOOM_IN else -1 if zoom == ZOOM_OUT else 0 req = {"Velocity": { "PanTilt": {"_x": pan_val, "_y": tilt_val}, "Zoom": {"_x": zoom_val}}} try: _LOGGER.debug( "Calling PTZ | Pan = %d | Tilt = %d | Zoom = %d", pan_val, tilt_val, zoom_val) await self._ptz_service.ContinuousMove(req) except exceptions.ONVIFError as err: if "Bad Request" in err.reason: self._ptz_service = None _LOGGER.debug("Camera '%s' doesn't support PTZ.", self._name) else: _LOGGER.debug("Camera '%s' doesn't support PTZ.", self._name) async def async_added_to_hass(self): """Handle entity addition to hass.""" _LOGGER.debug("Camera '%s' added to hass", self._name) if ONVIF_DATA not in self.hass.data: self.hass.data[ONVIF_DATA] = {} self.hass.data[ONVIF_DATA][ENTITIES] = [] self.hass.data[ONVIF_DATA][ENTITIES].append(self) async def async_camera_image(self): """Return a still image response from the camera.""" from haffmpeg.tools import ImageFrame, IMAGE_JPEG _LOGGER.debug("Retrieving image from camera '%s'", self._name) ffmpeg = ImageFrame( self.hass.data[DATA_FFMPEG].binary, loop=self.hass.loop) image = await asyncio.shield(ffmpeg.get_image( self._input, output_format=IMAGE_JPEG, extra_cmd=self._ffmpeg_arguments), loop=self.hass.loop) return image async def handle_async_mjpeg_stream(self, request): """Generate an HTTP MJPEG stream from the camera.""" from haffmpeg.camera import CameraMjpeg _LOGGER.debug("Handling mjpeg stream from camera '%s'", self._name) ffmpeg_manager = self.hass.data[DATA_FFMPEG] stream = CameraMjpeg(ffmpeg_manager.binary, loop=self.hass.loop) await stream.open_camera( self._input, extra_cmd=self._ffmpeg_arguments) try: stream_reader = await stream.get_reader() return await async_aiohttp_proxy_stream( self.hass, request, stream_reader, ffmpeg_manager.ffmpeg_stream_content_type) finally: await stream.close() @property def supported_features(self): """Return supported features.""" if self._input: return SUPPORT_STREAM return 0 @property def stream_source(self): """Return the stream source.""" return self._input @property def name(self): """Return the name of this camera.""" return self._name
# -*- coding: utf-8 -*- from onvif import ONVIFCamera __author__ = 'vahid' if __name__ == '__main__': mycam = ONVIFCamera('192.168.1.10', 8899, 'admin', 'admin') #, no_cache=True) event_service = mycam.create_events_service() print(event_service.GetEventProperties()) pullpoint = mycam.create_pullpoint_service() req = pullpoint.create_type('PullMessages') req.MessageLimit=100 print(pullpoint.PullMessages(req))