Example #1
0
    def get_definition(self, name, portType=None):
        """Returns xaddr and wsdl of specified service"""
        # Check if the service is supported
        if name not in SERVICES:
            raise ONVIFError('Unknown service %s' % name)
        wsdl_file = SERVICES[name]['wsdl']
        ns = SERVICES[name]['ns']

        binding_name = '{%s}%s' % (ns, SERVICES[name]['binding'])

        if portType:
            ns += '/' + portType

        wsdlpath = os.path.join(self.wsdl_dir, wsdl_file)
        if not os.path.isfile(wsdlpath):
            raise ONVIFError('No such file: %s' % wsdlpath)

        # XAddr for devicemgmt is fixed:
        if name == 'devicemgmt':
            xaddr = '%s:%s/onvif/device_service' % \
                    (self.host if (self.host.startswith('http://') or self.host.startswith('https://'))
                     else 'http://%s' % self.host, self.port)
            return xaddr, wsdlpath, binding_name

        # Get other XAddr
        xaddr = self.xaddrs.get(ns)
        if not xaddr:
            raise ONVIFError("Device doesn't support service: %s" % name)

        return xaddr, wsdlpath, binding_name
Example #2
0
    def __init__(self,
                 xaddr,
                 user,
                 passwd,
                 url,
                 cache_location='/tmp/suds',
                 cache_duration=None,
                 encrypt=True,
                 daemon=False,
                 ws_client=None,
                 no_cache=False,
                 portType=None,
                 dt_diff=None):

        if not os.path.isfile(url):
            raise ONVIFError('%s doesn`t exist!' % url)

        if no_cache:
            cache = NoCache()
        else:
            # Create cache object
            # NOTE: if cache_location is specified,
            # onvif must has the permission to access it.
            cache = ObjectCache(location=cache_location)
            # cache_duration: cache will expire in `cache_duration` days
            if cache_duration is not None:
                cache.setduration(days=cache_duration)

        # Convert pathname to url
        self.url = urlparse.urljoin('file:', urllib.pathname2url(url))
        self.xaddr = xaddr
        # Create soap client
        if not ws_client:
            self.ws_client = Client(
                url=self.url,
                location=self.xaddr,
                cache=cache,
                port=portType,
                headers={'Content-Type': 'application/soap+xml'})
        else:
            self.ws_client = ws_client
            self.ws_client.set_options(location=self.xaddr)

        # Set soap header for authentication
        self.user = user
        self.passwd = passwd
        # Indicate wether password digest is needed
        self.encrypt = encrypt

        self.daemon = daemon

        self.dt_diff = dt_diff

        if self.user is not None and self.passwd is not None:
            self.set_wsse()

        # Method to create type instance of service method defined in WSDL
        self.create_type = self.ws_client.factory.create
Example #3
0
def get_onvifCamera_client(username: str, password: str):
    """ get the onvif.client.ONVIFCamera"""
    try:
        camera = ONVIFCamera('172.16.18.162', 80, username, password)
    except Exception as e:
        # logger_file.error(f"Getting camera object ...Failed")
        # logger.error(f'Getting camera object ...Failed')
        raise ONVIFError(e)

    return camera
Example #4
0
    def get_definition(self, name):
        '''Returns xaddr and wsdl of specified service'''
        # Check if the service is supported
        if name not in SERVICES:
            raise ONVIFError('Unknown service %s' % name)
        wsdl_file = SERVICES[name]['wsdl']
        ns = SERVICES[name]['ns']

        wsdlpath = os.path.join(self.wsdl_dir, wsdl_file)
        if not os.path.isfile(wsdlpath):
            raise ONVIFError('No such file: %s' % wsdlpath)

        # XAddr for devicemgmt is fixed:
        if name == 'devicemgmt':
            xaddr = 'http://%s:%s/onvif/device_service' % (self.host, self.port)
            return xaddr, wsdlpath

        # Get other XAddr
        xaddr = self.xaddrs.get(ns)
        if not xaddr:
            raise ONVIFError('Device doesn`t support service: %s' % name)

        return xaddr, wsdlpath
