Beispiel #1
0
async def node1():
    with pynng.Req0() as sock:
        sock.dial(address)
        print(f"NODE1: SENDING DATE REQUEST")
        await sock.asend(DATE.encode())
        msg = await sock.arecv_msg()
        print(f"NODE1: RECEIVED DATE {msg.bytes.decode()}")
Beispiel #2
0
def test_synchronous_recv_context():
    with pynng.Rep0(listen=addr, recv_timeout=500) as rep, \
            pynng.Req0(dial=addr, recv_timeout=500) as req:
        req.send(b'oh hello there old pal')
        assert rep.recv() == b'oh hello there old pal'
        rep.send(b'it is so good to hear from you')
        assert req.recv() == b'it is so good to hear from you'
Beispiel #3
0
    def _send_bytes(self, buf):
        if self._req is None:
            self._req = pynng.Req0()

        logger.debug('Get address from directory for handle %s',
                     self._subhandle)
        addr = self._client.get(self._subhandle)

        retry = 15
        retry_sleep = 1
        while addr is None:
            time.sleep(retry_sleep)
            retry_sleep += 0.5
            addr = self._client.get(self._subhandle)
            retry -= 1
            if retry == 0:
                raise Exception(
                    'Server address could not be fetched for handle {}'.format(
                        self._subhandle))

        addr = addr.decode('utf-8')
        logger.debug('Dialing %s', addr)
        self._req.dial(addr)
        logger.debug('Send %i B to %s', len(buf), addr)
        self._req.send(buf)
        res = self._req.recv()
        logger.debug(res)
Beispiel #4
0
def main():
    for N in [100, 3 * 1024 * 1024, 1920 * 1080 * 3]:
        ba = (random.getrandbits(8 * N)).to_bytes(N, sys.byteorder)
        with pynng.Rep0(listen=ipc_address) as rep, pynng.Req0(dial=ipc_address) as req:
            t0 = time.time_ns()
            req.send(ba)
            rep.send(rep.recv())
            print((time.time_ns() - t0) / 10 ** 6, "ms")
def init():
    global hp
    global sock
    global numDevices
    global screenW
    global screenH
    global aspect

    print("Init Settings")
    start_time = timeit.default_timer()

    wm = bpy.context.window_manager

    ws_url = "ws://localhost:11222/driver"
    driver_url = "ipc:///tmp/holoplay-driver.ipc"

    ensure_site_packages([
        ("cbor", "cbor"),
        ("cffi","cffi"),
        ("pycparser","pycparser"),
        ("pynng","pynng"),
        ("sniffio", "sniffio"),
        ("PIL", "Pillow")
    ])

    import pynng

    # This script should work identically whether addr = driver_url or addr = ws_url
    addr = driver_url
    # if sock == None:
    sock = pynng.Req0(recv_timeout=2000)
    try:
        sock.dial(addr, block = True)
    except:
        print("Could not open socket. Is driver running?")
        sys.exit(1)

    response = send_message(sock, {'cmd':{'info':{}},'bin':''})
    if response != None:
        # create a dictionary with an index for this device
        devices = response['devices']
        if devices == []:
            print("No Looking Glass devices found")
        else:
            print("Printing Devices")
            screenW = devices[0]['calibration']['screenW']['value']
            screenH = devices[0]['calibration']['screenH']['value']
            aspect = screenW / screenH
            wm.screenW = screenW
            wm.screenH = screenH
            wm.aspect = aspect
            print(devices)
            wm.numDevicesConnected = 1

    print("Number of devices found: " + str(wm.numDevicesConnected))

    print("Init Settings")
Beispiel #6
0
async def test_multiple_contexts():
    async def recv_and_send(ctx):
        data = await ctx.arecv()
        await trio.sleep(0.05)
        await ctx.asend(data)

    with pynng.Rep0(listen=addr, recv_timeout=500) as rep, \
            pynng.Req0(dial=addr, recv_timeout=500) as req1, \
            pynng.Req0(dial=addr, recv_timeout=500) as req2:
        async with trio.open_nursery() as n:
            ctx1, ctx2 = [rep.new_context() for _ in range(2)]
            with ctx1, ctx2:
                n.start_soon(recv_and_send, ctx1)
                n.start_soon(recv_and_send, ctx2)

                await req1.asend(b'oh hi')
                await req2.asend(b'me toooo')
                assert (await req1.arecv() == b'oh hi')
                assert (await req2.arecv() == b'me toooo')
