Discover Raumfeld devices in the network

    :param timeout: The timeout in seconds
    :param retries: How often the search should be retried
    :returns:       A list of raumfeld devices, sorted by name
190178
def discover(timeout=1, retries=1):
    
    locations = []

    group = ('239.255.255.250', 1900)
    service = 'ssdp:urn:schemas-upnp-org:device:MediaRenderer:1'  # 'ssdp:all'
    message = '\r\n'.join(['M-SEARCH * HTTP/1.1',
                           'HOST: {group[0]}:{group[1]}',
                           'MAN: "ssdp:discover"',
                           'ST: {st}',
                           'MX: 1', '', '']).format(group=group, st=service)

    socket.setdefaulttimeout(timeout)
    for _ in range(retries):
        sock = socket.socket(socket.AF_INET,
                             socket.SOCK_DGRAM,
                             socket.IPPROTO_UDP)
        # socket options
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 2)

        # send group multicast
        sock.sendto(message.encode('utf-8'), group)

        while True:
            try:
                response = sock.recv(2048).decode('utf-8')
                for line in response.split('\r\n'):
                    if line.startswith('Location: '):
                        location = line.split(' ')[1].strip()
                        if not location in locations:
                            locations.append(location)
            except socket.timeout:
                break
    devices = [RaumfeldDevice(location) for location in locations]

    # only return 'Virtual Media Player' and sort the list
    return sorted([device for device in devices
                   if device.model_description == 'Virtual Media Player'],
                  key=lambda device: device.friendly_name)
597359
def get_changed_devices(self, timestamp):
        
        if timestamp is None:
            payload = {}
        else:
            payload = {
                'timeout': SUBSCRIPTION_WAIT,
                'minimumdelay': SUBSCRIPTION_MIN_WAIT
            }
            payload.update(timestamp)
        # double the timeout here so requests doesn't timeout before vera
        payload.update({
            'id': 'lu_sdata',
        })

        logger.debug("get_changed_devices() requesting payload %s", str(payload))
        r = self.data_request(payload, TIMEOUT*2)
        r.raise_for_status()

        # If the Vera disconnects before writing a full response (as lu_sdata
        # will do when interrupted by a Luup reload), the requests module will
        # happily return 200 with an empty string. So, test for empty response,
        # so we don't rely on the JSON parser to throw an exception.
        if r.text == "":
            raise PyveraError("Empty response from Vera")

        # Catch a wide swath of what the JSON parser might throw, within
        # reason. Unfortunately, some parsers don't specifically return
        # json.decode.JSONDecodeError, but so far most seem to derive what
        # they do throw from ValueError, so that's helpful.
        try:
            result = r.json()
        except ValueError as ex:
            raise PyveraError("JSON decode error: " + str(ex))

        if not ( type(result) is dict
                 and 'loadtime' in result and 'dataversion' in result ):
            raise PyveraError("Unexpected/garbled response from Vera")

        # At this point, all good. Update timestamp and return change data.
        device_data = result.get('devices')
        timestamp = {
            'loadtime': result.get('loadtime'),
            'dataversion': result.get('dataversion')
        }
        return [device_data, timestamp]
130853
def discover(timeout=DISCOVERY_TIMEOUT):
    
    hosts = {}
    payload = MAGIC + DISCOVERY
    for _ in range(RETRIES):
        _SOCKET.sendto(bytearray(payload), ('255.255.255.255', PORT))
        start = time.time()
        while time.time() < start + timeout:
            for host, data in _BUFFER.copy().items():
                if not _is_discovery_response(data):
                    continue
                if host not in hosts:
                    _LOGGER.debug("Discovered device at %s", host)
                    entry = {}
                    entry['mac'] = data[7:13]
                    entry['imac'] = data[19:25]
                    entry['next'] = 0
                    entry['st'] = int(data[-1])
                    entry['time'] = _device_time(data[37:41])
                    entry['serverTime'] = int(time.time())
                    hosts[host] = entry
    return hosts
972517
def maintainConnections(self, force=False):
        
        now = time.perf_counter()
        if now < self.nextCheck and not force:
            return False
        self.nextCheck = now + (self.config.RETRY_TIMEOUT_NOT_RESTRICTED
                                if self.isKeySharing
                                else self.config.RETRY_TIMEOUT_RESTRICTED)
        missing = self.connectToMissing()
        self.retryDisconnected(exclude=missing)
        logger.trace("{} next check for retries in {:.2f} seconds"
                     .format(self, self.nextCheck - now))
        return True
530073
def get(self, relpath=None, params=None):
    
    for retry in xrange(self.retries + 1):
      if retry:
        time.sleep(self.retry_sleep)
      try:
        return self.invoke("GET", relpath, params)
      except (socket.error, urllib2.URLError) as e:
        if "timed out" in str(e).lower():
          log_message = "Timeout issuing GET request for %s." \
              % (self._join_uri(relpath), )
          if retry < self.retries:
            log_message += " Will retry."
          else:
            log_message += " No retries left."
          LOG.warn(log_message, exc_info=True)
        else:
          raise
    else:
      raise e
709198
def _can_retry(self, batch, error):
        
        return (batch.attempts < self.config['retries']
                and getattr(error, 'retriable', False))
975412
def list_ptr_records(self, device):
        
        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        try:
            resp, resp_body = self._retry_get(uri)
        except exc.NotFound:
            return []
        records = [CloudDNSPTRRecord(rec, device)
                for rec in resp_body.get("records", [])]
        return records
