Exemplo n.º 1
0
def setUpModule():  # pylint: disable=invalid-name
    """ Initalizes a Home Assistant server and Slave instance. """
    global hass, slave, master_api, broken_api

    hass = ha.HomeAssistant()

    hass.bus.listen('test_event', lambda _: _)
    hass.states.set('test.test', 'a_state')

    http.setup(
        hass, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: 8122
            }
        })

    hass.start()

    master_api = remote.API("127.0.0.1", API_PASSWORD, 8122)

    # Start slave
    slave = remote.HomeAssistant(master_api)

    slave.start()

    # Setup API pointing at nothing
    broken_api = remote.API("127.0.0.1", "", 8125)
Exemplo n.º 2
0
    def test_home_assistant_init(self):
        """ Test HomeAssistant init. """
        # Wrong password
        self.assertRaises(ha.HomeAssistantError, remote.HomeAssistant,
                          remote.API('127.0.0.1', API_PASSWORD + 'A', 8124))

        # Wrong port
        self.assertRaises(ha.HomeAssistantError, remote.HomeAssistant,
                          remote.API('127.0.0.1', API_PASSWORD, 8125))
Exemplo n.º 3
0
    def __init__(self, ha_ip, ha_passw, tg_token):
        self.alive = True
        self.bot = telegram.Bot(token=tg_token)
        self.api = remote.API(ha_ip, ha_passw)

        try:
            remote.validate_api(self.api)
            self.bot.getMe()
        except:
            self.teardown()

        try:
            self.last_update_id = self.bot.getUpdates()[-1].update_id
        except IndexError:
            self.last_update_id = None
        #except telegram.TelegramError:
        #self.last_update_id = None
        self.sensors = self.get_homeassistant_sensors()

        # access control
        self.trusted_users = []
        self.admins = []
        self.token = ''.join(
            random.choice(string.ascii_lowercase + string.ascii_uppercase +
                          string.digits) for x in range(10))
Exemplo n.º 4
0
    def test_validate_api(self):
        """ Test Python API validate_api. """
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(
            remote.APIStatus.INVALID_PASSWORD,
            remote.validate_api(remote.API("127.0.0.1", API_PASSWORD + "A")))
Exemplo n.º 5
0
    def post(self, request):
        """Setup an event forwarder."""
        try:
            data = yield from request.json()
        except ValueError:
            return self.json_message("No data received.", HTTP_BAD_REQUEST)

        try:
            host = data['host']
            api_password = data['api_password']
        except KeyError:
            return self.json_message("No host or api_password received.",
                                     HTTP_BAD_REQUEST)

        try:
            port = int(data['port']) if 'port' in data else None
        except ValueError:
            return self.json_message("Invalid value received for port.",
                                     HTTP_UNPROCESSABLE_ENTITY)

        api = rem.API(host, api_password, port)

        valid = yield from self.hass.loop.run_in_executor(
            None, api.validate_api)
        if not valid:
            return self.json_message("Unable to validate API.",
                                     HTTP_UNPROCESSABLE_ENTITY)

        if self.event_forwarder is None:
            self.event_forwarder = rem.EventForwarder(self.hass)

        self.event_forwarder.async_connect(api)

        return self.json_message("Event forwarding setup.")
Exemplo n.º 6
0
def setUpModule():  # pylint: disable=invalid-name
    """ Initalizes a Home Assistant server and Slave instance. """
    global hass, slave, master_api

    hass = get_test_home_assistant()

    hass.bus.listen('test_event', lambda _: _)
    hass.states.set('test.test', 'a_state')

    bootstrap.setup_component(
        hass, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: MASTER_PORT
            }
        })

    bootstrap.setup_component(hass, 'api')

    hass.start()

    master_api = remote.API("127.0.0.1", API_PASSWORD, MASTER_PORT)

    # Start slave
    slave = remote.HomeAssistant(master_api)
    bootstrap.setup_component(
        slave, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: SLAVE_PORT
            }
        })

    slave.start()
