pyliblo - Example Code

Just some useless code to show what you can do with pyliblo.

Also take a look at the send_osc and dump_osc scripts, for tiny but functional examples.

Example Client

#!/usr/bin/env python

import liblo, sys

# send all messages to port 1234 on the local machine
try:
    target = liblo.Address(1234)
except liblo.AddressError, err:
    print str(err)
    sys.exit()

# send message "/foo/message1" with int, float and string arguments
liblo.send(target, "/foo/message1", 123, 456.789, "test")

# send double, int64 and char
liblo.send(target, "/foo/message2", ('d', 3.1415), ('h', 2**42), ('c', 'x'))

# we can also build a message object first...
msg = liblo.Message("/foo/blah")
# ... append arguments later...
msg.add(123, "foo")
# ... and then send it
liblo.send(target, msg)

# send a list of bytes as a blob
blob = [4, 8, 15, 16, 23, 42]
liblo.send(target, "/foo/blob", blob)

# wrap a message in a bundle, to be dispatched after 2 seconds
bundle = liblo.Bundle(liblo.time() + 2.0, liblo.Message("/blubb", 123))
liblo.send(target, bundle)

Example Server

#!/usr/bin/env python

import liblo, sys

# create server, listening on port 1234
try:
    server = liblo.Server(1234)
except liblo.ServerError, err:
    print str(err)
    sys.exit()

def foo_bar_callback(path, args):
    i, f = args
    print "received message '%s' with arguments '%d' and '%f'" % (path, i, f)

def foo_baz_callback(path, args, types, src, data):
    print "received message '%s'" % path
    print "blob contains %d bytes, user data was '%s'" % (len(args[0]), data)

def fallback(path, args, types, src):
    print "got unknown message '%s' from '%s'" % (path, src.url)
    for a, t in zip(args, types):
        print "argument of type '%s': %s" % (t, a)

# register method taking an int and a float
server.add_method("/foo/bar", 'if', foo_bar_callback)

# register method taking a blob, and passing user data to the callback
server.add_method("/foo/baz", 'b', foo_baz_callback, "blah")

# register a fallback for unhandled messages
server.add_method(None, None, fallback)

# loop and dispatch messages every 100ms
while True:
    server.recv(100)

Example ServerThread, using the @make_method decorator

#!/usr/bin/env python

from liblo import *
import sys

class MyServer(ServerThread):
    def __init__(self):
        ServerThread.__init__(self, 1234)

    @make_method('/foo', 'ifs')
    def foo_callback(self, path, args):
        i, f, s = args
        print "received message '%s' with arguments: %d, %f, %s" % (path, i, f, s)

    @make_method(None, None)
    def fallback(self, path, args):
        print "received unknown message '%s'" % path

try:
    server = MyServer()
except ServerError, err:
    print str(err)
    sys.exit()

server.start()
raw_input("press enter to quit...\n")