Exemple #1
0
def setup(hass, config):
    """Setup the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException

    host = config[DOMAIN].get(CONF_HOST, None)

    if host is None:
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")
        host = "0.0.0.0"

    try:
        port = int(config[DOMAIN].get(CONF_PORT, DEFAULT_PORT))
    except ValueError:
        _LOGGER.exception("Can't parse KNX IP interface port")
        return False

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        KNXTUNNEL.connect()
    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)
    return True
Exemple #2
0
def setup(hass, config):
    """Set up the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException

    host = config[DOMAIN].get(CONF_HOST)
    port = config[DOMAIN].get(CONF_PORT)

    if host is '0.0.0.0':
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        res = KNXTUNNEL.connect()
        _LOGGER.debug("Res = %s", res)
        if not res:
            _LOGGER.exception("Could not connect to KNX/IP interface %s", host)
            return False

    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)
    return True
Exemple #3
0
def setup(hass, config):
    """Set up the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException

    host = config[DOMAIN].get(CONF_HOST)
    port = config[DOMAIN].get(CONF_PORT)

    if host is '0.0.0.0':
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        res = KNXTUNNEL.connect()
        _LOGGER.debug("Res = %s", res)
        if not res:
            _LOGGER.error("Could not connect to KNX/IP interface %s", host)
            return False

    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)
    return True
Exemple #4
0
def KNX_tunnel(knx_gw_ip):
    """Open a tunnel with the KNX ethernet/knx bus module"""

    tunnel = KNXIPTunnel(knx_gw_ip)
    if tunnel.connect():
        print('Tunnel opened')
        return tunnel
    else:
        return None
Exemple #5
0
 def testKeepAlive(self):
     """Test if the background thread runs and updated the state"""
     tunnel = KNXIPTunnel("0.0.0.0")
     self.assertTrue(tunnel.connect())
     # Background thread should reset this to 0 if the connection is still
     # alive
     tunnel.connection_state = 1
     time.sleep(66)
     self.assertEqual(tunnel.connection_state, 0)
Exemple #6
0
 def testKeepAlive(self):
     """Test if the background thread runs and updated the state"""
     tunnel = KNXIPTunnel(gwip)
     self.assertTrue(tunnel.connect())
     # Background thread should reset this to 0 if the connection is still
     # alive
     tunnel.connection_state=1
     time.sleep(66)
     self.assertEqual(tunnel.connection_state,0)        
Exemple #7
0
    def testListeners(self):
        """Test if listeners can be registered and unregistered."""
        def message_received(address, data):
            pass

        tunnel = KNXIPTunnel("0.0.0.0")
        tunnel.register_listener(0, message_received)
        res = tunnel.unregister_listener(0, message_received)
        assert (res)
Exemple #8
0
    def testListeners(self):
        """Test if listeners can be registered and unregistered."""

        def message_received(address, data):
            pass

        tunnel = KNXIPTunnel(gwip)
        tunnel.register_listener(0, message_received)
        res = tunnel.unregister_listener(0, message_received)
        assert(res)
Exemple #9
0
    def testCleanup(self):
        """Test of disconnect works fine

        Makes sure that there are no connections left open
        """
        for _i in range(0, 10):
            # Try to connect to an auto-discovered KNX gateway
            tunnel = KNXIPTunnel(gwip)
            tunnel.connect()
            tunnel.disconnect()
Exemple #10
0
    def testReadTimeout(self):
        """Test if read timeouts work and group_read operations

        group_read operations should never block
        """
        tunnel = KNXIPTunnel("0.0.0.0")
        tunnel.connect()

        # Read from some random address and hope nothing responds here
        tick = datetime.now()
        res = tunnel.group_read(37000, timeout=1)
        tock = datetime.now()
        diff = tock - tick  # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 1 and diff.total_seconds() < 3)
        self.assertIsNone(res)

        # Read from some random address and hope nothing responds here
        tick = datetime.now()
        res = tunnel.group_read(37000, timeout=5)
        tock = datetime.now()
        diff = tock - tick  # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 5 and diff.total_seconds() < 6)
        self.assertIsNone(res)

        tunnel.disconnect()
Exemple #11
0
def KNX_tunnel(knx_gw_ip):
    """Open a tunnel with the KNX ethernet/knx bus module"""

    tunnel = KNXIPTunnel(ip=knx_gw_ip)
    """while not tunnel.connect():
        print("Tunnel not opened trying again")
        tunnel = KNXIPTunnel(knx_gw_ip)
    print("Tunnel opened")"""

    if tunnel.connect():
        print('Tunnel opened')
        return tunnel
    else:
        print('Tunnel not opened')
        return None
Exemple #12
0
    def testReadTimeout(self):
        """Test if read timeouts work and group_read operations

        group_read operations should never block
        """
        tunnel = KNXIPTunnel(gwip)
        tunnel.connect()

        # Read from some random address and hope nothing responds here
        tick = datetime.now()
        res = tunnel.group_read(37000, timeout=1)
        tock = datetime.now()
        diff = tock - tick    # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 1 and diff.total_seconds() < 3)
        self.assertIsNone(res)

        # Read from some random address and hope nothing responds here
        tick = datetime.now()
        res = tunnel.group_read(37000, timeout=5)
        tock = datetime.now()
        diff = tock - tick    # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 5 and diff.total_seconds() < 6)
        self.assertIsNone(res)

        tunnel.disconnect()
Exemple #13
0
    def testConnect(self):
        """Test if the system can connect to an auto-discovered gateway"""
        # Try to connect to an auto-discovered KNX gateway
        tunnel = KNXIPTunnel("0.0.0.0")
        self.assertTrue(tunnel.connect())
        tunnel.disconnect()

        # Try to connect to a non-existing gateway
        # Check if the timeout works as expected
        tunnel = KNXIPTunnel("240.0.0.0")
        tick = datetime.now()
        self.assertFalse(tunnel.connect(2))
        tock = datetime.now()
        diff = tock - tick  # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 1 and diff.total_seconds() < 3)
Exemple #14
0
    def testCleanup(self):
        """Test of disconnect works fine

        Makes sure that there are no connections left open
        """
        for _i in range(0, 10):
            # Try to connect to an auto-discovered KNX gateway
            tunnel = KNXIPTunnel("0.0.0.0")
            tunnel.connect()
            tunnel.disconnect()
Exemple #15
0
    def testConnect(self):
        """Test if the system can connect to an auto-discovered gateway"""
        # Try to connect to an auto-discovered KNX gateway
        tunnel = KNXIPTunnel(gwip)
        self.assertTrue(tunnel.connect())
        tunnel.disconnect()

        # Try to connect to a non-existing gateway
        # Check if the timeout works as expected
        tunnel = KNXIPTunnel("240.0.0.0")
        tick = datetime.now()
        self.assertFalse(tunnel.connect(2))
        tock = datetime.now()
        diff = tock - tick    # the result is a datetime.timedelta object
        self.assertTrue(diff.total_seconds() >= 1 and diff.total_seconds() < 3)
Exemple #16
0
    def __init__(self, engine, config_dict):
        super(KNX, self).__init__(engine, config_dict)
        conf = config_dict['KNX']

        # Read default information for gateway
        self._gateway_ip = conf['gateway_ip']
        self._gateway_port = int(conf.get('gateway_port', 3671))

        # Read the mapping information for KNX and store them locally
        self._knx_map = weeutil.config.deep_copy(conf)
        del self._knx_map['gateway_ip']
        del self._knx_map['gateway_port']

        self._knx_tunnel = KNXIPTunnel(self._gateway_ip, self._gateway_port)

        self.bind(weewx.NEW_ARCHIVE_RECORD, self._handle_new_archive_record)

        loginf('Started knx extension for weewx with gateway {0}'.format(
            self._gateway_ip))
        if self._gateway_ip == '0.0.0.0':
            loginf('Will try to auto-detect KNX/IP gateway')
Exemple #17
0
def setup(hass, config):
    """Set up the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException, parse_group_address

    host = config[DOMAIN].get(CONF_HOST)
    port = config[DOMAIN].get(CONF_PORT)

    if host == '0.0.0.0':
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        res = KNXTUNNEL.connect()
        _LOGGER.debug("Res = %s", res)
        if not res:
            _LOGGER.error("Could not connect to KNX/IP interface %s", host)
            return False

    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    def received_knx_event(address, data):
        """Process received KNX message."""
        if len(data) == 1:
            data = data[0]
        hass.bus.fire('knx_event', {'address': address, 'data': data})

    for listen in config[DOMAIN].get(CONF_LISTEN):
        _LOGGER.debug("Registering listener for %s", listen)
        try:
            KNXTUNNEL.register_listener(parse_group_address(listen),
                                        received_knx_event)
        except KNXException as knxexception:
            _LOGGER.error("Can't register KNX listener for address %s (%s)",
                          listen, knxexception)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)

    # Listen to KNX events and send them to the bus
    def handle_knx_send(event):
        """Bridge knx_frame_send events to the KNX bus."""
        try:
            addr = event.data["address"]
        except KeyError:
            _LOGGER.error("KNX group address is missing")
            return

        try:
            data = event.data["data"]
        except KeyError:
            _LOGGER.error("KNX data block missing")
            return

        knxaddr = None
        try:
            addr = int(addr)
        except ValueError:
            pass

        if knxaddr is None:
            try:
                knxaddr = parse_group_address(addr)
            except KNXException:
                _LOGGER.error("KNX address format incorrect")
                return

        knxdata = None
        if isinstance(data, list):
            knxdata = data
        else:
            try:
                knxdata = [int(data) & 0xff]
            except ValueError:
                _LOGGER.error("KNX data format incorrect")
                return

        KNXTUNNEL.group_write(knxaddr, knxdata)

    # Listen for when knx_frame_send event is fired
    hass.bus.listen(EVENT_KNX_FRAME_SEND, handle_knx_send)

    return True
