Python homeassistant.helpers.config_validation.port() Examples

The following are 17 code examples of homeassistant.helpers.config_validation.port(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module homeassistant.helpers.config_validation , or try the search function .
Example #1
Source File: light.py    From hass-dmx with MIT License 6 votes vote down vote up
def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    host = config.get(CONF_HOST)
    universe = config.get(CONF_UNIVERSE)
    port = config.get(CONF_PORT)
    send_levels_on_startup = config.get(CONF_SEND_LEVELS_ON_STARTUP)

    # Send the specified default level to pre-fill the channels with
    overall_default_level = config.get(CONF_DEFAULT_LEVEL)
    default_light_type = config.get(CONF_DEFAULT_TYPE)

    dmx_gateway = DMXGateway(host, universe, port, overall_default_level,
                             config[CONF_DMX_CHANNELS])

    lights = (DMXLight(light, dmx_gateway, send_levels_on_startup, default_light_type) for light in
              config[CONF_DEVICES])
    async_add_devices(lights)

    return True 
Example #2
Source File: sensor.py    From sensor.plex_recently_added with Apache License 2.0 6 votes vote down vote up
def image_url(self, cert_check, img, resolution=200):
    """Plex can resize images with a long & partially % encoded url."""
    from urllib.parse import quote
    ssl, host, local, port, token, self_cert, dl_images = self.url_elements
    if not cert_check and not self_cert:
        ssl = ''
    if dl_images:
        host = local
    encoded = quote('http{0}://{1}:{2}{3}?X-Plex-Token={4}'.format(ssl,
                                                                   local,
                                                                   port,
                                                                   img,
                                                                   token),
                    safe='')
    url = ('http{0}://{1}:{2}/photo/:/transcode?width={5}&height={5}'
           '&minSize=1&url={3}&X-Plex-Token={4}').format(ssl, host, port,
                                                         encoded, token,
                                                         resolution)
    return url 
Example #3
Source File: __init__.py    From PyLoxone with Apache License 2.0 6 votes vote down vote up
def getJson (self):
        url_version = "http://{}:{}/jdev/cfg/version".format(self.host, self.port)
        version_resp = await requests.get(url_version,
                                          auth=HTTPBasicAuth(self.lox_user, self.lox_pass),
                                          verify=False, timeout=TIMEOUT)

        if version_resp.status_code == 200:
            vjson = version_resp.json()
            if 'LL' in vjson:
                if 'Code' in vjson['LL'] and 'value' in vjson['LL']:
                    self.version = [int(x) for x in vjson['LL']['value'].split(".")]

        url = "http://" + str(self.host) + ":" + str(self.port) + self.loxapppath
        my_response = await requests.get(url, auth=HTTPBasicAuth(self.lox_user, self.lox_pass),
                                         verify=False, timeout=TIMEOUT)
        if my_response.status_code == 200:
            self.json = my_response.json()
            if self.version is not None:
                self.json['softwareVersion'] = self.version
        else:
            self.json = None
        self.responsecode = my_response.status_code
        return self.responsecode 
Example #4
Source File: xboxone.py    From hassio-addons with MIT License 5 votes vote down vote up
def setup_platform(hass, config, add_devices, discovery_info=None):
    """Set up the Xbox One platform."""
    name = config.get(CONF_NAME)
    ssl = config.get(CONF_SSL)
    host = config.get(CONF_HOST)
    port = config.get(CONF_PORT)
    liveid = config.get(CONF_DEVICE)
    ip = config.get(CONF_IP_ADDRESS)
    auth = config.get(CONF_AUTHENTICATION)

    proto = 'https' if ssl else 'http'
    base_url = '{0}://{1}:{2}'.format(proto, host, port)

    add_devices([XboxOneDevice(base_url, liveid, ip, name, auth)]) 
Example #5
Source File: climate.py    From Heatmiser-for-home-assistant with GNU General Public License v2.0 5 votes vote down vote up
def setup_platform(hass, config, add_devices, discovery_info=None):
    """ Sets up a Heatmiser Neo-Hub And Returns Neostats"""
    host = config.get(CONF_HOST, None)
    port = config.get(CONF_PORT, 4242)

    thermostats = []

    NeoHubJson = HeatmiserNeostat(TEMP_CELSIUS, False, host, port).json_request({"INFO": 0})

    _LOGGER.debug(NeoHubJson)

    for device in NeoHubJson['devices']:
        if device['DEVICE_TYPE'] != 6:
            name = device['device']
            tmptempfmt = device['TEMPERATURE_FORMAT']
            if (tmptempfmt == False) or (tmptempfmt.upper() == "C"):
                temperature_unit = TEMP_CELSIUS
            else:
                temperature_unit = TEMP_FAHRENHEIT
            away = device['AWAY']
            current_temperature = device['CURRENT_TEMPERATURE']
            set_temperature = device['CURRENT_SET_TEMPERATURE']

            _LOGGER.info("Thermostat Name: %s " % name)
            _LOGGER.info("Thermostat Away Mode: %s " % away)
            _LOGGER.info("Thermostat Current Temp: %s " % current_temperature)
            _LOGGER.info("Thermostat Set Temp: %s " % set_temperature)
            _LOGGER.info("Thermostat Unit Of Measurement: %s " % temperature_unit)

            if (('TIMECLOCK' in device['STAT_MODE']) and (ExcludeTimeClock == True)):
              _LOGGER.debug("Found a Neostat configured in timer mode named: %s skipping" % device['device'])
            else:
              thermostats.append(HeatmiserNeostat(temperature_unit, away, host, port, name))

        elif device['DEVICE_TYPE'] == 6:
            _LOGGER.debug("Found a Neoplug named: %s skipping" % device['device'])

    _LOGGER.info("Adding Thermostats: %s " % thermostats)
    add_devices(thermostats) 
Example #6
Source File: climate.py    From Heatmiser-for-home-assistant with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, unit_of_measurement, away, host, port, name="Null"):
        self._name = name
        self._unit_of_measurement = unit_of_measurement
        self._away = away
        self._host = host
        self._port = port
        #self._type = type Neostat vs Neostat-e
        self._hvac_action = None
        self._hvac_mode = None
        self._hvac_modes = hvac_modes
        self._support_flags = SUPPORT_FLAGS
        self._support_flags = self._support_flags | SUPPORT_TARGET_TEMPERATURE
        self.update() 
