示例#1
0
    def test_send_search_requests(self, _search_interface_mock,
                                  netifaces_mock):
        """Test finding all valid interfaces to send search requests to. No requests are sent."""
        # pylint: disable=protected-access
        xknx = XKNX()

        netifaces_mock.interfaces.return_value = self.fake_interfaces
        netifaces_mock.ifaddresses = lambda interface: self.fake_ifaddresses[
            interface]
        netifaces_mock.AF_INET = 2

        async def async_none():
            return None

        _search_interface_mock.return_value = asyncio.ensure_future(
            async_none())

        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)

        test_scan = self.loop.run_until_complete(gateway_scanner.scan())

        self.assertEqual(_search_interface_mock.call_count, 2)
        expected_calls = [
            ((gateway_scanner, "lo0", "127.0.0.1"), ),
            ((gateway_scanner, "en1", "10.1.1.2"), ),
        ]
        self.assertEqual(_search_interface_mock.call_args_list, expected_calls)
        self.assertEqual(test_scan, [])
示例#2
0
def build_and_destroy_tunnel(xknx):

    gatewayscanner = GatewayScanner(xknx)
    yield from gatewayscanner.async_start()

    if not gatewayscanner.found:
        print("No Gateways found")
        return

    src_address = Address("15.15.249")

    print("Connecting to {}:{} from {}".format(gatewayscanner.found_ip_addr,
                                               gatewayscanner.found_port,
                                               gatewayscanner.found_local_ip))

    tunnel = Tunnel(xknx,
                    src_address,
                    local_ip=gatewayscanner.found_local_ip,
                    gateway_ip=gatewayscanner.found_ip_addr,
                    gateway_port=gatewayscanner.found_port)

    yield from tunnel.connect_udp()
    yield from tunnel.connect()

    yield from tunnel.send_telegram(
        Telegram(Address('1/0/15'), payload=DPTBinary(0)))
    yield from asyncio.sleep(2)
    yield from tunnel.send_telegram(
        Telegram(Address('1/0/15'), payload=DPTBinary(1)))
    yield from asyncio.sleep(2)

    yield from tunnel.connectionstate()
    yield from tunnel.disconnect()
示例#3
0
    def test_scan_timeout(self, netifaces_mock):
        """Test gateway scanner timeout."""
        # pylint: disable=protected-access
        xknx = XKNX()
        # No interface shall be found
        netifaces_mock.interfaces.return_value = []

        gateway_scanner = GatewayScanner(xknx)
        gateway_scanner._response_received_or_timeout.wait = MagicMock(
            side_effect=asyncio.TimeoutError())
        timed_out_scan = self.loop.run_until_complete(gateway_scanner.scan())
        # Unsuccessfull scan() returns None
        self.assertEqual(timed_out_scan, [])
示例#4
0
 async def test_scan_timeout(
     self,
     getsockname_mock,
     udp_transport_send_mock,
     udp_transport_connect_mock,
     time_travel,
 ):
     """Test gateway scanner timeout."""
     xknx = XKNX()
     gateway_scanner = GatewayScanner(xknx)
     timed_out_scan_task = asyncio.create_task(gateway_scanner.scan())
     await time_travel(gateway_scanner.timeout_in_seconds)
     # Unsuccessfull scan() returns empty list
     assert await timed_out_scan_task == []
