From fce69b46eecf447a515475d65327da2c92bfdc40 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 14:14:02 +0200 Subject: [PATCH 01/10] added better chaosc init script to repo --- config_files/chaosc | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100755 config_files/chaosc diff --git a/config_files/chaosc b/config_files/chaosc new file mode 100755 index 0000000..ea5b027 --- /dev/null +++ b/config_files/chaosc @@ -0,0 +1,21 @@ +#!/sbin/runscript + +depend() { + need net + use dns localmount + after bootmisc + provide chaosc +} + + +start() { + ebegin "starting chaosc" + start-stop-daemon --start --pidfile /var/run/chaosc.pid --make-pidfile --user sarah --group sarah --background --exec /usr/bin/chaosc + eend $? +} + +stop() { + ebegin "stopping chaosc" + start-stop-daemon --stop --quiet --pidfile /var/run/chaosc.pid + eend $? +} From 2effe315a71a209151f73552b8ecc8279a7bb800 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 16:31:19 +0200 Subject: [PATCH 02/10] implemented dump_grabber --- dump_grabber/dump_grabber/main.py | 273 ++++++++++++++++++++++++++++-- 1 file changed, 261 insertions(+), 12 deletions(-) diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index 4c6ab8b..f0186ca 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -6,12 +6,40 @@ import sys, os, random from PyQt4 import QtCore, QtGui - +from PyQt4.QtCore import QBuffer, QByteArray, QIODevice from dump_grabber_ui import Ui_MainWindow from PyKDE4.kdecore import ki18n, KCmdLineArgs, KAboutData from PyKDE4.kdeui import KMainWindow, KApplication +from datetime import datetime +import threading +import Queue +import traceback +import numpy as np +import string +import time +import random +import socket +import os.path +from os import curdir, sep +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from SocketServer import ThreadingMixIn, ForkingMixIn +import select +import re + +from collections import deque + +from chaosc.argparser_groups import * +from chaosc.lib import resolve_host + +try: + from chaosc.c_osc_lib import OSCMessage, decode_osc +except ImportError as e: + print(e) + from chaosc.osc_lib import OSCMessage, decode_osc + + appName = "dump_grabber" catalog = "dump_grabber" programName = ki18n("dump_grabber") @@ -23,7 +51,7 @@ KCmdLineArgs.init (sys.argv, aboutData) app = KApplication() class MainWindow(KMainWindow, Ui_MainWindow): - def __init__(self, parent=None): + def __init__(self, parent=None, columns=3): super(MainWindow, self).__init__(parent) self.setupUi(self) self.graphics_view.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) @@ -39,24 +67,245 @@ class MainWindow(KMainWindow, Ui_MainWindow): self.font_metrics = QtGui.QFontMetrics(self.default_font) self.line_height = self.font_metrics.height() self.num_lines = 775/self.line_height - + self.graphics_scene.setFont(self.default_font) print "font", self.default_font.family(), self.default_font.pixelSize(), self.default_font.pointSize() self.brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) self.brush.setStyle(QtCore.Qt.SolidPattern) - pos_y = 0 - for i in range(self.num_lines): - text = self.graphics_scene.addSimpleText("osc address:/test/foo/bar arguments:[%d] types=[\"i\"]" % random.randint(0,255), self.default_font) - text.setBrush(self.brush) - text.setPos(0, i * self.line_height) - pos_y += self.line_height + self.column_count = columns + self.columns = [["" for j in range(self.num_lines)] + for i in range(columns)] + self.column_width = 775 / columns + self.column_heads = [self.num_lines - 1] * columns self.graphics_view.show() + def add_text(self, column, text): + head = self.column_heads[column] + text_item = self.graphics_scene.addSimpleText(text, self.default_font) + #text_item.setPen(QtCore.Qt.red) + if column == 0: + text_item.setBrush(QtCore.Qt.red) + elif column == 1: + text_item.setBrush(QtCore.Qt.green) + elif column == 2: + text_item.setBrush(QtCore.Qt.blue) + text_item.setPos(column * self.column_width, head * self.line_height) + print "head", column, head + self.columns[column][head] = text_item + self.column_heads[column] = (head - 1) % self.num_lines + + + def render(self): + image = QtGui.QImage(768, 576, QtGui.QImage.Format_ARGB32_Premultiplied) + image.fill(QtCore.Qt.black) + painter = QtGui.QPainter(image) + #painter.setPen(QtCore.Qt.white) + painter.setFont(self.default_font) + self.graphics_view.render(painter, target=QtCore.QRectF(0,0,768,576),source=QtCore.QRect(0,0,768,576)) + return image + + +class OSCThread(threading.Thread): + def __init__(self, args): + super(OSCThread, self).__init__() + self.args = args + self.running = True + + self.client_address = resolve_host(args.client_host, args.client_port, args.address_family) + + self.chaosc_address = chaosc_host, chaosc_port = resolve_host(args.chaosc_host, args.chaosc_port, args.address_family) + + self.osc_sock = socket.socket(args.address_family, 2, 17) + self.osc_sock.bind(self.client_address) + self.osc_sock.setblocking(0) + + print "%s: starting up osc receiver on '%s:%d'" % ( + datetime.now().strftime("%x %X"), self.client_address[0], self.client_address[1]) + + self.subscribe_me() + + def subscribe_me(self): + """Use this procedure for a quick'n dirty subscription to your chaosc instance. + + :param chaosc_address: (chaosc_host, chaosc_port) + :type chaosc_address: tuple + + :param receiver_address: (host, port) + :type receiver_address: tuple + + :param token: token to get authorized for subscription + :type token: str + """ + print "%s: subscribing to '%s:%d' with label %r" % (datetime.now().strftime("%x %X"), self.chaosc_address[0], self.chaosc_address[1], self.args.subscriber_label) + msg = OSCMessage("/subscribe") + msg.appendTypedArg(self.client_address[0], "s") + msg.appendTypedArg(self.client_address[1], "i") + msg.appendTypedArg(self.args.authenticate, "s") + if self.args.subscriber_label is not None: + msg.appendTypedArg(self.args.subscriber_label, "s") + self.osc_sock.sendto(msg.encode_osc(), self.chaosc_address) + + + def unsubscribe_me(self): + if self.args.keep_subscribed: + return + + print "%s: unsubscribing from '%s:%d'" % (datetime.now().strftime("%x %X"), self.chaosc_address[0], self.chaosc_address[1]) + msg = OSCMessage("/unsubscribe") + msg.appendTypedArg(self.client_address[0], "s") + msg.appendTypedArg(self.client_address[1], "i") + msg.appendTypedArg(self.args.authenticate, "s") + self.osc_sock.sendto(msg.encode_osc(), self.chaosc_address) + + def run(self): + + while self.running: + try: + reads, writes, errs = select.select([self.osc_sock], [], [], 0.05) + except Exception, e: + print "select error", e + pass + else: + if reads: + try: + osc_input, address = self.osc_sock.recvfrom(8192) + osc_address, typetags, messages = decode_osc(osc_input, 0, len(osc_input)) + print osc_address, typetags, messages + if osc_address.find("ekg") != -1 or osc_address.find("plot") != -1: + queue.put_nowait((osc_address, messages)) + except Exception, e: + print "recvfrom error", e + else: + queue.put_nowait(("/bjoern/ekg", [0])) + queue.put_nowait(("/merle/ekg", [0])) + queue.put_nowait(("/uwe/ekg", [0])) + + self.unsubscribe_me() + print "OSCThread is going down" + + +queue = Queue.Queue() + +class MyHandler(BaseHTTPRequestHandler): + + def do_GET(self): + + try: + self.path=re.sub('[^.a-zA-Z0-9]', "",str(self.path)) + if self.path=="" or self.path==None or self.path[:1]==".": + self.send_error(403,'Forbidden') + + + if self.path.endswith(".html"): + directory = os.path.dirname(os.path.abspath(__file__)) + data = open(os.path.join(directory, self.path), "rb").read() + self.send_response(200) + self.send_header('Content-type', 'text/html') + self.end_headers() + self.wfile.write(data) + elif self.path.endswith(".mjpeg"): + self.thread = thread = OSCThread(self.server.args) + thread.daemon = True + thread.start() + window = MainWindow() + window.show() + + self.send_response(200) + self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--aaboundary") + self.end_headers() + + event_loop = QtCore.QEventLoop() + while 1: + event_loop.processEvents() + app.sendPostedEvents(None, 0) + while 1: + try: + osc_address, args = queue.get_nowait() + print osc_address, args + except Queue.Empty: + break + else: + if "merle" in osc_address: + window.add_text(0, "%s = %s" % (osc_address[7:], ", ".join([str(i) for i in args]))) + elif "uwe" in osc_address: + window.add_text(1, "%s = %s" % (osc_address[5:], ", ".join([str(i) for i in args]))) + elif "bjoern" in osc_address: + window.add_text(2, "%s = %s" % (osc_address[8:], ", ".join([str(i) for i in args]))) + + img = window.render() + buffer = QBuffer() + buffer.open(QIODevice.WriteOnly) + img.save(buffer, "JPG", 100) + img.save("/tmp/test.jpg", "JPG") + + JpegData = buffer.data() + self.wfile.write("--aaboundary\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) + + JpegData = None + buffer = None + img = None + + elif self.path.endswith(".jpeg"): + directory = os.path.dirname(os.path.abspath(__file__)) + data = open(os.path.join(directory, self.path), "rb").read() + self.send_response(200) + self.send_header('Content-type','image/jpeg') + self.end_headers() + self.wfile.write(data) + return + except (KeyboardInterrupt, SystemError): + print "queue size", queue.qsize() + if hasattr(self, "thread") and self.thread is not None: + self.thread.running = False + self.thread.join() + self.thread = None + except IOError, e: + print "ioerror", e, e[0] + print dir(e) + if e[0] in (32, 104): + if hasattr(self, "thread") and self.thread is not None: + self.thread.running = False + self.thread.join() + self.thread = None + else: + print '-'*40 + print 'Exception happened during processing of request from' + traceback.print_exc() # XXX But this goes to stderr! + print '-'*40 + self.send_error(404,'File Not Found: %s' % self.path) + + +class JustAHTTPServer(HTTPServer): + pass + + def main(): - window = MainWindow() - window.show() - app.exec_() + arg_parser = ArgParser("ekgplotter") + arg_parser.add_global_group() + client_group = arg_parser.add_client_group() + arg_parser.add_argument(client_group, '-x', "--http_host", default="::", + help='my host, defaults to "::"') + arg_parser.add_argument(client_group, '-X', "--http_port", default=9000, + type=int, help='my port, defaults to 9000') + arg_parser.add_chaosc_group() + arg_parser.add_subscriber_group() + args = arg_parser.finalize() + + http_host, http_port = resolve_host(args.http_host, args.http_port, args.address_family) + + server = JustAHTTPServer((http_host, http_port), MyHandler) + server.address_family = args.address_family + server.args = args + print "%s: starting up http server on '%s:%d'" % ( + datetime.now().strftime("%x %X"), http_host, http_port) + + try: + server.serve_forever() + except KeyboardInterrupt: + print '^C received, shutting down server' + server.socket.close() + sys.exit(0) if ( __name__ == '__main__' ): From 7e93c46547a061da2ddc275f47e7ac7be0e5aa89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 17:46:14 +0200 Subject: [PATCH 03/10] fixed layout and colors --- dump_grabber/dump_grabber/main.py | 46 +++++++++++++++++++------------ 1 file changed, 28 insertions(+), 18 deletions(-) diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index f0186ca..300ab17 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -64,6 +64,7 @@ class MainWindow(KMainWindow, Ui_MainWindow): self.default_font = QtGui.QFont("Monospace", 14) self.default_font.setStyleHint(QtGui.QFont.Monospace) self.default_font.setBold(True) + self.blue_color = QtGui.QColor(47,147,235) self.font_metrics = QtGui.QFontMetrics(self.default_font) self.line_height = self.font_metrics.height() self.num_lines = 775/self.line_height @@ -72,28 +73,38 @@ class MainWindow(KMainWindow, Ui_MainWindow): print "font", self.default_font.family(), self.default_font.pixelSize(), self.default_font.pointSize() self.brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) self.brush.setStyle(QtCore.Qt.SolidPattern) + self.column_width = 775 / columns self.column_count = columns - self.columns = [["" for j in range(self.num_lines)] - for i in range(columns)] - self.column_width = 775 / columns - self.column_heads = [self.num_lines - 1] * columns + self.columns = list() + for i in range(columns): + column = list() + for j in range(self.num_lines): + text_item = self.graphics_scene.addSimpleText("", self.default_font) + if column == 0: + text_item.setBrush(QtCore.Qt.red) + elif column == 1: + text_item.setBrush(QtCore.Qt.green) + elif column == 2: + text_item.setBrush(self.blue_color) + text_item.setPos(j * self.line_height, i * self.column_width) + column.append(text_item) + self.columns.append(column) self.graphics_view.show() def add_text(self, column, text): - head = self.column_heads[column] text_item = self.graphics_scene.addSimpleText(text, self.default_font) - #text_item.setPen(QtCore.Qt.red) if column == 0: text_item.setBrush(QtCore.Qt.red) elif column == 1: text_item.setBrush(QtCore.Qt.green) elif column == 2: - text_item.setBrush(QtCore.Qt.blue) - text_item.setPos(column * self.column_width, head * self.line_height) - print "head", column, head - self.columns[column][head] = text_item - self.column_heads[column] = (head - 1) % self.num_lines + text_item.setBrush(self.blue_color) + old_item = self.columns[column].pop(0) + self.graphics_scene.removeItem(old_item) + self.columns[column].append(text_item) + for ix, text_item in enumerate(self.columns[column]): + text_item.setPos(column * self.column_width, ix * self.line_height) def render(self): @@ -162,7 +173,7 @@ class OSCThread(threading.Thread): while self.running: try: - reads, writes, errs = select.select([self.osc_sock], [], [], 0.05) + reads, writes, errs = select.select([self.osc_sock], [], [], 0.01) except Exception, e: print "select error", e pass @@ -171,15 +182,14 @@ class OSCThread(threading.Thread): try: osc_input, address = self.osc_sock.recvfrom(8192) osc_address, typetags, messages = decode_osc(osc_input, 0, len(osc_input)) - print osc_address, typetags, messages if osc_address.find("ekg") != -1 or osc_address.find("plot") != -1: queue.put_nowait((osc_address, messages)) except Exception, e: print "recvfrom error", e else: - queue.put_nowait(("/bjoern/ekg", [0])) - queue.put_nowait(("/merle/ekg", [0])) - queue.put_nowait(("/uwe/ekg", [0])) + queue.put_nowait(("/bjoern/ekg", [random.randint(0,255)])) + queue.put_nowait(("/merle/ekg", [random.randint(0,255)])) + queue.put_nowait(("/uwe/ekg", [random.randint(0,255)])) self.unsubscribe_me() print "OSCThread is going down" @@ -209,7 +219,7 @@ class MyHandler(BaseHTTPRequestHandler): thread.daemon = True thread.start() window = MainWindow() - window.show() + window.hide() self.send_response(200) self.send_header("Content-Type", "multipart/x-mixed-replace; boundary=--aaboundary") @@ -222,7 +232,6 @@ class MyHandler(BaseHTTPRequestHandler): while 1: try: osc_address, args = queue.get_nowait() - print osc_address, args except Queue.Empty: break else: @@ -245,6 +254,7 @@ class MyHandler(BaseHTTPRequestHandler): JpegData = None buffer = None img = None + time.sleep(0.03) elif self.path.endswith(".jpeg"): directory = os.path.dirname(os.path.abspath(__file__)) From 7ac50d1e79b81ea36c3f9e1b390e8d1214288ed3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 17:58:50 +0200 Subject: [PATCH 04/10] done with this --- dump_grabber/dump_grabber/main.py | 4 +-- dump_grabber/setup.py | 50 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 2 deletions(-) create mode 100644 dump_grabber/setup.py diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index 300ab17..9eb649f 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -61,7 +61,7 @@ class MainWindow(KMainWindow, Ui_MainWindow): self.graphics_scene = QtGui.QGraphicsScene(self) self.graphics_scene.setSceneRect(0,0, 775, 580) self.graphics_view.setScene(self.graphics_scene) - self.default_font = QtGui.QFont("Monospace", 14) + self.default_font = QtGui.QFont("Monospace", 16) self.default_font.setStyleHint(QtGui.QFont.Monospace) self.default_font.setBold(True) self.blue_color = QtGui.QColor(47,147,235) @@ -291,7 +291,7 @@ class JustAHTTPServer(HTTPServer): def main(): - arg_parser = ArgParser("ekgplotter") + arg_parser = ArgParser("dump_grabber") arg_parser.add_global_group() client_group = arg_parser.add_client_group() arg_parser.add_argument(client_group, '-x', "--http_host", default="::", diff --git a/dump_grabber/setup.py b/dump_grabber/setup.py new file mode 100644 index 0000000..48cf6f7 --- /dev/null +++ b/dump_grabber/setup.py @@ -0,0 +1,50 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from distribute_setup import use_setuptools +use_setuptools() + +import sys +from setuptools import find_packages, setup + +if sys.version_info >= (3,): + extras['use_2to3'] = True + +setup( + name='dump_grabber', + version="0.1", + packages=find_packages(exclude=["scripts",]), + + include_package_data = True, + + exclude_package_data = {'': ['.gitignore']}, + + # installing unzipped + zip_safe = False, + + # predefined extension points, e.g. for plugins + entry_points = """ + [console_scripts] + dump_grabber = dump_grabber.main:main + """, + # pypi metadata + author = "Stefan Kögl", + + # FIXME: add author email + author_email = "", + description = "osc messages logging terminal as mjpeg stream, uses 3 columns", + + # FIXME: add long_description + long_description = """ + """, + + # FIXME: add license + license = "LGPL", + + # FIXME: add keywords + keywords = "", + + # FIXME: add download url + url = "", + test_suite='tests' +) From 28e0cc3bc10963b8d21e44a42ff77fc0594127de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 18:16:47 +0200 Subject: [PATCH 05/10] reduced cpu load from 104% with ffmpeg x11grab, ffserver and konsole to 32% with my implementation - yeah --- dump_grabber/dump_grabber/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index 9eb649f..3a47354 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -254,7 +254,7 @@ class MyHandler(BaseHTTPRequestHandler): JpegData = None buffer = None img = None - time.sleep(0.03) + time.sleep(0.05) elif self.path.endswith(".jpeg"): directory = os.path.dirname(os.path.abspath(__file__)) From f5352f247a4d4ebf0845d027f26e0a8974b65fd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 18:35:15 +0200 Subject: [PATCH 06/10] reduced cpu load --- ekgplotter/ekgplotter/main.py | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/ekgplotter/ekgplotter/main.py b/ekgplotter/ekgplotter/main.py index e4fc94c..98e7ce6 100644 --- a/ekgplotter/ekgplotter/main.py +++ b/ekgplotter/ekgplotter/main.py @@ -54,18 +54,12 @@ from pyqtgraph.widgets.PlotWidget import PlotWidget from chaosc.argparser_groups import * from chaosc.lib import resolve_host -try: - from chaosc.c_osc_lib import * -except ImportError: - from chaosc.osc_lib import * - - try: - from chaosc.c_osc_lib import decode_osc + from chaosc.c_osc_lib import OSCMessage, decode_osc except ImportError as e: print(e) - from chaosc.osc_lib import decode_osc + from chaosc.osc_lib import OSCMessage, decode_osc @@ -137,7 +131,7 @@ class OSCThread(threading.Thread): while self.running: try: - reads, writes, errs = select.select([self.osc_sock], [], [], 0.05) + reads, writes, errs = select.select([self.osc_sock], [], [], 0.01) except Exception, e: print "select error", e pass @@ -407,6 +401,7 @@ class MyHandler(BaseHTTPRequestHandler): #s = np.clip(dt*3., 0, 1) #fps = fps * (1-s) + (1.0/dt) * s #print '%0.2f fps' % fps + time.sleep(0.05) elif self.path.endswith(".jpeg"): directory = os.path.dirname(os.path.abspath(__file__)) From dcd8e49f8568f0078b4c4aaab442c88eb40ad15a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Wed, 23 Apr 2014 19:19:05 +0200 Subject: [PATCH 07/10] better --- dump_grabber/dump_grabber/main.py | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index 3a47354..4e875d8 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -61,7 +61,7 @@ class MainWindow(KMainWindow, Ui_MainWindow): self.graphics_scene = QtGui.QGraphicsScene(self) self.graphics_scene.setSceneRect(0,0, 775, 580) self.graphics_view.setScene(self.graphics_scene) - self.default_font = QtGui.QFont("Monospace", 16) + self.default_font = QtGui.QFont("Monospace", 14) self.default_font.setStyleHint(QtGui.QFont.Monospace) self.default_font.setBold(True) self.blue_color = QtGui.QColor(47,147,235) @@ -182,14 +182,11 @@ class OSCThread(threading.Thread): try: osc_input, address = self.osc_sock.recvfrom(8192) osc_address, typetags, messages = decode_osc(osc_input, 0, len(osc_input)) - if osc_address.find("ekg") != -1 or osc_address.find("plot") != -1: - queue.put_nowait((osc_address, messages)) + queue.put_nowait((osc_address, messages)) except Exception, e: print "recvfrom error", e else: - queue.put_nowait(("/bjoern/ekg", [random.randint(0,255)])) - queue.put_nowait(("/merle/ekg", [random.randint(0,255)])) - queue.put_nowait(("/uwe/ekg", [random.randint(0,255)])) + pass self.unsubscribe_me() print "OSCThread is going down" From 2837ab938908bcf6090fed0d6b1d8345bbd7480b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Thu, 24 Apr 2014 09:32:16 +0200 Subject: [PATCH 08/10] more init scripts --- config_files/dump_grabber | 21 +++++++++++++++++++++ config_files/ekgplotter | 21 +++++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100755 config_files/dump_grabber create mode 100755 config_files/ekgplotter diff --git a/config_files/dump_grabber b/config_files/dump_grabber new file mode 100755 index 0000000..287caeb --- /dev/null +++ b/config_files/dump_grabber @@ -0,0 +1,21 @@ +#!/sbin/runscript + +depend() { + need net + use dns localmount chaosc + after bootmisc + provide dump_grabber +} + + +start() { + ebegin "starting dump_grabber" + start-stop-daemon --start --pidfile /var/run/dump_grabber.pid --make-pidfile --user stefan --group stefan --background --exec env DISPLAY=:0 /usr/bin/dump_grabber + eend $? +} + +stop() { + ebegin "stopping dump_grabber" + start-stop-daemon --stop --quiet --pidfile /var/run/dump_grabber.pid + eend $? +} diff --git a/config_files/ekgplotter b/config_files/ekgplotter new file mode 100755 index 0000000..f53f3dd --- /dev/null +++ b/config_files/ekgplotter @@ -0,0 +1,21 @@ +#!/sbin/runscript + +depend() { + need net + use dns localmount chaosc + after bootmisc + provide ekgplotter +} + + +start() { + ebegin "starting ekgplotter" + start-stop-daemon --start --pidfile /var/run/ekgplotter.pid --make-pidfile --user stefan --group stefan --background --exec env DISPLAY=:0 /usr/bin/ekgplotter + eend $? +} + +stop() { + ebegin "stopping ekgplotter" + start-stop-daemon --stop --quiet --pidfile /var/run/ekgplotter.pid + eend $? +} From f3a8e8c4dd73d212d45c7abb757e3d2a19bd1ab6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Thu, 24 Apr 2014 09:33:43 +0200 Subject: [PATCH 09/10] cleaned up dump_grabber --- dump_grabber/dump_grabber/main.py | 125 +++++++++++++++++------------- 1 file changed, 70 insertions(+), 55 deletions(-) diff --git a/dump_grabber/dump_grabber/main.py b/dump_grabber/dump_grabber/main.py index 4e875d8..8a50453 100644 --- a/dump_grabber/dump_grabber/main.py +++ b/dump_grabber/dump_grabber/main.py @@ -2,44 +2,63 @@ # -*- coding: utf-8 -*- -import sys, os, random +# This file is part of chaosc and psychosis +# +# chaosc is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# chaosc is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with chaosc. If not, see . +# +# Copyright (C) 2014 Stefan Kögl -from PyQt4 import QtCore, QtGui -from PyQt4.QtCore import QBuffer, QByteArray, QIODevice +from __future__ import absolute_import -from dump_grabber_ui import Ui_MainWindow +import os + +from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from chaosc.argparser_groups import * +from chaosc.lib import logger, resolve_host +from collections import deque +from datetime import datetime +from dump_grabber.dump_grabber_ui import Ui_MainWindow +from os import curdir, sep from PyKDE4.kdecore import ki18n, KCmdLineArgs, KAboutData from PyKDE4.kdeui import KMainWindow, KApplication - -from datetime import datetime -import threading -import Queue -import traceback -import numpy as np -import string -import time -import random -import socket -import os.path -from os import curdir, sep -from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer +from PyQt4 import QtCore, QtGui +from PyQt4.QtCore import QBuffer, QByteArray, QIODevice from SocketServer import ThreadingMixIn, ForkingMixIn -import select + +import logging +import numpy as np + +import os.path +import Queue +import random import re - -from collections import deque - -from chaosc.argparser_groups import * -from chaosc.lib import resolve_host +import select +import socket +import string +import sys +import threading +import time +import traceback try: from chaosc.c_osc_lib import OSCMessage, decode_osc except ImportError as e: - print(e) from chaosc.osc_lib import OSCMessage, decode_osc + appName = "dump_grabber" catalog = "dump_grabber" programName = ki18n("dump_grabber") @@ -50,6 +69,11 @@ aboutData = KAboutData(appName, catalog, programName, version) KCmdLineArgs.init (sys.argv, aboutData) app = KApplication() + +fh = logging.FileHandler(os.path.expanduser("~/.chaosc/dump_grabber.log")) +fh.setLevel(logging.DEBUG) +logger.addHandler(fh) + class MainWindow(KMainWindow, Ui_MainWindow): def __init__(self, parent=None, columns=3): super(MainWindow, self).__init__(parent) @@ -70,7 +94,6 @@ class MainWindow(KMainWindow, Ui_MainWindow): self.num_lines = 775/self.line_height self.graphics_scene.setFont(self.default_font) - print "font", self.default_font.family(), self.default_font.pixelSize(), self.default_font.pointSize() self.brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) self.brush.setStyle(QtCore.Qt.SolidPattern) self.column_width = 775 / columns @@ -108,7 +131,7 @@ class MainWindow(KMainWindow, Ui_MainWindow): def render(self): - image = QtGui.QImage(768, 576, QtGui.QImage.Format_ARGB32_Premultiplied) + image = QtGui.QImage(768, 576, QtGui.QImage.Format_ARGB32) image.fill(QtCore.Qt.black) painter = QtGui.QPainter(image) #painter.setPen(QtCore.Qt.white) @@ -131,8 +154,7 @@ class OSCThread(threading.Thread): self.osc_sock.bind(self.client_address) self.osc_sock.setblocking(0) - print "%s: starting up osc receiver on '%s:%d'" % ( - datetime.now().strftime("%x %X"), self.client_address[0], self.client_address[1]) + logger.info("starting up osc receiver on '%s:%d'", self.client_address[0], self.client_address[1]) self.subscribe_me() @@ -148,7 +170,7 @@ class OSCThread(threading.Thread): :param token: token to get authorized for subscription :type token: str """ - print "%s: subscribing to '%s:%d' with label %r" % (datetime.now().strftime("%x %X"), self.chaosc_address[0], self.chaosc_address[1], self.args.subscriber_label) + logger.info("%s: subscribing to '%s:%d' with label %r", datetime.now().strftime("%x %X"), self.chaosc_address[0], self.chaosc_address[1], self.args.subscriber_label) msg = OSCMessage("/subscribe") msg.appendTypedArg(self.client_address[0], "s") msg.appendTypedArg(self.client_address[1], "i") @@ -162,7 +184,7 @@ class OSCThread(threading.Thread): if self.args.keep_subscribed: return - print "%s: unsubscribing from '%s:%d'" % (datetime.now().strftime("%x %X"), self.chaosc_address[0], self.chaosc_address[1]) + logger.info("unsubscribing from '%s:%d'", self.chaosc_address[0], self.chaosc_address[1]) msg = OSCMessage("/unsubscribe") msg.appendTypedArg(self.client_address[0], "s") msg.appendTypedArg(self.client_address[1], "i") @@ -175,7 +197,6 @@ class OSCThread(threading.Thread): try: reads, writes, errs = select.select([self.osc_sock], [], [], 0.01) except Exception, e: - print "select error", e pass else: if reads: @@ -184,12 +205,12 @@ class OSCThread(threading.Thread): osc_address, typetags, messages = decode_osc(osc_input, 0, len(osc_input)) queue.put_nowait((osc_address, messages)) except Exception, e: - print "recvfrom error", e + pass else: pass self.unsubscribe_me() - print "OSCThread is going down" + logger.info("OSCThread is going down") queue = Queue.Queue() @@ -242,8 +263,8 @@ class MyHandler(BaseHTTPRequestHandler): img = window.render() buffer = QBuffer() buffer.open(QIODevice.WriteOnly) - img.save(buffer, "JPG", 100) - img.save("/tmp/test.jpg", "JPG") + img.save(buffer, "JPG", 50) + img.save("/tmp/test.jpg", "JPG", 50) JpegData = buffer.data() self.wfile.write("--aaboundary\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData)) @@ -251,7 +272,7 @@ class MyHandler(BaseHTTPRequestHandler): JpegData = None buffer = None img = None - time.sleep(0.05) + time.sleep(0.06) elif self.path.endswith(".jpeg"): directory = os.path.dirname(os.path.abspath(__file__)) @@ -262,25 +283,26 @@ class MyHandler(BaseHTTPRequestHandler): self.wfile.write(data) return except (KeyboardInterrupt, SystemError): - print "queue size", queue.qsize() + #print "queue size", queue.qsize() if hasattr(self, "thread") and self.thread is not None: self.thread.running = False self.thread.join() self.thread = None except IOError, e: - print "ioerror", e, e[0] - print dir(e) + #print "ioerror", e, e[0] + #print dir(e) if e[0] in (32, 104): if hasattr(self, "thread") and self.thread is not None: self.thread.running = False self.thread.join() self.thread = None else: - print '-'*40 - print 'Exception happened during processing of request from' - traceback.print_exc() # XXX But this goes to stderr! - print '-'*40 - self.send_error(404,'File Not Found: %s' % self.path) + pass + #print '-'*40 + #print 'Exception happened during processing of request from' + #traceback.print_exc() # XXX But this goes to stderr! + #print '-'*40 + #self.send_error(404,'File Not Found: %s' % self.path) class JustAHTTPServer(HTTPServer): @@ -293,8 +315,8 @@ def main(): client_group = arg_parser.add_client_group() arg_parser.add_argument(client_group, '-x', "--http_host", default="::", help='my host, defaults to "::"') - arg_parser.add_argument(client_group, '-X', "--http_port", default=9000, - type=int, help='my port, defaults to 9000') + arg_parser.add_argument(client_group, '-X', "--http_port", default=9001, + type=int, help='my port, defaults to 9001') arg_parser.add_chaosc_group() arg_parser.add_subscriber_group() args = arg_parser.finalize() @@ -304,16 +326,9 @@ def main(): server = JustAHTTPServer((http_host, http_port), MyHandler) server.address_family = args.address_family server.args = args - print "%s: starting up http server on '%s:%d'" % ( - datetime.now().strftime("%x %X"), http_host, http_port) - - try: - server.serve_forever() - except KeyboardInterrupt: - print '^C received, shutting down server' - server.socket.close() - sys.exit(0) + logger.info("starting up http server on '%s:%d'", http_host, http_port) + server.serve_forever() if ( __name__ == '__main__' ): main() From 40ffb2e43d305d1d12ef99f0a844ab800a0aeecb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Stefan=20K=C3=B6gl?= Date: Thu, 24 Apr 2014 09:34:37 +0200 Subject: [PATCH 10/10] cleaned up ekgplotter --- ekgplotter/ekgplotter/main.py | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/ekgplotter/ekgplotter/main.py b/ekgplotter/ekgplotter/main.py index 98e7ce6..dbc1ba2 100644 --- a/ekgplotter/ekgplotter/main.py +++ b/ekgplotter/ekgplotter/main.py @@ -29,6 +29,7 @@ from datetime import datetime import threading import Queue import traceback +import logging import numpy as np import string import time @@ -52,9 +53,13 @@ import pyqtgraph as pg from pyqtgraph.widgets.PlotWidget import PlotWidget from chaosc.argparser_groups import * -from chaosc.lib import resolve_host +from chaosc.lib import logger, resolve_host +fh = logging.FileHandler(os.path.expanduser("~/.chaosc/ekgplotter.log")) +fh.setLevel(logging.DEBUG) +logger.addHandler(fh) + try: from chaosc.c_osc_lib import OSCMessage, decode_osc except ImportError as e: @@ -92,7 +97,7 @@ class OSCThread(threading.Thread): print "%s: starting up osc receiver on '%s:%d'" % ( datetime.now().strftime("%x %X"), self.client_address[0], self.client_address[1]) - self.subscribe_me() + #self.subscribe_me() def subscribe_me(self): """Use this procedure for a quick'n dirty subscription to your chaosc instance. @@ -140,16 +145,15 @@ class OSCThread(threading.Thread): try: osc_input, address = self.osc_sock.recvfrom(8192) osc_address, typetags, messages = decode_osc(osc_input, 0, len(osc_input)) - if osc_address.find("ekg") != -1 or osc_address.find("plot") != -1: - queue.put_nowait((osc_address, messages)) + queue.put_nowait((osc_address, messages)) except Exception, e: print "recvfrom error", e - else: - queue.put_nowait(("/bjoern/ekg", [0])) - queue.put_nowait(("/merle/ekg", [0])) - queue.put_nowait(("/uwe/ekg", [0])) + #else: + #queue.put_nowait(("/bjoern/ekg", [0])) + #queue.put_nowait(("/merle/ekg", [0])) + #queue.put_nowait(("/uwe/ekg", [0])) - self.unsubscribe_me() + #self.unsubscribe_me() print "OSCThread is going down" @@ -246,7 +250,7 @@ class EkgPlot(object): self.plot.showGrid(False, False) self.plot.setYRange(0, 255) self.plot.setXRange(0, num_data) - self.plot.resize(1280, 720) + self.plot.resize(768, 576) ba = self.plot.getAxis("bottom") bl = self.plot.getAxis("left") @@ -380,10 +384,12 @@ class MyHandler(BaseHTTPRequestHandler): plotter.update(osc_address, args[0]) exporter = pg.exporters.ImageExporter.ImageExporter(plotter.plot.plotItem) + exporter.parameters()['width'] = 768 img = exporter.export("tmpfile", True) buffer = QBuffer() buffer.open(QIODevice.WriteOnly) - img.save(buffer, "JPG", 100) + img.save(buffer, "JPG") + img.save("/tmp/test2.jpg", "JPG") JpegData = buffer.data() self.wfile.write("--aaboundary\r\nContent-Type: image/jpeg\r\nContent-length: %d\r\n\r\n%s\r\n\r\n\r\n" % (len(JpegData), JpegData))