Example #7
Source File: light.py    From hass-dmx with MIT License 5 votes vote down vote up
def __init__(self, host, universe, port, default_level,
                 number_of_channels):
        """
        Initialise a bank of channels, with a default value.
        """

        self._host = host
        self._universe = universe
        self._port = port
        self._number_of_channels = number_of_channels
        self._default_level = default_level

        # Number of channels must be even
        if number_of_channels % 2 != 0:
            self._number_of_channels += 1

        # Initialise the DMX channel array with the default values
        self._channels = [self._default_level] * self._number_of_channels

        # Initialise socket
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)  # UDP

        packet = bytearray()
        packet.extend(map(ord, "Art-Net"))
        packet.append(0x00)  # Null terminate Art-Net
        packet.extend([0x00, 0x50])  # Opcode ArtDMX 0x5000 (Little endian)
        packet.extend([0x00, 0x0e])  # Protocol version 14
        packet.extend([0x00, 0x00])  # Sequence, Physical
        packet.extend([self._universe, 0x00])  # Universe
        packet.extend(pack('>h', self._number_of_channels))
        self._base_packet = packet 
Example #8
Source File: sensor.py    From sensor.plex_recently_added with Apache License 2.0 5 votes vote down vote up
def __init__(self, hass, conf, name):
        from pytz import timezone
        self._name = name
        self.conf_dir = str(hass.config.path()) + '/'
        self._dir = conf.get(CONF_IMG_CACHE)
        if self._name:
            self._dir = self._dir + self._name.replace(' ', '_') + '/'
        self.img = '{0}{1}{2}{3}{4}.jpg'.format(
            self.conf_dir, {}, self._dir, {}, {})
        self.img_url = '{0}{1}{2}{3}.jpg'.format({}, self._dir, {}, {})
        self._tz = timezone(str(hass.config.time_zone))
        self.cert = conf.get(CONF_SSL_CERT)
        self.ssl = 's' if conf.get(CONF_SSL) or self.cert else ''
        self.token = conf.get(CONF_TOKEN)
        self.server_name = conf.get(CONF_SERVER)
        self.max_items = int(conf.get(CONF_MAX))
        self.dl_images = conf.get(CONF_DL_IMAGES)
        self.on_deck = conf.get(CONF_ON_DECK)
        self.sections = conf.get(CONF_SECTION_TYPES)
        self.excludes = conf.get(CONF_EXCLUDE_KEYWORDS)
        self.resolution = conf.get(CONF_RESOLUTION)
        if self.server_name:
            _LOGGER.warning(
                "Plex Recently Added: The server_name option has been removed. Use host and port options instead.")
            return
        else:
            self.server_ip = conf.get(CONF_HOST)
            self.local_ip = conf.get(CONF_HOST)
            self.port = conf.get(CONF_PORT)
        self.url_elements = [self.ssl, self.server_ip, self.local_ip,
                             self.port, self.token, self.cert, self.dl_images]
        self.change_detected = False
        self._state = None
        self.card_json = []
        self.api_json = []
        self.data = [{1}] 