557984
def retry(
        transport: 'UDPTransport',
        messagedata: bytes,
        message_id: UDPMessageID,
        recipient: Address,
        stop_event: Event,
        timeout_backoff: Iterable[int],
) -> bool:
    

    async_result = transport.maybe_sendraw_with_result(
        recipient,
        messagedata,
        message_id,
    )

    event_quit = event_first_of(
        async_result,
        stop_event,
    )

    for timeout in timeout_backoff:

        if event_quit.wait(timeout=timeout) is True:
            break

        log.debug(
            'retrying message',
            node=pex(transport.raiden.address),
            recipient=pex(recipient),
            msgid=message_id,
        )

        transport.maybe_sendraw_with_result(
            recipient,
            messagedata,
            message_id,
        )

    return async_result.ready()
675914
def ListClients(self, request, timeout=None):
    
    return self._RetryLoop(
        lambda t: self._stub.ListClients(request, timeout=t))
137729
def get_devices(self, refresh=False, generic_type=None):
        """"""
        _LOGGER.info("Updating all devices...")
        if refresh or self._devices is None:
            if self._devices is None:
                self._devices = {}

            responseObject = self.get_sensors()
            if (responseObject and
                    not isinstance(responseObject, (tuple, list))):
                responseObject = responseObject

            for deviceJson in responseObject:
                # Attempt to reuse an existing device
                device = self._devices.get(deviceJson['name'])

                # No existing device, create a new one
                if device:
                    device.update(deviceJson)
                else:
                    device = newDevice(deviceJson, self)

                    if not device:
                        _LOGGER.info('Device is unknown')
                        continue

                    self._devices[device.device_id] = device

            # We will be treating the Lupusec panel itself as an armable device.
            panelJson = self.get_panel()
            _LOGGER.debug("Get the panel in get_devices: %s", panelJson)

            self._panel.update(panelJson)

            alarmDevice = self._devices.get('0')

            if alarmDevice:
                alarmDevice.update(panelJson)
            else:
                alarmDevice = ALARM.create_alarm(panelJson, self)
                self._devices['0'] = alarmDevice

            # Now we will handle the power switches
            switches = self.get_power_switches()
            _LOGGER.debug(
                'Get active the power switches in get_devices: %s', switches)

            for deviceJson in switches:
                # Attempt to reuse an existing device
                device = self._devices.get(deviceJson['name'])

                # No existing device, create a new one
                if device:
                    device.update(deviceJson)
                else:
                    device = newDevice(deviceJson, self)
                    if not device:
                        _LOGGER.info('Device is unknown')
                        continue
                    self._devices[device.device_id] = device

        if generic_type:
            devices = []
            for device in self._devices.values():
                if (device.type is not None and
                        device.type in generic_type[0]):
                    devices.append(device)
            return devices

        return list(self._devices.values())
611148
def view_rest_retry(self, url=None):
        
        if url is None:
            url = "https://"
        return vars(self._session.get_adapter(url).max_retries)
1254657
def retry_on_excs(excs, retry_count=3, delay=5):
    

    def wrapper(f):
        @functools.wraps(f)
        def deco(*args, **kwargs):
            for i in range(0, retry_count):
                try:
                    return f(*args, **kwargs)
                except excs:
                    if logger:
                        logger.warning(
                            'HTTPError caught.Retrying ...'.format(f.__name__),
                            exc_info=True
                        )
                    time.sleep(delay)
            else:
                logger.error(
                    '{} failed after {} retries'.format(
                        f.__name__, retry_count)
                )
            return f(*args, **kwargs)

        return deco

    return wrapper
359142
def get_devices(self) -> list:
        """"""

        if not self.enabled:
            return None

        self.in_process = True

        response, _ = helpers.call_api(
            '/cloud/v1/deviceManaged/devices',
            'post',
            headers=helpers.req_headers(self),
            json=helpers.req_body(self, 'devicelist')
        )

        if response and helpers.check_response(response, 'get_devices'):
            if 'result' in response and 'list' in response['result']:
                device_list = response['result']['list']
                outlets, switches, fans = self.process_devices(device_list)
            else:
                logger.error('Device list in response not found')
        else:
            logger.error('Error retrieving device list')

        self.in_process = False

        return (outlets, switches, fans)
863867
private long getWaitUntilMillis(int retryAfterSeconds) {
    double multiplier = waitTimeNoiseFactor.get().nextDouble();
    multiplier =
        multiplier * (MAX_WAIT_TIME_MULTIPLIER - MIN_WAIT_TIME_MULTIPLIER)
            + MIN_WAIT_TIME_MULTIPLIER;
    double result = SECONDS.toMillis(retryAfterSeconds) * multiplier;
    return (long) result;
  }
1200503
def discover(self, seconds=2):
        
        log.info("Discovering devices")
        with gevent.Timeout(seconds, StopBroadcasting) as timeout:
            try:
                try:
                    while True:
                        self.upnp.broadcast()
                        gevent.sleep(1)
                except Exception as e:
                    raise StopBroadcasting(e)
            except StopBroadcasting:
                return
140682
def _get_timeout(self, timeout):
        '''
        
        '''
        if timeout is None:
            return self.opts['timeout']
        if isinstance(timeout, int):
            return timeout
        if isinstance(timeout, six.string_types):
            try:
                return int(timeout)
            except ValueError:
                return self.opts['timeout']
        # Looks like the timeout is invalid, use config
        return self.opts['timeout']
919723
def _new_session(retry_timeout_config):
        
        retry = requests.packages.urllib3.Retry(
            total=None,
            connect=retry_timeout_config.connect_retries,
            read=retry_timeout_config.read_retries,
            method_whitelist=retry_timeout_config.method_whitelist,
            redirect=retry_timeout_config.max_redirects)
        session = requests.Session()
        session.mount('https://',
                      requests.adapters.HTTPAdapter(max_retries=retry))
        session.mount('http://',
                      requests.adapters.HTTPAdapter(max_retries=retry))
        return session