Just showing off some work I did this weekend porting some internal code to the 
`nesper` library. It's an RPC library taken from `nim-json-rpc` but with async 
support cut out -- shout out to the Status-IM Folks for the handy rpc macros! 
It supports either JSON or MessagePack as the transport mechanism over TCP 
sockets. Meaning you can re-use all of your standard json-rpc libraries and 
knowledge in the embedded world. :-)

Normally JSON on an embedded device is tedious and the libraries tend to be 
relatively large (in embedded terms) so many prefer Firmata (based on MIDI) or 
similar. Nim makes it a cake walk however:
    
    
    import nesper/servers/rpc/rpcsocket_json
    # import nesper/servers/rpc/rpcsocket_mpack
    
    # Setup RPC Server #
    proc run_rpc_server*() =
        
        var rt = createRpcRouter(MaxRpcReceiveBuffer)
        
        rpc(rt, "hello") do(input: string) -> string:
            result = "Hello " & input
        
        rpc(rt, "add") do(a: int, b: int) -> int:
            result = a + b
        
        rpc(rt, "addAll") do(vals: seq[int]) -> int:
            result = 0
            for x in vals:
                result += x
        
        echo "starting rpc server on port 5555"
        logi(TAG,"starting rpc server buffer size: %s", $(rt.buffer))
        startRpcSocketServer(Port(5555), router=rt)
    
    
    
    Run

I did some profiling on the overhead. It takes about 12ms using messagepack and 
18ms using JSON when passing an array of 300 ints. Given the ping RTT on my 
network to an ESP32 Feather/Huzzah is about 4ms (broadcast), that means the 
time to service the RPC request is about 8-14ms. Not bad! Note its compiled 
using ESP-IDF debug and Nim release settings.

The RPC doesn't use async since I'd like to use ARC instead of ORC to avoid 
that overhead. Instead it uses `select` on the LwIP socket library. I'd like to 
explore implementing an async library using the FreeRTOS event loop, but that's 
beyond me at the moment.

Does anyone have ideas on how to make an `async` library for Nim using the 
esp's event loop? Could it be done using ARC only? 

Reply via email to