Beispiel #7
0
def test_multiple_contexts():
    async def recv_and_send(ctx):
        data = await ctx.arecv()
        await trio.sleep(0.05)
        await ctx.asend(data)

    async def do_some_stuff(rep, req1, req2):
        async with trio.open_nursery() as n:
            ctx1, ctx2 = rep.new_contexts(2)
            n.start_soon(recv_and_send, ctx1)
            n.start_soon(recv_and_send, ctx2)

            await req1.asend(b'oh hi')
            await req2.asend(b'me toooo')
            assert (await req1.arecv() == b'oh hi')
            assert (await req2.arecv() == b'me toooo')

    with pynng.Rep0(listen=addr, recv_timeout=500) as rep, \
            pynng.Req0(dial=addr, recv_timeout=500) as req1, \
            pynng.Req0(dial=addr, recv_timeout=500) as req2:
        trio.run(do_some_stuff, rep, req1, req2)
Beispiel #8
0
async def client_loop(worker_name, addresses):
    with pynng.Req0() as req_sock:
        for addr in addresses:
            req_sock.dial(addr)

        for i in range(30):
            uid = uuid.uuid4().hex[:8]
            await trio.sleep(0.5)
            print(f'{worker_name}: sending message')
            await req_sock.asend(f"msg {i}-{uid}".encode())
            msg = await req_sock.arecv_msg()
            print(f"{worker_name} received response: {msg.bytes.decode()}")
            print()
Beispiel #9
0
def test_context_recv_send_msg():
    with pynng.Req0(listen=addr, recv_timeout=to) as s1, \
            pynng.Rep0(dial=addr, recv_timeout=to) as s2:
        with s1.new_context() as ctx1, s2.new_context() as ctx2:
            wait_pipe_len(s1, 1)
            msg = pynng.Message(b'do i even know you')
            ctx1.send_msg(msg)
            msg2 = ctx2.recv_msg()
            assert msg2.pipe is s2.pipes[0]
            assert msg2.bytes == b'do i even know you'
            msg3 = pynng.Message(b'yes of course i am your favorite platypus')
            ctx2.send_msg(msg3)
            msg4 = ctx1.recv_msg()
            assert msg4.pipe is s1.pipes[0]
            assert msg4.bytes == b'yes of course i am your favorite platypus'
Beispiel #10
0
def client(n, dm, rm):
    with pynng.Req0(dial=ipc_address) as req:
        ba = (random.getrandbits(8 * n)).to_bytes(n, sys.byteorder)
        try:
            t0 = time.time_ns()
            req.send(b"connect")
            if req.recv() == b"data":
                t1 = time.time_ns()
                dm.write(ba)
                print("write data to mmap", (time.time_ns() - t1) / 10 ** 6, "ms")
                req.send(b"ready")
            if req.recv() == b"result":
                print(len(rm))
                req.send(b"get")
            print("ttl: ", (time.time_ns() - t0) / 10 ** 6, "ms")
        except Exception as e:
            print(e)
Beispiel #11
0
def test_cannot_double_send():
    # double send would cause a SEGFAULT!!! That's no good
    with pynng.Req0(listen=addr, recv_timeout=to) as s1, \
            pynng.Rep0(dial=addr, recv_timeout=to) as s2:
        msg = pynng.Message(b'this is great')
        s1.send_msg(msg)
        with pytest.raises(pynng.MessageStateError):
            s1.send_msg(msg)

        with s1.new_context() as ctx:
            msg = pynng.Message(b'this also is great')
            ctx.send_msg(msg)
            with pytest.raises(pynng.MessageStateError):
                ctx.send_msg(msg)

        # don't really need to receive, but linters hate not using s2
        s2.recv_msg()
Beispiel #12
0
def test_reqrep0():
    with pynng.Req0(listen=addr, recv_timeout=100) as req, \
            pynng.Rep0(dial=addr, recv_timeout=100) as rep:

        request = b'i am requesting'
        req.send(request)
        assert rep.recv() == request

        response = b'i am responding'
        rep.send(response)
        assert req.recv() == response

        with pytest.raises(pynng.BadState):
            req.recv()

        # responders can't send before receiving
        with pytest.raises(pynng.BadState):
            rep.send(b'I cannot do this why am I trying')
