From e5edab6dc1fa9b2d0115bcecf3f0c0f14eafbd92 Mon Sep 17 00:00:00 2001 From: Steffen Vogel Date: Sat, 28 Oct 2017 10:16:17 +0200 Subject: [PATCH] python: added example client application which uses Protobuf and UDP / domain sockets to communicate with VILLASnode --- clients/python/villas.py | 64 ++++++++++++++++++++++++++++++++++++++++ etc/example.conf | 4 +-- 2 files changed, 66 insertions(+), 2 deletions(-) create mode 100644 clients/python/villas.py diff --git a/clients/python/villas.py b/clients/python/villas.py new file mode 100644 index 000000000..73b22512f --- /dev/null +++ b/clients/python/villas.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- +import villas_pb2 +import time, socket, errno, sys, os, os.path + +layer = sys.argv[1] if len(sys.argv) == 2 else 'udp' + +if layer not in ['udp', 'unix']: + raise Exception('Unsupported socket type') + +if layer == 'unix': + local = '/var/run/villas-node.client.sock' + remote = '/var/run/villas-node.server.sock' + + skt = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) + + # Delete stale sockets + if os.path.exists(local): + os.unlink(local) +elif layer == 'udp': + local = ('0.0.0.0', 12001) + remote = ('127.0.0.1', 12000) + + skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + +print('Start client...') + +skt.bind(local) + +# Try to connect in case Unix domain socket does not exist yet.. +connected = False +while not connected: + try: + skt.connect(remote) + except socket.error as serr: + if serr.errno not in [ errno.ECONNREFUSED, errno.ENOENT ]: + raise serr + + print('Not connected. Retrying in 1 sec') + time.sleep(1) + else: + connected = True + +print('Ready. Ctrl-C to quit.') + +msg = villas_pb2.Message() + +while True: + try: + dgram = skt.recv(1024) + if not dgram: + break + else: + msg.ParseFromString(dgram) + print(msg) + + skt.send(msg.SerializeToString()) + + except KeyboardInterrupt: + print('Shutting down.') + break + +skt.close() + +print('Bye.') diff --git a/etc/example.conf b/etc/example.conf index 7bdba406e..984a9d862 100644 --- a/etc/example.conf +++ b/etc/example.conf @@ -99,8 +99,8 @@ nodes = { type = "socket", layer = "unix", # Datagram UNIX domain sockets require two endpoints - local = "/var/run/villas/node/node.sock", - remote = "/var/run/villas/node/client.sock" + local = "/var/run/villas-node/node.sock", + remote = "/var/run/villas-node/client.sock" }, opal_node = { # The server can be started as an Asynchronous process type = "opal", # from within an OPAL-RT model.