示例#5
0
    def test_search_response_reception(self):
        """Test function of gateway scanner."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)
        gateway_scanner = GatewayScanner(xknx)
        test_search_response = fake_router_search_response(xknx)
        udp_client_mock = unittest.mock.create_autospec(UDPClient)
        udp_client_mock.local_addr = ("192.168.42.50", 0, "en1")
        udp_client_mock.getsockname.return_value = ("192.168.42.50", 0)

        self.assertEqual(gateway_scanner.found_gateways, [])
        gateway_scanner._response_rec_callback(test_search_response, udp_client_mock)
        self.assertEqual(str(gateway_scanner.found_gateways[0]),
                         str(self.gateway_desc_both))
示例#6
0
    def test_search_response_reception(self):
        """Test function of gateway scanner."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)
        gateway_scanner = GatewayScanner(xknx)
        test_search_response = fake_router_search_response(xknx)
        udp_client_mock = unittest.mock.create_autospec(UDPClient)
        udp_client_mock.local_addr = ("192.168.42.50", 0, "en1")
        udp_client_mock.getsockname.return_value = ("192.168.42.50", 0)

        self.assertEqual(gateway_scanner.found_gateways, [])
        gateway_scanner._response_rec_callback(test_search_response,
                                               udp_client_mock)
        self.assertEqual(str(gateway_scanner.found_gateways[0]),
                         str(self.gateway_desc_both))
示例#7
0
    def test_search_response_reception(self):
        """Test function of gateway scanner."""
        xknx = XKNX()
        gateway_scanner = GatewayScanner(xknx)
        test_search_response = fake_router_search_response(xknx)
        udp_client_mock = create_autospec(UDPClient)
        udp_client_mock.local_addr = ("192.168.42.50", 0)
        udp_client_mock.getsockname.return_value = ("192.168.42.50", 0)

        assert gateway_scanner.found_gateways == []
        gateway_scanner._response_rec_callback(test_search_response,
                                               udp_client_mock,
                                               interface="en1")
        assert str(gateway_scanner.found_gateways[0]) == str(
            self.gateway_desc_both)
示例#8
0
    async def test_send_search_requests(self, _search_interface_mock,
                                        netifaces_mock):
        """Test finding all valid interfaces to send search requests to. No requests are sent."""
        xknx = XKNX()

        netifaces_mock.interfaces.return_value = self.fake_interfaces
        netifaces_mock.ifaddresses = lambda interface: self.fake_ifaddresses[
            interface]
        netifaces_mock.AF_INET = 2

        async def async_none():
            return None

        _search_interface_mock.return_value = asyncio.ensure_future(
            async_none())

        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)

        test_scan = await gateway_scanner.scan()

        assert _search_interface_mock.call_count == 2
        expected_calls = [
            ((gateway_scanner, "lo0", "127.0.0.1"), ),
            ((gateway_scanner, "en1", "10.1.1.2"), ),
        ]
        assert _search_interface_mock.call_args_list == expected_calls
        assert test_scan == []
示例#9
0
    async def test_send_search_requests(
        self,
        udp_transport_send_mock,
        udp_transport_connect_mock,
    ):
        """Test if both search requests are sent per interface."""
        xknx = XKNX()
        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)
        with patch(
                "xknx.io.util.get_default_local_ip",
                return_value="10.1.1.2",
        ), patch(
                "xknx.io.util.get_local_interface_name",
                return_value="en_0123",
        ), patch(
                "xknx.io.gateway_scanner.UDPTransport.getsockname",
                return_value=("10.1.1.2", 56789),
        ):
            await gateway_scanner.scan()

        assert udp_transport_connect_mock.call_count == 1
        assert udp_transport_send_mock.call_count == 2
        frame_1 = udp_transport_send_mock.call_args_list[0].args[0]
        frame_2 = udp_transport_send_mock.call_args_list[1].args[0]
        assert isinstance(frame_1.body, SearchRequestExtended)
        assert isinstance(frame_2.body, SearchRequest)
        assert frame_1.body.discovery_endpoint == HPAI(ip_addr="10.1.1.2",
                                                       port=56789)
示例#10
0
async def main():
    """Search for a Tunnelling device, walk through all possible channels and disconnect them."""
    xknx = XKNX()
    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("No Gateways found")
        return

    gateway = gateways[0]

    if not gateway.supports_tunnelling:
        print("Gateway does not support tunneling")
        return

    udp_client = UDPClient(xknx, (gateway.local_ip, 0), (gateway.ip_addr, gateway.port))

    await udp_client.connect()

    for i in range(0, 255):

        conn_state = ConnectionState(xknx, udp_client, communication_channel_id=i)

        await conn_state.start()

        if conn_state.success:
            print("Disconnecting ", i)
            disconnect = Disconnect(xknx, udp_client, communication_channel_id=i)

            await disconnect.start()

            if disconnect.success:
                print("Disconnected ", i)
