コード例 #1
0
ファイル: test_sending.py プロジェクト: delfick/photons
 async def gen(sd, reference, **kwargs):
     async with hp.tick(0, max_iterations=3, name="test_m1", min_wait=0) as ticks:
         async for i, _ in ticks:
             try:
                 called.append(("m1_start", i))
                 await (yield original2)
             except:
                 called.append(("m1_except", i, type(sys.exc_info()[1]).__name__))
                 raise
             finally:
                 called.append(("m1_finally", i))
コード例 #2
0
ファイル: test_sending.py プロジェクト: delfick/photons
 async def gen(sd, reference, **kwargs):
     async with hp.tick(0, min_wait=0, name="test_m2") as ticks:
         async for i, _ in ticks:
             try:
                 called.append(("m2_start", i))
                 await (yield [original1, msg])
             except:
                 called.append(("m2_except", i, type(sys.exc_info()[1]).__name__))
                 raise
             finally:
                 called.append(("m2_finally", i))
コード例 #3
0
ファイル: test_sending.py プロジェクト: delfick/photons
 async def gen(sd, reference, **kwargs):
     async with hp.tick(0, min_wait=0, name="test") as ticks:
         async for i, _ in ticks:
             try:
                 called.append(("start", i))
                 await (yield original)
             except:
                 called.append(("except", i, sys.exc_info()))
                 raise
             finally:
                 called.append(("finally", i))
コード例 #4
0
    async def open_browser(self):
        async with hp.tick(0.1, max_time=3) as ticker:
            async for _ in ticker:
                if port_connected(self.options.port):
                    break

        if not port_connected(self.options.port):
            self.photons_app.final_future.set_exception(
                PhotonsAppError("Failed to start the server"))
            return

        if "NO_WEB_OPEN" not in os.environ:
            webbrowser.open(f"http://{self.options.host}:{self.options.port}")
コード例 #5
0
ファイル: script.py プロジェクト: delfick/photons
    async def gen(reference, sender, **kwargs):
        min_wait = False
        if spread <= 0:
            min_wait = 0

        async with hp.tick(spread, min_wait=min_wait) as ticks:
            async for i, _ in ticks:
                if i > len(messages):
                    return

                t = yield messages[i - 1]
                success = await t
                if not success and short_circuit_on_error:
                    return
コード例 #6
0
    async def collect_parts(self, ts):
        async with hp.tick(
                self.run_options.rediscover_every,
                final_future=self.final_future,
                name="AnimationRunner::collect_parts[tick]",
        ) as ticks:
            async for _ in ticks:
                with hp.just_log_exceptions(log,
                                            reraise=[asyncio.CancelledError]):
                    serials = self.reference
                    if isinstance(serials, str):
                        serials = [serials]
                    elif isinstance(serials, SpecialReference):
                        self.reference.reset()
                        try:
                            _, serials = await self.reference.find(
                                self.sender,
                                timeout=self.kwargs.get("find_timeout", 10))
                        except asyncio.CancelledError:
                            raise
                        except FoundNoDevices:
                            log.warning("Didn't find any devices")
                            continue

                    new = set(serials) - self.seen_serials
                    if not new:
                        continue

                    devices = []
                    collected = []
                    async for device, parts in self.parts_from_serials(new):
                        # Make sure the part isn't known by other animations currently running
                        if device.serial not in self.used_serials:
                            self.used_serials.add(device.serial)
                            self.collected[device.serial] = parts
                            devices.append(device)

                            def process(res):
                                if ts.pending == 0:
                                    self.final_future.cancel()

                            self.original_canvas.add_parts(*parts,
                                                           with_colors=True)
                            collected.append(parts)

                    yield collected

                    for device in devices:
                        t = ts.add(self.turn_on(device.serial))
                        t.add_done_callback(process)
コード例 #7
0
ファイル: io.py プロジェクト: delfick/photons
    async def power_on(self, event):
        await super().power_on(event)

        class ServerProtocol(asyncio.Protocol):
            def connection_made(sp, transport):
                sp.udp_transport = transport

            def datagram_received(sp, data, addr):
                if not self.device.has_power:
                    return

                async def give_reply(bts, addr, replying_to, *, reply):
                    if sp.udp_transport and not sp.udp_transport.is_closing():
                        sp.udp_transport.sendto(bts, addr)

                self.received(data, give_reply, addr)

        port = None
        error = None
        remote = None
        async with hp.tick(0.1, max_iterations=3) as ticker:
            async for _ in ticker:
                port = self.options.port
                if port is None:
                    port = make_port()

                try:
                    remote, _ = await hp.get_event_loop(
                    ).create_datagram_endpoint(ServerProtocol,
                                               local_addr=("0.0.0.0", port))
                    self.remote = remote
                except OSError as e:
                    error = e
                else:
                    await self.device.annotate(
                        logging.INFO,
                        f"Creating {self.io_source} port",
                        serial=self.device.serial,
                        port=port,
                        service=self.io_source,
                    )
                    self.options.port = port
                    break

        if remote is None:
            raise Exception(
                "%" * 80 +
                f"%%% Failed to bind to a udp socket: {port} ({error})\n" +
                "You should stop whatever is using that port!")