Example #9
Source File: sensor.py    From sensor.plex_recently_added with Apache License 2.0 5 votes vote down vote up
def state(self):
        if self.server_name:
            return "server_name is no longer an option, use host and port."
        return self._state 
Example #10
Source File: notify.py    From HomeAssistantConfig with MIT License 5 votes vote down vote up
def __init__(self, server, port, timeout, sender, encryption, username,
                 password, recipients, sender_name, debug):
        """Initialize the SMTP service."""
        self._server = server
        self._port = port
        self._timeout = timeout
        self._sender = sender
        self.encryption = encryption
        self.username = username
        self.password = password
        self.recipients = recipients
        self._sender_name = sender_name
        self.debug = debug
        self.tries = 2 
Example #11
Source File: __init__.py    From PyLoxone with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        self.host = None
        self.port = None
        self.loxapppath = "/data/LoxAPP3.json"

        self.lox_user = None
        self.lox_pass = None
        self.json = None
        self.responsecode = None
        self.version = None 
Example #12
Source File: udp.py    From mysmarthome with MIT License 4 votes vote down vote up
def update(self):
        """Get the latest value for this sensor."""
        with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
            sock.settimeout(self._config[CONF_TIMEOUT])
            try:
                sock.connect(
                    (self._config[CONF_HOST], self._config[CONF_PORT]))
            except socket.error as err:
                _LOGGER.error(
                    "Unable to connect to %s on port %s: %s",
                    self._config[CONF_HOST], self._config[CONF_PORT], err)
                return

            try:
                sock.send(self._config[CONF_PAYLOAD].encode())
            except socket.error as err:
                _LOGGER.error(
                    "Unable to send payload %r to %s on port %s: %s",
                    self._config[CONF_PAYLOAD], self._config[CONF_HOST],
                    self._config[CONF_PORT], err)
                return

            readable, _, _ = select.select(
                [sock], [], [], self._config[CONF_TIMEOUT])
            if not readable:
                _LOGGER.warning(
                    "Timeout (%s second(s)) waiting for a response after "
                    "sending %r to %s on port %s.",
                    self._config[CONF_TIMEOUT], self._config[CONF_PAYLOAD],
                    self._config[CONF_HOST], self._config[CONF_PORT])
                return

            value = sock.recv(self._config[CONF_BUFFER_SIZE]).decode()

        if self._config[CONF_VALUE_TEMPLATE] is not None:
            try:
                self._state = self._config[CONF_VALUE_TEMPLATE].render(
                    value=value)
                return
            except TemplateError:
                _LOGGER.error(
                    "Unable to render template of %r with value: %r",
                    self._config[CONF_VALUE_TEMPLATE], value)
                return

        self._state = value 