示例#11
0
async def main():
    """Connect to a tunnel, send 2 telegrams and disconnect."""
    xknx = XKNX()
    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("No Gateways found")
        return

    gateway = gateways[0]
    src_address = PhysicalAddress("15.15.249")

    print("Connecting to {}:{} from {}".format(gateway.ip_addr, gateway.port,
                                               gateway.local_ip))

    tunnel = Tunnel(xknx,
                    src_address,
                    local_ip=gateway.local_ip,
                    gateway_ip=gateway.ip_addr,
                    gateway_port=gateway.port)

    await tunnel.connect_udp()
    await tunnel.connect()

    await tunnel.send_telegram(
        Telegram(GroupAddress('1/0/15'), payload=DPTBinary(1)))
    await asyncio.sleep(2)
    await tunnel.send_telegram(
        Telegram(GroupAddress('1/0/15'), payload=DPTBinary(0)))
    await asyncio.sleep(2)

    await tunnel.connectionstate()
    await tunnel.disconnect()
示例#12
0
    def test_scan_timeout(self, netifaces_mock):
        """Test gateway scanner timeout."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)
        # No interface shall be found
        netifaces_mock.interfaces.return_value = []

        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)

        timed_out_scan = self.loop.run_until_complete(gateway_scanner.scan())

        # Timeout handle was cancelled (cancelled method requires Python 3.7)
        event_has_cancelled = getattr(gateway_scanner._timeout_handle, "cancelled", None)
        if callable(event_has_cancelled):
            self.assertTrue(gateway_scanner._timeout_handle.cancelled())
        self.assertTrue(gateway_scanner._response_received_or_timeout.is_set())
        # Unsuccessfull scan() returns None
        self.assertEqual(timed_out_scan, [])
示例#13
0
    def test_scan_timeout(self, netifaces_mock):
        """Test gateway scanner timeout."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)
        # No interface shall be found
        netifaces_mock.interfaces.return_value = []

        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)

        timed_out_scan = self.loop.run_until_complete(gateway_scanner.scan())

        # Timeout handle was cancelled (cancelled method requires Python 3.7)
        event_has_cancelled = getattr(gateway_scanner._timeout_handle,
                                      "cancelled", None)
        if callable(event_has_cancelled):
            self.assertTrue(gateway_scanner._timeout_handle.cancelled())
        self.assertTrue(gateway_scanner._response_received_or_timeout.is_set())
        # Unsuccessfull scan() returns None
        self.assertEqual(timed_out_scan, [])