コード例 #8
0
ファイル: device_finder.py プロジェクト: xbliss/photons-core
    async def search_loop(self):
        refresh_discovery_fltr = Filter.empty(refresh_discovery=True)

        async for _ in hp.tick(self.search_interval):
            if self.final_future.done():
                return

            try:
                async for device in self.finder.find(refresh_discovery_fltr):
                    device.ensure_refresh_information_loop(
                        self.sender, self.time_between_queries,
                        self.finder.collections)
            except asyncio.CancelledError:
                raise
            except Exception:
                log.exception("Something went wrong in a search")
コード例 #9
0
ファイル: device_finder.py プロジェクト: xbliss/photons-core
        async def gen(reference, sender, **kwargs):
            async for _ in hp.tick(1):
                if self.final_future.done():
                    return

                e = next(points)
                fut = self.point_futures[e]

                if fut.done():
                    refresh = refreshes[e]
                    if refresh is None:
                        continue

                    if time.time() - fut.result() < refresh:
                        continue

                yield e.value.msg
コード例 #10
0
ファイル: device_finder.py プロジェクト: delfick/photons
        async def gen(reference, sender, **kwargs):
            async with hp.tick(
                1,
                final_future=self.final_future,
                name=f"Device({self.serial})::refresh_information_loop[tick]",
            ) as ticks:
                async for info in ticks:
                    if self.final_future.done():
                        return

                    e = find_point()
                    if e is None:
                        continue

                    if self.serial not in sender.found:
                        break

                    t = yield e.value.msg
                    await t
コード例 #11
0
ファイル: script.py プロジェクト: delfick/photons
    async def gen(reference, sender, **kwargs):
        async with hp.tick(min_loop_time,
                           min_wait=False,
                           final_future=sender.stop_fut) as ticks:
            async for i, _ in ticks:
                try:
                    await (yield msg)
                finally:
                    if isinstance(reference, SpecialReference):
                        reference.reset()

                    if callable(on_done_loop):
                        try:
                            await on_done_loop()
                        except Repeater.Stop:
                            return
                        except asyncio.CancelledError:
                            raise
                        except Exception as error:
                            hp.add_error(kwargs["error_catcher"], error)
コード例 #12
0
 async def gen(reference, sender, **kwargs):
     with alter_called("primary"):
         async with hp.tick(0.3) as ticks:
             async for i, _ in ticks:
                 called.append(("primary", i))
                 yield make_secondary_msg(i, m)
コード例 #13
0
 async def gen(reference, sender, **kwargs):
     with alter_called(("secondary", i)):
         async with hp.tick(0.1) as ticks:
             async for _ in ticks:
                 called.append(("secondary", i))
                 yield DeviceMessages.SetPower(level=0)
コード例 #14
0
 async def tick(self):
     async with hp.tick(*self.args, **self.kwargs) as ticks:
         async for i, nxt_time in ticks:
             if i == 4:
                 wait.set_result(True)
             yield i, nxt_time
コード例 #15
0
ファイル: test_ticker.py プロジェクト: xbliss/photons-core
            finals = [(final, i) for i, (final, _, _) in enumerate(whens)]

            for final, i, in sorted(finals):
                if time.time() < final:
                    self.t.set(final)
                whens[i][2]()
                await asyncio.sleep(0)


describe "tick":
    async it "keeps yielding such that yields are 'every' apart", FakeTime:
        called = []

        with FakeTime() as t:
            async with MockedCallLater(t) as m:
                async for i in hp.tick(3):
                    called.append((i, time.time()))
                    if len(called) == 5:
                        break

        assert called == [(1, 0), (2, 3), (3, 6), (4, 9), (5, 12)]
        assert m.called_times == [3, 3, 3, 3]

    async it "keeps yielding until max_iterations", FakeTime:
        called = []

        with FakeTime() as t:
            async with MockedCallLater(t):
                async for i in hp.tick(3, max_iterations=5):
                    called.append(i)
コード例 #16
0
ファイル: test_sending.py プロジェクト: delfick/photons
 async def gen(sd, reference, **kwargs):
     async with hp.tick(0, min_wait=0) as ticks:
         async for _ in ticks:
             await (yield original)
コード例 #17
0
ファイル: test_ticker.py プロジェクト: delfick/photons
# coding: spec

from photons_app import helpers as hp

import asyncio
import time


describe "tick":

    async it "keeps yielding such that yields are 'every' apart", FakeTime, MockedCallLater:
        called = []

        with FakeTime() as t:
            async with MockedCallLater(t) as m:
                async with hp.tick(3) as ticks:
                    async for i, nxt in ticks:
                        called.append((i, nxt, time.time()))
                        if len(called) == 5:
                            break

        assert called == [(1, 3, 0), (2, 3, 3), (3, 3, 6), (4, 3, 9), (5, 3, 12)]
        assert m.called_times == [3, 6, 9, 12]

    async it "works with 0 every", FakeTime, MockedCallLater:
        called = []

        with FakeTime() as t:
            async with MockedCallLater(t) as m:
                async with hp.tick(0, min_wait=0) as ticks:
                    async for i, nxt in ticks: