Cleanup, qrnet updates

This commit is contained in:
seba 2011-10-30 02:56:45 +01:00
parent 50faf05cd9
commit a124ccf1f0
5 changed files with 112 additions and 96 deletions

View File

@ -3,21 +3,6 @@
# | ircvpn - irc virtual public network configuration | # | ircvpn - irc virtual public network configuration |
# |___________________________________________________| # |___________________________________________________|
# config options
# IRC
# - server (ip, port, ssl)
# - channel
# - nick prefix
# - maximum line length
# Network
# - device: ip, netmask, mtu
# - dhclient instead of static ip?
# - routing?
# - dns?
# Tunnel
# - security settings
# - mode (hub or switch)
import os import os
Conf = { Conf = {
@ -39,9 +24,6 @@ Conf = {
# ======== IRC settings ======== # ======== IRC settings ========
# irc-server to use # irc-server to use
#ircserver = ('irc.someserver.de', 6667)
#ircserver = ('testine.someserver.de', 6667)
#ircserver = ('192.168.56.1', 6667)
'ircserver': ('testine.someserver.de', 6667), 'ircserver': ('testine.someserver.de', 6667),
# broadcast domain (where to meet other clients) # broadcast domain (where to meet other clients)
@ -78,6 +60,6 @@ Conf = {
# ======== misc settings ======== # ======== misc settings ========
# executed after being connected to the server # executed after being connected to the server
# arguments: <command> <device> # %s will be replaces with the device name
'postConnectCmd': '/sbin/dhclient -v %s', 'postConnectCmd': '/sbin/dhclient -v %s',
} }

View File

@ -119,7 +119,7 @@ class IrcVPN(Ether2Any):
partmsg = base64.b64decode(basemsg[:64]) partmsg = base64.b64decode(basemsg[:64])
if len(partmsg) < 24: if len(partmsg) < 24:
raise ValueError() raise ValueError()
except base64.binascii.Error, ValueError: except (base64.binascii.Error, ValueError):
self.irclog.warning("Could not decode parted base64 message, discarding") self.irclog.warning("Could not decode parted base64 message, discarding")
return return
self.packets[msgid] = basemsg self.packets[msgid] = basemsg

22
tunnel/qrnet/conf.py Executable file
View File

@ -0,0 +1,22 @@
import os
Conf = {
# ======== network settings ========
# ipsettings for the device
'devname': '',
'network':
{
'address': '10.10.10.74',
'netmask': '255.255.255.0',
#gateway: '',
'mtu': 417,
},
# number of video device, mostly /dev/video<num> (value needed for opencv)
'camnum': 0,
# drop outgoing packets if more than X are in the queue
'packetDrop': 20,
}

View File

@ -1,19 +0,0 @@
import os
netmask = "255.255.255.0"
mtu = 417
ip = ""
camnum = 0
packetDrop = 20
if os.popen("hostname", "r").read().strip() in ("navi", ):
ip = "10.44.13.1"
camnum = 0
else:
ip = "10.44.13.2"
camnum = 2
if __name__ == '__main__':
print ip

View File

@ -27,19 +27,21 @@ from conf import Conf
mqueueMutex = threading.Lock() mqueueMutex = threading.Lock()
squeueMutex = threading.Lock() squeueMutex = threading.Lock()
exqueue = Queue.Queue()
class QrDisplay(gtk.Window): class QrDisplay(gtk.Window):
def __init__(self, mqueue, squeue, displog, timeout=250): def __init__(self, mqueue, squeue, displog, timeout=250):
super(QrDisplay, self).__init__() super(QrDisplay, self).__init__()
self.fullscreen()
self.qrimgPadding = 20
(wx, wy) = self.getHackySize()
self.timeout = timeout self.timeout = timeout
self.mqueue = mqueue self.mqueue = mqueue
self.squeue = squeue self.squeue = squeue
self.displog = displog self.displog = displog
self.fullscreen()
self.qrimgPadding = 20
(wx, wy) = self.getHackySize()
# build up gui # build up gui
self.vbox = gtk.VBox(False, 0) self.vbox = gtk.VBox(False, 0)
self.qrimg = gtk.Image() self.qrimg = gtk.Image()
@ -54,7 +56,7 @@ class QrDisplay(gtk.Window):
self.add(self.vbox) self.add(self.vbox)
# connect signals # connect signals
self.connect("destroy", gtk.main_quit) self.connect("destroy", self.quitGui)
self.set_size_request(wx, wy) self.set_size_request(wx, wy)
self.maximize() self.maximize()
self.set_position(gtk.WIN_POS_CENTER) self.set_position(gtk.WIN_POS_CENTER)
@ -62,6 +64,9 @@ class QrDisplay(gtk.Window):
self.qrSet("") self.qrSet("")
gobject.timeout_add(self.timeout, self.checkQueue) gobject.timeout_add(self.timeout, self.checkQueue)
def quitGui(self, *args, **kwargs):
exqueue.put(KeyboardInterrupt())
def checkQueue(self): def checkQueue(self):
#print "Check queue...", #print "Check queue...",
mqueueMutex.acquire() mqueueMutex.acquire()
@ -87,7 +92,7 @@ class QrDisplay(gtk.Window):
def getHackySize(self): def getHackySize(self):
""" Obtain current size of screen via xrandr. """ """ Obtain current size of screen via xrandr. """
#p = subprocess.Popen(["bash", "-c", 'xrandr|egrep "\*+"|egrep -o "[0-9]+x[0-9]+"'], stdout=subprocess.PIPE) #p = subprocess.Popen(["bash", "-c", 'xrandr|egrep "\*+"|egrep -o "[0-9]+x[0-9]+"'], stdout=subprocess.PIPE)
p = subprocess.Popen('xrandr|egrep "\*+"|egrep -o "[0-9]+x[0-9]+"', stdout=subprocess.PIPE) p = subprocess.Popen('xrandr|egrep "\*+"|egrep -o "[0-9]+x[0-9]+"', stdout=subprocess.PIPE, shell=True)
p.wait() p.wait()
(myout, myin) = p.communicate() (myout, myin) = p.communicate()
return map(lambda x: int(x)-self.qrimgPadding, myout.strip().split("x")) return map(lambda x: int(x)-self.qrimgPadding, myout.strip().split("x"))
@ -124,14 +129,17 @@ class DisplayThread(threading.Thread):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.dev = dev self.dev = dev
self.quit = False self.quit = False
self.qrdisplay = QrDisplay(mqueue, squeue, ) self.qrdisplay = QrDisplay(mqueue, squeue, displog)
self.mqueue = mqueue self.mqueue = mqueue
self.squeue = squeue self.squeue = squeue
self.displog = displog self.displog = displog
def run(self): def run(self):
self.displog.info("Display GTK Gui is up and running.") self.displog.info("Display GTK Gui is up and running.")
gtk.main() try:
gtk.main()
except Exception, e:
exqueue.push(e)
class CamThread(threading.Thread): class CamThread(threading.Thread):
""" Captures images from a webcam and decodes them. """ Captures images from a webcam and decodes them.
@ -151,55 +159,57 @@ class CamThread(threading.Thread):
self.success = 0 self.success = 0
self.lastPacket = "" self.lastPacket = ""
self.reader = highgui.cvCreateCameraCapture(camnum) self.reader = highgui.cvCreateCameraCapture(Conf.get("camnum", 0))
self.scanner = zbar.ImageScanner() self.scanner = zbar.ImageScanner()
self.scanner.parse_config('enable') self.scanner.parse_config('enable')
def run(self): def run(self):
while not self.quit: try:
frame = highgui.cvQueryFrame(self.reader) while not self.quit:
self.frame += 1 frame = highgui.cvQueryFrame(self.reader)
self.frame += 1
frame = opencv.cvGetMat(frame)
img = adaptors.Ipl2PIL(frame) frame = opencv.cvGetMat(frame)
width, height = img.size img = adaptors.Ipl2PIL(frame)
zimg = zbar.Image(width, height, 'Y800', img.convert("L").tostring()) width, height = img.size
self.scanner.scan(zimg) zimg = zbar.Image(width, height, 'Y800', img.convert("L").tostring())
data = None self.scanner.scan(zimg)
for symbol in zimg: data = None
data = symbol.data for symbol in zimg:
self.camlog.debug("Data is: %s" % data) data = symbol.data
self.success += 1 self.camlog.debug("Data is: %s" % data)
# handle data self.success += 1
if not self.lastPacket == data: # handle data
self.lastPacket = data if not self.lastPacket == data:
try: self.lastPacket = data
msg = base64.b64decode(data) try:
(rawtime, packet) = (msg[0:8], msg[8:]) msg = base64.b64decode(data)
ptime = struct.unpack("<d", rawtime) (rawtime, packet) = (msg[0:8], msg[8:])
self.camlog.debug("Network packet! Heade (time) is %s" % (ptime,)) ptime = struct.unpack("<d", rawtime)
self.dev.write(packet) self.camlog.debug("Network packet! Heade (time) is %s" % (ptime,))
except base64.binascii.Error: self.dev.write(packet)
print " ==> base64 error" except (base64.binascii.Error, TypeError):
self.camlog.error("Base64 error - could not decode packet") self.camlog.error("Base64 error - could not decode packet")
except struct.error: except struct.error:
self.camlog.error("Header error - could not extract header information") self.camlog.error("Header error - could not extract header information")
else: else:
# packet is already known, discard # packet is already known, discard
pass pass
# status report to gui # status report to gui
if self.frame % self.reportAfter == 0:
if self.frame % self.reportAfter == 0: self.frame = self.success = 0
self.frame = self.success = 0
# too much status codes? flush 'em squeueMutex.acquire()
squeueMutex.acquire() if self.squeue.qsize() > self.reportAfter/2:
if self.squeue.qsize() > self.reportAfter/2: while not self.squeue.empty():
while not self.squeue.empty(): self.squeue.get()
self.squeue.get() # add new status code
# add new status code self.squeue.put((self.frame, self.success))
self.squeue.put((self.frame, self.success)) squeueMutex.release()
squeueMutex.release() except Exception, e:
exqueue.put(e)
raise e
class QrNet(Ether2Any): class QrNet(Ether2Any):
@ -208,10 +218,15 @@ class QrNet(Ether2Any):
# device # device
Ether2Any.__init__(self, tap=True) Ether2Any.__init__(self, tap=True)
self.qrlog = self.setupLogging("QrNet") self.qrlog = self.setupLogging("QrNet")
self.dev.ifconfig(address=ip, netmask=netmask, mtu=mtu)
self.packetDrop = packetDrop
self.mqueue = Queue.Queue() self.mqueue = Queue.Queue()
self.squeue = Queue.Queue() self.squeue = Queue.Queue()
self.setTimeout(1)
network = Conf.get("network", {'mtu': 400})
self.packetDrop = Conf.get("packetDrop", 20)
self.dev.ifconfig(**network)
self.dev.up()
# thread starting... # thread starting...
gtk.gdk.threads_init() gtk.gdk.threads_init()
@ -221,10 +236,10 @@ class QrNet(Ether2Any):
self.display = DisplayThread(self.dev, self.mqueue, self.squeue, self.setupLogging("DisplayThread")) self.display = DisplayThread(self.dev, self.mqueue, self.squeue, self.setupLogging("DisplayThread"))
self.display.start() self.display.start()
def sendToNet(self): def sendToNet(self, msg):
# prepare data for queue && display # prepare data for queue && display
self.qrlog.debug("Data from the device") self.qrlog.debug("Data from the device")
msg = self.dev.read()
# add acttime to generate "unique" images # add acttime to generate "unique" images
acttime = struct.pack("<d", time.time()) acttime = struct.pack("<d", time.time())
bmsg = base64.b64encode(acttime + msg) bmsg = base64.b64encode(acttime + msg)
@ -238,10 +253,26 @@ class QrNet(Ether2Any):
self.qrlog.debug("Dropping packet!") self.qrlog.debug("Dropping packet!")
mqueueMutex.release() mqueueMutex.release()
def callAfterSelect(self):
# check queue for excetions
if exqueue.qsize() > 0:
ex = exqueue.get()
raise ex
def quit(self): def quit(self):
self.display.quit = True self.display.quit = True
self.cam.quit = True self.cam.quit = True
gtk.main_quit()
if __name__ == '__main__': if __name__ == '__main__':
qrnet = QrNet() try:
qrnet.run() qrnet = QrNet()
qrnet.run()
except KeyboardInterrupt:
try:
qrnet.quit()
except NameError:
pass
sys.exit(0)
except Exception, e:
raise e