Example #13
Source File: __init__.py    From PyLoxone with Apache License 2.0 4 votes vote down vote up
def __init__(self, user=None,
                 password=None,
                 host="http://192.168.1.225 ",
                 port="8080", token_persist_filename=None,
                 loxconfig=None):
        self._username = user
        self._pasword = password
        self._host = host
        self._port = port
        self._token_refresh_count = TOKEN_REFRESH_RETRY_COUNT
        self._token_persist_filename = token_persist_filename
        self._loxconfig = loxconfig
        self._version = 0
        if self._loxconfig is not None:
            if 'softwareVersion' in self._loxconfig:
                vers = self._loxconfig['softwareVersion']
                if isinstance(vers, list) and len(vers) >= 2:
                    try:
                        self._version = float("{}.{}".format(vers[0], vers[1]))
                    except ValueError:
                        self._version = 0

        if self._token_persist_filename is None:
            self._token_persist_filename = DEFAULT_TOKEN_PERSIST_NAME

        self._iv = gen_init_vec()
        self._key = gen_key()
        self._token = LxToken()
        self._token_valid_until = 0
        self._salt = ""
        self._salt_uesed_count = 0
        self._salt_time_stamp = 0
        self._public_key = None
        self._rsa_cipher = None
        self._session_key = None
        self._ws = None
        self._current_message_typ = None
        self._encryption_ready = False
        self._visual_hash = None
        self._keep_alive_task = None

        self.message_call_back = None
        self._pending = []

        self.connect_retries = 10
        self.connect_delay = 30
        self.state = "CLOSED"
        self._secured_queue = queue.Queue(maxsize=1) 
Example #14
Source File: image_processing.py    From HASS-Deepstack-object with MIT License 4 votes vote down vote up
def __init__(
        self,
        ip_address,
        port,
        api_key,
        timeout,
        targets,
        confidence,
        roi_y_min,
        roi_x_min,
        roi_y_max,
        roi_x_max,
        show_boxes,
        save_file_folder,
        save_timestamped_file,
        camera_entity,
        name=None,
    ):
        """Init with the API key and model id."""
        super().__init__()
        self._dsobject = ds.DeepstackObject(ip_address, port, api_key, timeout)
        self._targets = targets
        self._confidence = confidence
        self._camera = camera_entity
        if name:
            self._name = name
        else:
            camera_name = split_entity_id(camera_entity)[1]
            self._name = "deepstack_object_{}".format(camera_name)

        self._state = None
        self._objects = []  # The parsed raw data
        self._targets_found = []
        self._summary = {}

        self._roi_dict = {
            "y_min": roi_y_min,
            "x_min": roi_x_min,
            "y_max": roi_y_max,
            "x_max": roi_x_max,
        }

        self._show_boxes = show_boxes
        self._last_detection = None
        self._image_width = None
        self._image_height = None
        self._save_file_folder = save_file_folder
        self._save_timestamped_file = save_timestamped_file 
Example #15
Source File: __init__.py    From HomeAssistant-CustomComponents with Apache License 2.0 4 votes vote down vote up
def async_setup(hass, config):
    """Initialize of Mikrotik component."""
    conf = config[DOMAIN]
    host = conf.get(CONF_HOST)
    username = conf.get(CONF_USERNAME)
    password = conf.get(CONF_PASSWORD, "")
    port = conf.get(CONF_PORT, DEFAUL_PORT)

    _LOGGER.info("Setup")

    @asyncio.coroutine
    def run_script(call):
        """Run script service."""
        req_script = call.data.get(CONF_NAME)

        _LOGGER.debug("Sending request to run '%s' script",
                      req_script)
        try:
            client = librouteros.connect(
                host,
                username,
                password,
                port=port
            )

            try:
                scripts = client(cmd='/system/script/print')

                for script in scripts:
                    try:
                        _LOGGER.debug("Script found: %s, id: %s, invalid: %s",
                                      script.get('name'),
                                      script.get('.id'),
                                      script.get('invalid'))

                        if req_script == script.get('name') and \
                                not script.get('invalid'):
                            _LOGGER.info("Running script id: %s",
                                         script.get('.id'))

                            params = {'.id': script.get('.id')}
                            run = client(cmd='/system/script/run', **params)

                    except Exception as e:
                        _LOGGER.error("Run script error: %s", str(e))

            except (librouteros.exceptions.TrapError,
                    librouteros.exceptions.MultiTrapError,
                    librouteros.exceptions.ConnectionError):
                _LOGGER.error("Command error")

        except (librouteros.exceptions.TrapError,
                librouteros.exceptions.MultiTrapError,
                librouteros.exceptions.ConnectionError) as api_error:
            _LOGGER.error("Connection error: %s", api_error)

    hass.services.async_register(
        DOMAIN, SERVICE_COMMAND_NAME, run_script,
        schema=SERVICE_SCHEMA)

    return True 