Exemple #18
0
def setup(hass, config):
    """Set up the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException, parse_group_address

    host = config[DOMAIN].get(CONF_HOST)
    port = config[DOMAIN].get(CONF_PORT)

    if host == '0.0.0.0':
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        res = KNXTUNNEL.connect()
        _LOGGER.debug("Res = %s", res)
        if not res:
            _LOGGER.error("Could not connect to KNX/IP interface %s", host)
            return False

    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    def received_knx_event(address, data):
        """Process received KNX message."""
        if len(data) == 1:
            data = data[0]
        hass.bus.fire('knx_event', {
            'address': address,
            'data': data
        })

    for listen in config[DOMAIN].get(CONF_LISTEN):
        _LOGGER.debug("Registering listener for %s", listen)
        try:
            KNXTUNNEL.register_listener(parse_group_address(listen),
                                        received_knx_event)
        except KNXException as knxexception:
            _LOGGER.error("Can't register KNX listener for address %s (%s)",
                          listen, knxexception)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)

    # Listen to KNX events and send them to the bus
    def handle_knx_send(event):
        """Bridge knx_frame_send events to the KNX bus."""
        try:
            addr = event.data["address"]
        except KeyError:
            _LOGGER.error("KNX group address is missing")
            return

        try:
            data = event.data["data"]
        except KeyError:
            _LOGGER.error("KNX data block missing")
            return

        knxaddr = None
        try:
            addr = int(addr)
        except ValueError:
            pass

        if knxaddr is None:
            try:
                knxaddr = parse_group_address(addr)
            except KNXException:
                _LOGGER.error("KNX address format incorrect")
                return

        knxdata = None
        if isinstance(data, list):
            knxdata = data
        else:
            try:
                knxdata = [int(data) & 0xff]
            except ValueError:
                _LOGGER.error("KNX data format incorrect")
                return

        KNXTUNNEL.group_write(knxaddr, knxdata)

    # Listen for when knx_frame_send event is fired
    hass.bus.listen(EVENT_KNX_FRAME_SEND, handle_knx_send)

    return True
Exemple #19
0
 def testAutoConnect(self):
     """Test if the KNX tunnel will be automatically connected."""
     tunnel = KNXIPTunnel("0.0.0.0")
     self.assertFalse(tunnel.connected)
     tunnel.group_read(1)
     self.assertTrue(tunnel.connected)
Exemple #20
0
 def testAutoConnect(self):
     """Test if the KNX tunnel will be automatically connected."""
     tunnel = KNXIPTunnel(gwip)
     self.assertFalse(tunnel.connected)
     tunnel.group_read(1)
     self.assertTrue(tunnel.connected)
Exemple #21
0
def setup(hass, config):
    """Set up the connection to the KNX IP interface."""
    global KNXTUNNEL

    from knxip.ip import KNXIPTunnel
    from knxip.core import KNXException, parse_group_address

    host = config[DOMAIN].get(CONF_HOST)
    port = config[DOMAIN].get(CONF_PORT)

    if host == '0.0.0.0':
        _LOGGER.debug("Will try to auto-detect KNX/IP gateway")

    KNXTUNNEL = KNXIPTunnel(host, port)
    try:
        res = KNXTUNNEL.connect()
        _LOGGER.debug("Res = %s", res)
        if not res:
            _LOGGER.error("Could not connect to KNX/IP interface %s", host)
            return False

    except KNXException as ex:
        _LOGGER.exception("Can't connect to KNX/IP interface: %s", ex)
        KNXTUNNEL = None
        return False

    _LOGGER.info("KNX IP tunnel to %s:%i established", host, port)

    descriptions = load_yaml_config_file(
        os.path.join(os.path.dirname(__file__), 'services.yaml'))

    def received_knx_event(address, data):
        """Process received KNX message."""
        if len(data) == 1:
            data = data[0]
        hass.bus.fire('knx_event', {
            'address': address,
            'data': data
        })

    for listen in config[DOMAIN].get(CONF_LISTEN):
        _LOGGER.debug("Registering listener for %s", listen)
        try:
            KNXTUNNEL.register_listener(parse_group_address(listen),
                                        received_knx_event)
        except KNXException as knxexception:
            _LOGGER.error("Can't register KNX listener for address %s (%s)",
                          listen, knxexception)

    hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, close_tunnel)

    # Listen to KNX events and send them to the bus
    def handle_group_write(call):
        """Bridge knx_frame_send events to the KNX bus."""
        # parameters are pre-validated using KNX_WRITE_SCHEMA
        addrlist = call.data.get("address")
        knxdata = call.data.get("data")

        knxaddrlist = []
        for addr in addrlist:
            try:
                _LOGGER.debug("Found %s", addr)
                knxaddr = int(addr)
            except ValueError:
                knxaddr = None

            if knxaddr is None:
                try:
                    knxaddr = parse_group_address(addr)
                except KNXException:
                    _LOGGER.error("KNX address format incorrect: %s", addr)

            knxaddrlist.append(knxaddr)

        for addr in knxaddrlist:
            KNXTUNNEL.group_write(addr, knxdata)

    # Listen for when knx_frame_send event is fired
    hass.services.register(DOMAIN,
                           KNX_GROUP_WRITE,
                           handle_group_write,
                           descriptions[DOMAIN][KNX_GROUP_WRITE],
                           schema=KNX_WRITE_SCHEMA)

    return True
Exemple #22
0
'''
'''
from knxip.ip import KNXIPTunnel
from knxip.timeupdater import KNXDateTimeUpdater

tun = KNXIPTunnel()
print("Connected to KNX interface")
upd = KNXDateTimeUpdater(tun,
                         dateaddr="0/2/1",
                         timeaddr="0/2/0",
                         updateinterval=3)
upd.send_updates()

upd.run_updater_in_background()

time.sleep(60)