File size: 1,654 Bytes
7073aad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# Minimal policy server speaking the openpi websocket protocol (openpi_client.websocket_client_policy):
# on connect send msgpack-numpy packed metadata; then for each packed observation reply with the packed result dict,
# or with a plain string (traceback) on error. Shared by the GR00T and OpenWAM MobileManipBench servers.
import asyncio
import logging
import time
import traceback

import websockets.asyncio.server
import websockets.frames
from openpi_client import msgpack_numpy


def serve(infer, metadata: dict, host: str = "0.0.0.0", port: int = 8000):
    packer = msgpack_numpy.Packer()

    async def handler(ws):
        logging.info("client connected: %s", ws.remote_address)
        await ws.send(packer.pack(metadata))
        while True:
            try:
                obs = msgpack_numpy.unpackb(await ws.recv())
                t0 = time.monotonic()
                out = infer(obs)
                out["server_timing"] = {"infer_ms": (time.monotonic() - t0) * 1000}
                await ws.send(packer.pack(out))
            except websockets.ConnectionClosed:
                logging.info("client disconnected: %s", ws.remote_address)
                break
            except Exception:
                await ws.send(traceback.format_exc())
                await ws.close(code=websockets.frames.CloseCode.INTERNAL_ERROR, reason="internal server error")
                raise

    async def main():
        async with websockets.asyncio.server.serve(handler, host, port, compression=None, max_size=None) as srv:
            logging.info("serving on %s:%d", host, port)
            await srv.serve_forever()

    asyncio.run(main())