Example #16
Source File: __init__.py    From home-assistant-remote with Apache License 2.0 4 votes vote down vote up
def __init__(self, hass, conf):
        """Initialize the connection."""
        self._hass = hass
        self._host = conf.get(CONF_HOST)
        self._port = conf.get(CONF_PORT)
        self._secure = conf.get(CONF_SECURE)
        self._verify_ssl = conf.get(CONF_VERIFY_SSL)
        self._access_token = conf.get(CONF_ACCESS_TOKEN)
        self._password = conf.get(CONF_API_PASSWORD)

        # see homeassistant/components/influxdb/__init__.py
        # for include/exclude logic
        include = conf.get(CONF_INCLUDE, {})
        exclude = conf.get(CONF_EXCLUDE, {})
        self._whitelist_e = set(include.get(CONF_ENTITIES, []))
        self._whitelist_d = set(include.get(CONF_DOMAINS, []))
        self._blacklist_e = set(exclude.get(CONF_ENTITIES, []))
        self._blacklist_d = set(exclude.get(CONF_DOMAINS, []))

        self._filter = [
            {
                CONF_ENTITY_ID: re.compile(fnmatch.translate(f.get(CONF_ENTITY_ID))) if f.get(CONF_ENTITY_ID) else None,
                CONF_UNIT_OF_MEASUREMENT: f.get(CONF_UNIT_OF_MEASUREMENT),
                CONF_ABOVE: f.get(CONF_ABOVE),
                CONF_BELOW: f.get(CONF_BELOW)
            }
            for f in conf.get(CONF_FILTER, [])
        ]

        self._subscribe_events = conf.get(CONF_SUBSCRIBE_EVENTS)
        self._entity_prefix = conf.get(CONF_ENTITY_PREFIX)

        self._connection_state_entity = 'sensor.'

        if self._entity_prefix != '':
            self._connection_state_entity = '{}{}'.format(self._connection_state_entity, self._entity_prefix)

        self._connection_state_entity = '{}remote_connection_{}_{}'.format(self._connection_state_entity, self._host.replace('.', '_').replace('-', '_'), self._port)

        self._connection = None
        self._entities = set()
        self._handlers = {}
        self._remove_listener = None

        self._instance_attrs = {
            'host': self._host,
            'port': self._port,
            'secure': self._secure,
            'verify_ssl': self._verify_ssl,
            'entity_prefix': self._entity_prefix
        }

        self._entities.add(self._connection_state_entity)
        self._hass.states.async_set(self._connection_state_entity, STATE_CONNECTING, self._instance_attrs)

        self.__id = 1 
Example #17
Source File: __init__.py    From HomeAssistant_Components with Apache License 2.0 4 votes vote down vote up
def setup(hass, yaml_config):
    """Activate the emulated_hue component."""
    timezone = yaml_config.get("homeassistant").get("time_zone")
    config = Config(hass, yaml_config.get(DOMAIN, {}), timezone)

    app = web.Application()
    app['hass'] = hass
    handler = None
    server = None

    DescriptionXmlView(config).register(app, app.router)
    HueDingDongConfigView(config).register(app, app.router)
    HueUsernameView().register(app, app.router)
    HueAllLightsStateView(config).register(app, app.router)
    HueOneLightStateView(config).register(app, app.router)
    HueOneLightChangeView(config).register(app, app.router)

    upnp_listener = UPNPResponderThread(
        config.host_ip_addr, config.listen_port,
        config.upnp_bind_multicast, config.advertise_ip,
        config.advertise_port)

    async def stop_emulated_hue_bridge(event):
        """Stop the emulated hue bridge."""
        upnp_listener.stop()
        if server:
            server.close()
            await server.wait_closed()
        await app.shutdown()
        if handler:
            await handler.shutdown(10)
        await app.cleanup()

    async def start_emulated_hue_bridge(event):
        """Start the emulated hue bridge."""
        upnp_listener.start()
        nonlocal handler
        nonlocal server

        handler = app.make_handler(loop=hass.loop)

        try:
            server = await hass.loop.create_server(
                handler, config.host_ip_addr, config.listen_port)
        except OSError as error:
            _LOGGER.error("Failed to create HTTP server at port %d: %s",
                          config.listen_port, error)
        else:
            hass.bus.async_listen_once(
                EVENT_HOMEASSISTANT_STOP, stop_emulated_hue_bridge)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_emulated_hue_bridge)

    return True