Exemplo n.º 7
0
def _handle_post_api_event_forward(handler, path_match, data):
    """Handle adding an event forwarding target."""
    try:
        host = data['host']
        api_password = data['api_password']
    except KeyError:
        handler.write_json_message(
            "No host or api_password received.", HTTP_BAD_REQUEST)
        return

    try:
        port = int(data['port']) if 'port' in data else None
    except ValueError:
        handler.write_json_message(
            "Invalid value received for port", HTTP_UNPROCESSABLE_ENTITY)
        return

    api = rem.API(host, api_password, port)

    if not api.validate_api():
        handler.write_json_message(
            "Unable to validate API", HTTP_UNPROCESSABLE_ENTITY)
        return

    if handler.server.event_forwarder is None:
        handler.server.event_forwarder = \
            rem.EventForwarder(handler.server.hass)

    handler.server.event_forwarder.connect(api)

    handler.write_json_message("Event forwarding setup.")
Exemplo n.º 8
0
def setup(hass, config):
    """ Sets up the HTTP API and debug interface. """

    if not util.validate_config(config, {DOMAIN: [CONF_API_PASSWORD]},
                                _LOGGER):
        return False

    api_password = config[DOMAIN]['api_password']

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, rem.SERVER_PORT)

    development = config[DOMAIN].get(CONF_DEVELOPMENT, "") == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development)

    hass.listen_once_event(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True).start())

    # If no local api set, set one with known information
    if isinstance(hass, rem.HomeAssistant) and hass.local_api is None:
        hass.local_api = \
            rem.API(util.get_local_ip(), api_password, server_port)

    return True
Exemplo n.º 9
0
    def _handle_post_api_event_forward(self, path_match, data):
        """ Handles adding an event forwarding target. """

        try:
            host = data['host']
            api_password = data['api_password']
        except KeyError:
            self._message("No host or api_password received.",
                          HTTP_BAD_REQUEST)
            return

        try:
            port = int(data['port']) if 'port' in data else None
        except ValueError:
            self._message(
                "Invalid value received for port", HTTP_UNPROCESSABLE_ENTITY)
            return

        if self.server.event_forwarder is None:
            self.server.event_forwarder = \
                rem.EventForwarder(self.server.hass)

        api = rem.API(host, api_password, port)

        self.server.event_forwarder.connect(api)

        self._message("Event forwarding setup.")
Exemplo n.º 10
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)

    # If no server host is given, accept all incoming requests
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, "")) == "1"
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)

    try:
        server = HomeAssistantHTTPServer(
            (server_host, server_port), RequestHandler, hass, api_password,
            development, ssl_certificate, ssl_key)
    except OSError:
        # If address already in use
        _LOGGER.exception("Error setting up HTTP server")
        return False

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event:
        threading.Thread(target=server.start, daemon=True,
                         name='HTTP-server').start())

    hass.http = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else util.get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Exemplo n.º 11
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, "")) == "1"
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START, lambda event: threading.Thread(
            target=server.start, daemon=True, name='WSGI-server').start())

    hass.wsgi = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Exemplo n.º 12
0
def setup(hass, config=None):
    """ Sets up the HTTP API and debug interface. """

    if config is None or DOMAIN not in config:
        config = {DOMAIN: {}}

    api_password = util.convert(config[DOMAIN].get(CONF_API_PASSWORD), str)

    no_password_set = api_password is None

    if no_password_set:
        api_password = util.get_random_string()

    # If no server host is given, accept all incoming requests
    server_host = config[DOMAIN].get(CONF_SERVER_HOST, '0.0.0.0')

    server_port = config[DOMAIN].get(CONF_SERVER_PORT, SERVER_PORT)

    development = str(config[DOMAIN].get(CONF_DEVELOPMENT, "")) == "1"

    server = HomeAssistantHTTPServer((server_host, server_port),
                                     RequestHandler, hass, api_password,
                                     development, no_password_set)

    hass.bus.listen_once(
        ha.EVENT_HOMEASSISTANT_START,
        lambda event: threading.Thread(target=server.start, daemon=True).start(
        ))

    hass.http = server
    hass.config.api = rem.API(util.get_local_ip(), api_password, server_port)

    return True
