示例#1
0
def discovery():
    cameras = []

    wsd = WSDiscovery()
    wsd.start()
    ret = wsd.searchServices()

    for index, service in enumerate(ret):
        address = service.getXAddrs()[0]

        if 'onvif' not in address:
            continue

        res = re.findall(r'[0-9.]+|(?<=:)\d+', address)
        cam = {
            'ip': res[0],
            'port': int(res[1]) if len(res) > 1 else 80,
            'online': True
        }

        #Exclude devices on local Server Network
        if (cam['ip'] != '10.0.3.229' and cam['ip'] != '192.168.13.247'):
            cameras.append(cam)

    wsd.stop()
    cameras.sort(key=lambda x: x['ip'])
    return cameras
def test_probing(monkeypatch, probe_response):
    "mock up socket registration, event selection & socket message response"

    sck = None

    def mock_register(selector, rsock, evtmask):
        """get hold of the multicast socket that will send the Probe message,
        when the socket is registered with the selector"""
        global sck
        # The Probe is sent multicast, we use that to identify the right socket.
        # Identification could be done better, but this is enough for now.
        if rsock.getsockname()[1] == MULTICAST_PORT:
            sck = rsock

    def mock_select(*args):
        "set a mock Probe response event in motion for the same socket"
        global sck
        if sck and sck.getsockname()[1] == MULTICAST_PORT:
            key = selectors.SelectorKey(sck.makefile(), sck.fileno(), [], "")
            # to mock just one response we just nullify the sock
            sck = None
            return [(key, selectors.EVENT_READ)]
        else:
            return []

    def mock_recvfrom(*args):
        return probe_response

    monkeypatch.setattr(selectors.DefaultSelector, "register", mock_register)
    monkeypatch.setattr(selectors.DefaultSelector, "select", mock_select)
    monkeypatch.setattr(socket.socket, "recvfrom", mock_recvfrom)

    # we cannot use a fixture that'd start discovery for us, since the socket
    # selector registration happens at startup time
    wsd = WSDiscovery()
    wsd.start()
    found = wsd.searchServices()

    assert len(found) == 1
    assert probe_response[1] in found[0].getXAddrs()[0]
    assert len(found[0].getScopes()) == 4
示例#3
0
   def discover(self, attempts=3):
      "Use WS DIscovery to try & find available camera(s) a number of times"

      wsd = WSDiscovery()
      wsd.start()

      attempts_left = attempts
      found = None

      while not found and attempts_left:

         found = wsd.searchServices()
         for service in found:
            url = urlparse(service.getXAddrs()[0])
            if "onvif" not in url.path:
               logger.warning("not an Onvif service path: %s", url.path)
            else:
               found = url
               logger.info(f"discovered onvif service at {found.netloc}{found.path}")
               break

         attempts_left -= 1

      return (found.hostname, found.port or 80, found.path) if found else None
def Discovery_original():
    global IPList
    global IPL
    del IPList[:]
    wsd = WSDiscovery()
    wsd.start()

    ret = wsd.searchServices()

    stroka = ''

    for service in ret:
        addrs = service.getXAddrs()[0]
        x = addrs.find('/')
        ip = addrs[x + 1:]
        x = addrs.find('/')
        y = addrs.rfind(':')
        if y <= x:
            y = addrs[x + 2:].find('/')
            ip = addrs[x + 2:x + 2 + y]
            port = '80'
        else:
            ip = addrs[x + 2:y]
            x = addrs[y:].find('/')
            port = addrs[y + 1:y + x]
        if ip[9] == '1':
            print(ip + '      ' + port)
            #   try:
            SMT = SetIPL(ip, port)
            if SMT.Ptz == 'error':
                print('error')
            else:
                IPList.append(SMT)
                print('ip=' + ip + '     port=' + port)


#except:
#   print ('something happend')
            IPList.sort(key=lambda x: x.IP)
    for i, IPL in enumerate(IPList):
        stroka = stroka + IPL.IP + ',' + IPL.Port + ',' + str(i) + ','
    wsd.stop()

    f = open('discovery.txt', 'w')
    f.write(stroka)
    f.close()
    return ('ODiscovery_ready')
示例#5
0
 def discovery(self, timeout=3):
     '''以 WS-Discovery 方式探索 IP Cam
     傳入:
         timeout : int -- 等待逾時時間, 單位秒, 預設 5 秒
     傳回:
         list(str) -- 搜尋到的 IP Cam 的 ONVIF 服務網址清單
     '''
     svcs = []
     try:
         wsd = WSDiscovery()
         wsd.start()
         services = wsd.searchServices(types=[ONVIF_TYPE_NVT],
                                       timeout=timeout)
     except Exception as ex:
         self.log.error(f'WS-Discovery Error:{ex}')
         return svcs
     else:
         for service in services:
             url = service.getXAddrs()[0]
             if not list(filter(lambda s: s == url, svcs)):
                 svcs.append(url)
         return svcs
     finally:
         wsd.stop()
def wsd():
    "provide the discovery client"
    client = WSDiscovery()
    client.start()
    yield client
    client.stop()
示例#7
0
from wsdiscovery import WSDiscovery
from onvif import ONVIFCamera, ONVIFError
import urllib.parse

"""
pip install --upgrade onvif_zeep

"""

try_auth = [
    ('admin', 'admin'),
    ('test', 'test'),
]

wsd = WSDiscovery()
wsd.start()

seen_services = []

services = wsd.searchServices()
for service in services:
    print(service.getEPR() + ":" + service.getXAddrs()[0])
    if service.getXAddrs()[0] in seen_services:
        continue
        
    seen_services.append(service.getXAddrs()[0])
    parsed = urllib.parse.urlparse(service.getXAddrs()[0])
    parts =  parsed.netloc.split(':')
    ip = parts[0]
    if len(parts) > 1:
        port = parts[1]
示例#8
0
def probe_match():
    wsd = WSDiscovery()
    wsd.start()
    ret = wsd.searchServices()
    wsd.stop()