Beispiel #13
0
async def test_context():
    with pynng.Req0(listen=addr, recv_timeout=1000) as req_sock, \
            pynng.Rep0(dial=addr, recv_timeout=1000) as rep_sock:
        with req_sock.new_context() as req, rep_sock.new_context() as rep:

            assert isinstance(req, pynng.Context)
            assert isinstance(rep, pynng.Context)
            request = b'i am requesting'
            await req.asend(request)
            assert await rep.arecv() == request

            response = b'i am responding'
            await rep.asend(response)
            assert await req.arecv() == response

            with pytest.raises(pynng.BadState):
                await req.arecv()

            # responders can't send before receiving
            with pytest.raises(pynng.BadState):
                await rep.asend(b'I cannot do this why am I trying')
Beispiel #14
0
def req(target: Addr, topic: str, payload: Any, timeout: int = 0) -> Any:
    """ 发起req请求

    Args:
        target: 目标地址
        topic: 主题
        payload: 消息
        timeout: 发送超时时间(毫秒)。默认为0,即非阻塞。若为-1,则将一直等待。
    """

    with pynng.Req0() as node:
        node.dial(f'tcp://{target[1]}:{target[0]}')
        node.send(topic.encode() + b'^&*;' + pickle.dumps(payload))

        node.recv_timeout = timeout
        try:
            res = node.recv()
        except:
            res = None

        return pickle.loads(res)
Beispiel #15
0
    def InitializeApp(self, app_name, hpc_license_type):

        # set default error value:
        # NOTE: - if communication with HoloPlay Service fails, we use the
        #         direct HID approach to read calibration data
        error = self.client_error.CLIERR_NOERROR.value

        # if all python dependencies are fulfilled
        if python_dependecies == True:

            # open a Req0 socket
            self.socket = pynng.Req0(recv_timeout = 5000)

            # try to address the HoloPlay Service
            try:

                self.socket.dial(self.driver_address, block = True)

                # TODO: Set proper error values
                # set error value
                error = self.client_error.CLIERR_NOERROR.value

            except:

                # Close socket and reset status variable
                if self.socket != None:
                    self.socket.close()
                    self.socket = None

                pass

        # if everything is fine:
        if error == self.client_error.CLIERR_NOERROR.value:

            # we use the RefreshState function to build
            # the list of Looking Glass devices, since it is the same code
            self.RefreshState()

        # return error value
        return error
Beispiel #16
0
def init():
    global hp
    global sock
    global numDevices
    global screenW
    global screenH
    global aspect
    global hardwareVersion

    print("Init Settings")
    start_time = timeit.default_timer()

    wm = bpy.context.window_manager

    ws_url = "ws://localhost:11222/driver"
    driver_url = "ipc:///tmp/holoplay-driver.ipc"

    ensure_site_packages([("pynng", "pynng"), ("PIL", "Pillow")])

    import pynng

    # This script should work identically whether addr = driver_url or addr = ws_url
    addr = driver_url

    sock = pynng.Req0(recv_timeout=2000)
    try:
        sock.dial(addr, block=True)
    except:
        print("Could not open socket. Is driver running?")
        sock = None
        return False

    response = send_message(sock, {'cmd': {'info': {}}, 'bin': ''})
    if response != None:
        # create a dictionary with an index for this device
        devices = response['devices']
        if devices == []:
            print("No Looking Glass devices found")
        else:
            print("Reading settings from device")
            screenW = devices[0]['calibration']['screenW']['value']
            screenH = devices[0]['calibration']['screenH']['value']
            quiltX = devices[0]['defaultQuilt']['quiltX']
            quiltY = devices[0]['defaultQuilt']['quiltY']
            tileX = devices[0]['defaultQuilt']['tileX']
            tileY = devices[0]['defaultQuilt']['tileY']
            hardwareVersion = devices[0][
                'hardwareVersion']  # not storing this in wm because we need to change this to support multiple devices in the future
            aspect = screenW / screenH
            wm.screenW = screenW
            wm.screenH = screenH
            wm.aspect = aspect
            wm.quiltX = quiltX
            wm.quiltY = quiltY
            wm.tileX = tileX
            wm.tileY = tileY
            if hardwareVersion == 'portrait':
                wm.viewX = 420
                wm.viewY = 560
                wm.quiltX = 3360
                wm.quiltY = 3360
            # print(devices)
            # print(hardwareVersion)
            wm.numDevicesConnected = 1  # temporarily support only one device due to the way we globally store vars in the wm

    print("Number of devices found: " + str(wm.numDevicesConnected))
Beispiel #17
0
    async def async_run(self):
        """Setup Request Handler (Request/Response) pattern."""
        self.s_request = pynng.Req0(dial='tcp://0.0.0.0:41000')

        await self.request(AnnounceMessage("test_service", "0.0.0.0", 8080))