Example #5
0
    def __init__(self,
                 xaddr,
                 user,
                 passwd,
                 url,
                 encrypt=True,
                 daemon=False,
                 zeep_client=None,
                 no_cache=False,
                 portType=None,
                 dt_diff=None,
                 binding_name='',
                 transport=None):
        if not os.path.isfile(url):
            raise ONVIFError('%s doesn`t exist!' % url)

        self.url = url
        self.xaddr = xaddr
        wsse = UsernameDigestTokenDtDiff(user,
                                         passwd,
                                         dt_diff=dt_diff,
                                         use_digest=encrypt)
        # Create soap client
        if not zeep_client:
            #print(self.url, self.xaddr)
            ClientType = Client if no_cache else CachingClient
            settings = Settings()
            settings.strict = False
            settings.xml_huge_tree = True
            self.zeep_client = ClientType(wsdl=url,
                                          wsse=wsse,
                                          transport=transport,
                                          settings=settings)
        else:
            self.zeep_client = zeep_client
        self.ws_client = self.zeep_client.create_service(
            binding_name, self.xaddr)

        # Set soap header for authentication
        self.user = user
        self.passwd = passwd
        # Indicate wether password digest is needed
        self.encrypt = encrypt
        self.daemon = daemon
        self.dt_diff = dt_diff
        self.create_type = lambda x: self.zeep_client.get_element('ns0:' + x)()
Example #6
0
    def __init__(self,
                 xaddr,
                 user,
                 passwd,
                 url,
                 cache_location=None,
                 cache_duration=None,
                 encrypt=True,
                 daemon=False,
                 ws_client=None):

        if not os.path.isfile(url):
            raise ONVIFError('%s doesn`t exist!' % url)

        # Convert pathname to url
        self.url = urlparse.urljoin('file:', urllib.pathname2url(url))
        self.xaddr = xaddr
        # Create soap client
        if not ws_client:
            self.ws_client = Client(url=self.url, location=self.xaddr)
        else:
            self.ws_client = ws_client
            self.ws_client.set_options(location=self.xaddr)

        # Set cache duration and location
        if cache_duration is not None:
            self.ws_client.options.cache.setduration(days=cache_duration)
        if cache_location is not None:
            self.ws_client.options.cache.setlocation(cache_location)

        # Set soap header for authentication
        self.user = user
        self.passwd = passwd
        # Indicate wether password digest is needed
        self.encrypt = encrypt

        self.daemon = daemon

        self.set_wsse()

        # Method to create type instance of service method defined in WSDL
        self.create_type = self.ws_client.factory.create
Example #7
0
async def test_flow_import_onvif_api_error(hass):
    """Test that config flow fails when ONVIF API fails."""
    with patch("homeassistant.components.onvif.config_flow.get_device"
               ) as mock_onvif_camera:
        setup_mock_onvif_camera(mock_onvif_camera)
        mock_onvif_camera.create_devicemgmt_service = MagicMock(
            side_effect=ONVIFError("Could not get device mgmt service"))

        result = await hass.config_entries.flow.async_init(
            config_flow.DOMAIN,
            context={"source": config_entries.SOURCE_IMPORT},
            data={
                config_flow.CONF_NAME: NAME,
                config_flow.CONF_HOST: HOST,
                config_flow.CONF_PORT: PORT,
                config_flow.CONF_USERNAME: USERNAME,
                config_flow.CONF_PASSWORD: PASSWORD,
            },
        )

        assert result["type"] == data_entry_flow.RESULT_TYPE_ABORT
        assert result["reason"] == "onvif_error"
Example #8
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception as err:
         raise ONVIFError(err)
Example #9
0
 def wrapped(*args, **kwargs):
     try:
         return func(*args, **kwargs)
     except Exception as err:
         #print('Ouuups: err =', err, ', func =', func, ', args =', args, ', kwargs =', kwargs)
         raise ONVIFError(err)