Exemplo n.º 13
0
 def connect(self):
     self.api = remote.API(self.host,
                           api_password=self.password,
                           port=self.port,
                           use_ssl=self.use_ssl)
     print('Connecting to Home Assistant instance...')
     print(remote.validate_api(self.api))
Exemplo n.º 14
0
 def notification_loop(self):
     api = remote.API('brixpro.lan', haPass)
     while True:
         try:
             v = self.char_read_hnd(0x21)
             # objT = (v[1]<<8)+v[0]
             ambT = (v[3] << 8) + v[2]
             ambT = tosigned(ambT)
             c_tmpAmb = ambT / 128.0
             f_tmpAmb = 9.0 / 5.0 * c_tmpAmb + 32
             remote.set_state(api,
                              'sensor.bedroom_temp',
                              new_state=f_tmpAmb,
                              attributes={'unit_of_measurement': '°F'})
             # targetT = calcTmpTarget(objT, ambT)
             # self.data['t006'] = targetT
             # print "T006 %.1f" % c_tmpAmb
             v = self.char_read_hnd(0x29)
             rawT = (v[1] << 8) + v[0]
             rawH = (v[3] << 8) + v[2]
             (t, rh) = calcHum(rawT, rawH)
             remote.set_state(api,
                              'sensor.bedroom_humidity',
                              new_state=rh,
                              attributes={'unit_of_measurement': '%'})
             #print ("%s -- %.1f %.1f" % (time.strftime('%l:%M:%S%p %Z on %b %d, %Y'), f_tmpAmb, rh))
             time.sleep(120)  # save battery on sensortag?
         except pexpect.TIMEOUT:
             print("TIMEOUT exception!")
             break
Exemplo n.º 15
0
    def activate(self):
        """
        Triggers on plugin activation

        You should delete it if you're not using it to override any default behaviour
        """
        super(HomeAssistant, self).activate()
        self.api = remote.API(self.config['HASS_URL'], self.config['PASSWORD'])
Exemplo n.º 16
0
 def cycle(self):
     url = "http://pegasus.cs.moravian.edu:8080/api/wemo"  # Enter url here
     api = remote.API('http://homeassistant.cs.moravian.edu:8123/states', 'raspberry')
     for i in range(3):
         remote.call_service(api, 'switch', 'turn_on')
         time.sleep(3)
         remote.call_service(api, 'switch', 'turn_off')
         time.sleep(3)