示例#14
0
    def test_search_response_reception(self):
        """Test function of gateway scanner."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)
        gateway_scanner = GatewayScanner(xknx)
        search_response = fake_router_search_response(xknx)
        udp_client = unittest.mock.create_autospec(UDPClient)
        udp_client.local_addr = ("192.168.42.50", 0, "en1")
        udp_client.getsockname.return_value = ("192.168.42.50", 0)
        router_gw_descriptor = GatewayDescriptor(name="Gira KNX/IP-Router",
                                                 ip_addr="192.168.42.10",
                                                 port=3671,
                                                 local_interface="en1",
                                                 local_ip="192.168.42.50",
                                                 supports_tunnelling=True,
                                                 supports_routing=True)

        self.assertEqual(gateway_scanner.found_gateways, [])
        gateway_scanner._response_rec_callback(search_response, udp_client)
        self.assertEqual(str(gateway_scanner.found_gateways[0]),
                         str(router_gw_descriptor))
示例#15
0
    async def test_scan_timeout(self, netifaces_mock):
        """Test gateway scanner timeout."""
        xknx = XKNX()
        # No interface shall be found
        netifaces_mock.interfaces.return_value = []

        gateway_scanner = GatewayScanner(xknx)
        gateway_scanner._response_received_event.wait = MagicMock(
            side_effect=asyncio.TimeoutError())
        timed_out_scan = await gateway_scanner.scan()
        # Unsuccessfull scan() returns None
        assert timed_out_scan == []
示例#16
0
    def test_search_response_reception(self):
        """Test function of gateway scanner."""
        xknx = XKNX()
        gateway_scanner = GatewayScanner(xknx)
        test_search_response = fake_router_search_response()
        udp_transport_mock = create_autospec(UDPTransport)
        udp_transport_mock.local_addr = ("192.168.42.50", 0)
        udp_transport_mock.getsockname.return_value = ("192.168.42.50", 0)

        assert not gateway_scanner.found_gateways
        gateway_scanner._response_rec_callback(
            test_search_response,
            HPAI("192.168.42.50", 0),
            udp_transport_mock,
            interface="en1",
        )
        assert len(gateway_scanner.found_gateways) == 1

        gateway_scanner._response_rec_callback(
            test_search_response,
            HPAI("192.168.42.230", 0),
            udp_transport_mock,
            interface="eth1",
        )
        assert len(gateway_scanner.found_gateways) == 1

        assert str(gateway_scanner.found_gateways[
            test_search_response.body.control_endpoint]) == str(
                self.gateway_desc_both)
示例#17
0
    def test_send_search_requests(self, _search_interface_mock, netifaces_mock):
        """Test finding all valid interfaces to send search requests to. No requests are sent."""
        # pylint: disable=protected-access
        xknx = XKNX(loop=self.loop)

        netifaces_mock.interfaces.return_value = self.fake_interfaces
        netifaces_mock.ifaddresses = lambda interface: self.fake_ifaddresses[interface]
        netifaces_mock.AF_INET = 2

        async def async_none():
            return None
        _search_interface_mock.return_value = asyncio.ensure_future(async_none())

        gateway_scanner = GatewayScanner(xknx, timeout_in_seconds=0)

        test_scan = self.loop.run_until_complete(gateway_scanner.scan())

        self.assertEqual(_search_interface_mock.call_count, 2)
        expected_calls = [((gateway_scanner, 'lo0', '127.0.0.1'),),
                          ((gateway_scanner, 'en1', '10.1.1.2'),)]
        self.assertEqual(_search_interface_mock.call_args_list, expected_calls)
        self.assertEqual(test_scan, [])
示例#18
0
async def main():

    xknx = XKNX()

    # Recherche des gateways

    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("none")
        return

    gateway = gateways[0]
    print(gateway)
示例#19
0
async def main():
    """Search for available KNX/IP devices with GatewayScanner and print out result if a device was found."""
    xknx = XKNX()
    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("No Gateways found")

    else:
        for gateway in gateways:
            print("Gateway found: {0} / {1}:{2}".format(
                gateway.name, gateway.ip_addr, gateway.port))
            if gateway.supports_tunnelling:
                print("- Device supports tunneling")
            if gateway.supports_routing:
                print("- Device supports routing, connecting via {0}".format(
                    gateway.local_ip))
示例#20
0
async def main():
    """Connect to a tunnel, send 2 telegrams and disconnect."""
    xknx = XKNX()
    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("No Gateways found")
        return

    gateway = gateways[0]
    # an individual address will most likely be assigned by the tunnelling server
    xknx.own_address = IndividualAddress("15.15.249")

    print(
        f"Connecting to {gateway.ip_addr}:{gateway.port} from {gateway.local_ip}"
    )

    tunnel = UDPTunnel(
        xknx,
        telegram_received_callback=received_callback,
        gateway_ip=gateway.ip_addr,
        gateway_port=gateway.port,
        local_ip=gateway.local_ip,
        local_port=0,
        route_back=False,
    )

    await tunnel.connect()

    await tunnel.send_telegram(
        Telegram(
            destination_address=GroupAddress("1/0/15"),
            payload=GroupValueWrite(DPTBinary(1)),
        ))
    await asyncio.sleep(2)
    await tunnel.send_telegram(
        Telegram(
            destination_address=GroupAddress("1/0/15"),
            payload=GroupValueWrite(DPTBinary(0)),
        ))
    await asyncio.sleep(2)

    await tunnel.disconnect()
示例#21
0
    async def test_async_scan_exit(
        self,
        udp_transport_send_mock,
        udp_transport_connect_mock,
        time_travel,
    ):
        """Test gateway scanner timeout for async generator."""
        xknx = XKNX()
        test_search_response = fake_router_search_response()
        udp_transport_mock = Mock()
        udp_transport_mock.local_addr = ("10.1.1.2", 56789)

        gateway_scanner = GatewayScanner(xknx, local_ip="10.1.1.2")

        async def test():
            async for gateway in gateway_scanner.async_scan():
                assert isinstance(gateway, GatewayDescriptor)
                return True
            return False

        with patch(
                "xknx.io.gateway_scanner.UDPTransport.getsockname",
                return_value=("10.1.1.2", 56789),
        ), patch("xknx.io.gateway_scanner.UDPTransport.register_callback"
                 ) as register_callback_mock:
            scan_task = asyncio.create_task(test())
            await time_travel(0)
            _fished_response_rec_callback = register_callback_mock.call_args.args[
                0]
            _fished_response_rec_callback(
                test_search_response,
                HPAI("192.168.42.50", 0),
                udp_transport_mock,
            )
            assert await scan_task
            await time_travel(0)  # for task cleanup
示例#22
0
async def main():
    """Connect to a tunnel, send 2 telegrams and disconnect."""
    xknx = XKNX()
    gatewayscanner = GatewayScanner(xknx)
    gateways = await gatewayscanner.scan()

    if not gateways:
        print("No Gateways found")
        return

    gateway = gateways[0]
    # an individual address will most likely be assigned by the tunnelling server
    xknx.own_address = PhysicalAddress("15.15.249")

    print("Connecting to {}:{} from {}".format(gateway.ip_addr, gateway.port,
                                               gateway.local_ip))

    tunnel = Tunnel(
        xknx,
        local_ip=gateway.local_ip,
        gateway_ip=gateway.ip_addr,
        gateway_port=gateway.port,
    )

    await tunnel.connect_udp()
    await tunnel.connect()

    await tunnel.send_telegram(
        Telegram(GroupAddress("1/0/15"), payload=DPTBinary(1)))
    await asyncio.sleep(2)
    await tunnel.send_telegram(
        Telegram(GroupAddress("1/0/15"), payload=DPTBinary(0)))
    await asyncio.sleep(2)

    await tunnel.connectionstate()
    await tunnel.disconnect()
示例#23
0
import asyncio
from xknx import XKNX
from xknx.io. async import ConnectionState, Disconnect
from xknx.io. async import UDPClient, GatewayScanner

xknx = XKNX()

gatewayscanner = GatewayScanner(xknx)
gatewayscanner.start()
gatewayscanner.stop()

if not gatewayscanner.found:
    raise Exception("No Gateways found")

print("Connecting to {}:{} from {}".format(gatewayscanner.found_ip_addr,
                                           gatewayscanner.found_port,
                                           gatewayscanner.found_local_ip))

own_ip = "192.168.42.1"
gateway_ip = "192.168.42.10"
gateway_port = 3671

udp_client = UDPClient(
    xknx, (gatewayscanner.found_local_ip, 0),
    (gatewayscanner.found_ip_addr, gatewayscanner.found_port))

task = asyncio.Task(udp_client.connect())

xknx.loop.run_until_complete(task)

for i in range(0, 255):
示例#24
0
 async def test():
     xknx = XKNX()
     async for _ in GatewayScanner(xknx).async_scan():
         break
     else:
         return True