Exemplo n.º 17
0
def async_setup(hass, config):
    """Set up the HTTP API and debug interface."""
    conf = config.get(DOMAIN)

    if conf is None:
        conf = HTTP_SCHEMA({})

    api_password = conf[CONF_API_PASSWORD]
    server_host = conf[CONF_SERVER_HOST]
    server_port = conf[CONF_SERVER_PORT]
    development = conf[CONF_DEVELOPMENT] == '1'
    ssl_certificate = conf[CONF_SSL_CERTIFICATE]
    ssl_key = conf[CONF_SSL_KEY]
    cors_origins = conf[CONF_CORS_ORIGINS]
    use_x_forwarded_for = conf[CONF_USE_X_FORWARDED_FOR]
    trusted_networks = conf[CONF_TRUSTED_NETWORKS]
    is_ban_enabled = conf[CONF_IP_BAN_ENABLED]
    login_threshold = conf[CONF_LOGIN_ATTEMPTS_THRESHOLD]

    if api_password is not None:
        logging.getLogger('aiohttp.access').addFilter(
            HideSensitiveDataFilter(api_password))

    server = HomeAssistantWSGI(
        hass,
        development=development,
        server_host=server_host,
        server_port=server_port,
        api_password=api_password,
        ssl_certificate=ssl_certificate,
        ssl_key=ssl_key,
        cors_origins=cors_origins,
        use_x_forwarded_for=use_x_forwarded_for,
        trusted_networks=trusted_networks,
        login_threshold=login_threshold,
        is_ban_enabled=is_ban_enabled
    )

    @asyncio.coroutine
    def stop_server(event):
        """Callback to stop the server."""
        yield from server.stop()

    @asyncio.coroutine
    def start_server(event):
        """Callback to start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        yield from server.start()

    hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server
    hass.config.api = rem.API(server_host if server_host != '0.0.0.0'
                              else get_local_ip(),
                              api_password, server_port,
                              ssl_certificate is not None)

    return True
Exemplo n.º 18
0
    def test_validate_api(self):
        """Test Python API validate_api."""
        self.assertEqual(remote.APIStatus.OK, remote.validate_api(master_api))

        self.assertEqual(
            remote.APIStatus.INVALID_PASSWORD,
            remote.validate_api(
                remote.API("127.0.0.1", API_PASSWORD + "A", MASTER_PORT)))

        self.assertEqual(remote.APIStatus.CANNOT_CONNECT,
                         remote.validate_api(broken_api))
Exemplo n.º 19
0
 def auth(self):
     status = True
     try:
         self.api = remote.API(self.metadata['host'],
                               self.metadata['password'],
                               self.metadata.get('port', 8123),
                               self.metadata.get('use_ssl', False))
     except HomeAssistantError as exception:
         logger.error(exception)
         status = False
     return status
Exemplo n.º 20
0
 def __init__(self, bot):
     self.bot = bot
     self.session = self.bot.http.session
     self.settings = dataIO.load_json(SETTINGS)
     if self.settings["ip"] == "":
         print("Cog error: hass, no IP found, please configure me!")
     if self.settings["api_key"] == "":
         print("Cog error: hass, no API Key found, please configure me!")
     global api
     global url
     api = remote.API(self.settings["ip"], self.settings["api_key"])
     url = 'https://hass.justin-tech.com'
Exemplo n.º 21
0
def ensure_slave_started():
    """ Ensure a home assistant slave is started. """

    ensure_homeassistant_started()

    if not HAHelper.slave:
        local_api = remote.API("127.0.0.1", API_PASSWORD, 8124)
        remote_api = remote.API("127.0.0.1", API_PASSWORD)
        slave = remote.HomeAssistant(remote_api, local_api)

        http.setup(slave,
                   {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD,
                                  http.CONF_SERVER_PORT: 8124}})

        slave.start()

        # Give objects time to startup
        time.sleep(1)

        HAHelper.slave = slave

    return HAHelper.slave
Exemplo n.º 22
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    logging.getLogger('aiohttp.access').addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    use_x_forwarded_for = conf.get(CONF_USE_X_FORWARDED_FOR, False)
    trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in conf.get(CONF_TRUSTED_NETWORKS, [])
    ]

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins,
                               use_x_forwarded_for=use_x_forwarded_for,
                               trusted_networks=trusted_networks)

    @asyncio.coroutine
    def stop_server(event):
        """Callback to stop the server."""
        yield from server.stop()

    @asyncio.coroutine
    def start_server(event):
        """Callback to start the server."""
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_server)
        yield from server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_server)

    hass.http = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Exemplo n.º 23
0
def structure_init(server, ha_ip, pwd):

    api = remote.API(ha_ip, pwd)
    cfg = remote.get_config(api)
    # e.g. make version property

    print(cfg)

    uri = "http://hassopcua.lvonwedel.net"
    idx = server.register_namespace(uri)

    # create state type for HASS
    types = server.get_node(ua.ObjectIds.BaseObjectType)

    object_type_to_derive_from = server.get_root_node().get_child(
        ["0:Types", "0:ObjectTypes", "0:BaseObjectType"])
    ha_state_type = types.add_object_type(idx, "HAStateType")
    ha_state_type.add_variable(idx, "state", 1.0)

    # create objects
    objects = server.get_objects_node()

    loc_name = cfg['location_name']
    loc_node = objects.add_folder(idx, loc_name)
    loc_node.add_property(idx, "location_name", loc_name)
    loc_node.add_property(idx, "elevation", cfg['elevation'])
    loc_node.add_property(idx, "latitiude", cfg['latitude'])
    loc_node.add_property(idx, "longitude", cfg['longitude'])
    loc_node.add_property(idx, "version", cfg['version'])

    entities = remote.get_states(api)
    for entity in entities:
        # create the node
        node = loc_node.add_object(idx, entity.entity_id, ha_state_type.nodeid)

        # set the value for the state child variable
        state = node.get_child('%d:state' % idx)
        state.set_value(entity.state)

        # node.set_attribute(ua.AttributeIds.DisplayName, entity.attributes['friendly_name'])

        for attr in entity.attributes.keys():
            if attr in [
                    'latitude', 'longitude', 'unit_of_measurement',
                    'friendly_name'
            ]:
                node.add_property(idx, attr, entity.attributes[attr])

    return (idx, loc_name)
Exemplo n.º 24
0
def cli(ctx, verbose, host, password, ssl, port):
    """A command line interface for Home Assistant."""
    import requests

    ctx.verbose = verbose
    ctx.password = password
    ctx.ssl = ssl
    if host is not None:
        ctx.host = host
    if port is not None:
        ctx.port = port        
    ctx.api = remote.API(ctx.host, ctx.password, ctx.port, ctx.ssl)
    if str(remote.validate_api(ctx.api)) == 'invalid_password':
        ctx.log("Your API password for %s was not provided or is wrong. "
                "Use '--password/-p'", ctx.host)
        sys.exit(1)
Exemplo n.º 25
0
    def __init__(self, hass, altitude, pressure_kpa, zones_sensors, connectors,
                 refresh_interval, evolution_arrows_minutes, remote_api_conf):
        """Initialize Local File Camera component."""
        self.hass = hass
        self._last_tile_generation = None
        self._delta_refresh = timedelta(seconds=refresh_interval)
        self._altitude = altitude
        self._pressure_kpa = pressure_kpa
        self.zones_sensors = zones_sensors
        self.colors_interior_zones = {
            k: next(POINT_COLORS)
            for k in sorted(self.zones_sensors[CONF_INTERIOR])
        }
        self.connectors = connectors

        if evolution_arrows_minutes:
            len_deque = int(
                timedelta(minutes=evolution_arrows_minutes) /
                self._delta_refresh)
        else:
            len_deque = 1
        self.points = deque([], maxlen=len_deque)
        self.svg_image_bytes = None

        self.delta_house = None
        self.open_house = None
        self._deadband = 0.5  # ºC
        self.sensor_attributes = {}

        # Remote access to sensors in other HA instance
        self.remote_api = None
        if remote_api_conf:
            from homeassistant import remote
            api = remote.API(remote_api_conf['base_url'],
                             api_password=remote_api_conf.get('api_password'),
                             port=remote_api_conf.get('port', 8123),
                             use_ssl=remote_api_conf.get('use_ssl', False))
            assert api.validate_api()
            self.remote_api = api

        # Chart regeneration
        if self.remote_api is not None:  # No need to wait
            async_track_point_in_utc_time(self.hass, self.update_chart,
                                          now() + timedelta(seconds=10))
        async_track_time_interval(self.hass, self.update_chart,
                                  self._delta_refresh)
Exemplo n.º 26
0
def setup(hass, config):
    """Set up the HTTP API and debug interface."""
    _LOGGER.addFilter(HideSensitiveFilter(hass))

    conf = config.get(DOMAIN, {})

    api_password = util.convert(conf.get(CONF_API_PASSWORD), str)
    server_host = conf.get(CONF_SERVER_HOST, '0.0.0.0')
    server_port = conf.get(CONF_SERVER_PORT, SERVER_PORT)
    development = str(conf.get(CONF_DEVELOPMENT, '')) == '1'
    ssl_certificate = conf.get(CONF_SSL_CERTIFICATE)
    ssl_key = conf.get(CONF_SSL_KEY)
    cors_origins = conf.get(CONF_CORS_ORIGINS, [])
    trusted_networks = [
        ip_network(trusted_network)
        for trusted_network in conf.get(CONF_TRUSTED_NETWORKS, [])
    ]

    server = HomeAssistantWSGI(hass,
                               development=development,
                               server_host=server_host,
                               server_port=server_port,
                               api_password=api_password,
                               ssl_certificate=ssl_certificate,
                               ssl_key=ssl_key,
                               cors_origins=cors_origins,
                               trusted_networks=trusted_networks)

    def start_wsgi_server(event):
        """Start the WSGI server."""
        server.start()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_START, start_wsgi_server)

    def stop_wsgi_server(event):
        """Stop the WSGI server."""
        server.stop()

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, stop_wsgi_server)

    hass.wsgi = server
    hass.config.api = rem.API(
        server_host if server_host != '0.0.0.0' else util.get_local_ip(),
        api_password, server_port, ssl_certificate is not None)

    return True
Exemplo n.º 27
0
def setUpModule():  # pylint: disable=invalid-name
    """Initalization of a Home Assistant server and Slave instance."""
    global hass, slave, master_api

    hass = get_test_home_assistant()

    hass.bus.listen('test_event', lambda _: _)
    hass.states.set('test.test', 'a_state')

    bootstrap.setup_component(
        hass, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: MASTER_PORT
            }
        })

    bootstrap.setup_component(hass, 'api')

    hass.start()
    time.sleep(0.05)

    master_api = remote.API("127.0.0.1", API_PASSWORD, MASTER_PORT)

    # Start slave
    loop = asyncio.new_event_loop()

    # FIXME: should not be a daemon
    threading.Thread(name="SlaveThread", daemon=True,
                     target=loop.run_forever).start()

    slave = remote.HomeAssistant(master_api, loop=loop)
    slave.config.config_dir = get_test_config_dir()
    slave.config.skip_pip = True
    bootstrap.setup_component(
        slave, http.DOMAIN, {
            http.DOMAIN: {
                http.CONF_API_PASSWORD: API_PASSWORD,
                http.CONF_SERVER_PORT: SLAVE_PORT
            }
        })

    with patch.object(ha, 'async_create_timer', return_value=None):
        slave.start()
Exemplo n.º 28
0
def setUpModule():
    """Initialization of a Home Assistant server instance."""
    global hass, master_api

    hass = get_test_home_assistant()

    hass.bus.listen('test_event', lambda _: _)
    hass.states.set('test.test', 'a_state')

    setup.setup_component(
        hass, http.DOMAIN,
        {http.DOMAIN: {http.CONF_API_PASSWORD: API_PASSWORD,
                       http.CONF_SERVER_PORT: MASTER_PORT}})

    setup.setup_component(hass, 'api')

    hass.start()

    master_api = remote.API('127.0.0.1', API_PASSWORD, MASTER_PORT)
Exemplo n.º 29
0
    def __init__(self, config, args):
        self.args = args
        self.nodes = Nodes()
        self.json = {'nodes': [], 'edges': []}

        self.haconf = homeassistant.config.load_yaml_config_file(config)

        self.directory = os.path.join(os.path.dirname(config), 'www')
        self.filename = 'z-wave-graph.json'

        # API connection necessities.
        api_password = None
        base_url = 'http://localhost'
        port = homeassistant.const.SERVER_PORT

        if self.haconf['http'] is not None and 'base_url' in self.haconf[
                'http']:
            base_url = self.haconf['http']['base_url']

        if self.haconf['http'] is not None and 'api_password' in self.haconf[
                'http']:
            api_password = str(self.haconf['http']['api_password'])

        # If the base_url ends with a port, then strip it and set the port.
        # remote.API adds the default port if port= is not set.
        m = re.match(r'(^.*)(:(\d+))$', base_url)
        if m:
            base_url = m.group(1)
            port = m.group(3)

        self.api = remote.API(base_url, api_password, port=port)
        if remote.validate_api(self.api).value != 'ok':
            print("Error, unable to connect to the API: %s" %
                  remote.validate_api(self.api))
            sys.exit(1)

        self._get_entities()

        if self.args.debug:
            self.dump_nodes()

        self._build_dot()
Exemplo n.º 30
0
def _handle_delete_api_event_forward(handler, path_match, data):
    """Handle deleting an event forwarding target."""
    try:
        host = data['host']
    except KeyError:
        handler.write_json_message("No host received.", HTTP_BAD_REQUEST)
        return

    try:
        port = int(data['port']) if 'port' in data else None
    except ValueError:
        handler.write_json_message(
            "Invalid value received for port", HTTP_UNPROCESSABLE_ENTITY)
        return

    if handler.server.event_forwarder is not None:
        api = rem.API(host, None, port)

        handler.server.event_forwarder.disconnect(api)

    handler.write_json_message("Event forwarding cancelled.")