Changeset - 5037fa2c9983
[Not reviewed]
default
0 2 0
drewp@bigasterisk.com - 15 years ago 2010-06-19 22:24:39
drewp@bigasterisk.com
fix how KC reads its graphs. switch to logging lib and add -v flag
Ignore-this: f16eb2408c6a56c41e086567c749b64a
2 files changed with 22 insertions and 12 deletions:
0 comments (0 inline, 0 general)
bin/keyboardcomposer
Show inline comments
 
#!/usr/bin/python
 

	
 
from __future__ import division, nested_scopes
 
import cgi, os, sys, time, subprocess
 
import cgi, os, sys, time, subprocess, logging
 
from optparse import OptionParser
 
import webcolors, colorsys
 

	
 
from twisted.internet import reactor, tksupport
 
from twisted.web import xmlrpc, server, resource
 
from Tix import *
 
import Tix as tk
 
import pickle
 

	
 
import run_local
 
from light9.Fadable import Fadable
 
from light9.Submaster import Submasters, sub_maxes
 
@@ -435,28 +435,31 @@ class Sliders(BCF2000):
 
            else:
 
                return
 

	
 
            kc.change_row(kc.current_row + diff)
 
            self.valueOut(name, 0)
 

	
 
if __name__ == "__main__":
 
    parser = OptionParser()
 
    parser.add_option('--nonpersistent', action="store_true",
 
                      help="don't load or save levels")
 
    parser.add_option('--no-sliders', action='store_true',
 
                      help="don't attach to hardware sliders")
 
    parser.add_option('-v', action='store_true', help="log info level")
 
    opts, args = parser.parse_args()
 

	
 
    logging.basicConfig(level=logging.INFO if opts.v else logging.WARN)
 
    log = logging.getLogger()
 

	
 
    graph = showconfig.getGraph()
 
    
 
    s = Submasters(graph)
 

	
 
    root = Tk()
 
    tl = toplevelat("Keyboard Composer", existingtoplevel=root)
 

	
 
    startLevels = None
 
    if opts.nonpersistent:
 
        startLevels = {}
 
    kc = KeyboardComposer(tl, graph, s, startLevels,
 
                          hw_sliders=not opts.no_sliders)
 
    kc.pack(fill=BOTH, expand=1)
 

	
light9/Submaster.py
Show inline comments
 
from __future__ import division
 
import os
 
import os, logging
 
from rdflib.Graph import Graph
 
from rdflib import RDFS, Literal, BNode
 
from light9.namespaces import L9, XSD
 
from light9.TLUtility import dict_scale, dict_max
 
from light9 import Patch, showconfig
 
try:
 
    import dispatch.dispatcher as dispatcher
 
except ImportError:
 
    from louie import dispatcher
 
log = logging.getLogger()
 

	
 
class Submaster:
 
    "Contain a dictionary of levels, but you didn't need to know that"
 
    def __init__(self,
 
                 name=None,
 
                 graph=None, sub=None,
 
                 leveldict=None, temporary=False):
 
        """sub is the URI for this submaster, graph is a graph where
 
        we can learn about the sub. If graph is not provided, we look
 
        in a file named name.
 

	
 
        name is the filename where we can load a graph about this URI
 
@@ -46,62 +47,68 @@ class Submaster:
 
            assert isinstance(graph, Graph)
 
        self.name = name
 
        self.uri = sub
 
        self.graph = graph
 
        self.temporary = temporary
 
        if leveldict:
 
            self.levels = leveldict
 
        else:
 
            self.levels = {}
 
            self.reload(quiet=True, graph=graph)
 
        if not self.temporary:
 
            dispatcher.connect(self.reload, 'reload all subs')
 
        log.info("%s initial levels %s", self.name, self.levels)
 
            
 
    def reload(self, quiet=False, graph=None):
 
        if self.temporary:
 
            return
 
        try:
 
            oldlevels = self.levels.copy()
 
            self.levels.clear()
 
            patchGraph = showconfig.getGraph()
 
            if graph is None:
 
            if 1 or graph is None:
 
                # need to read the sub graph to build the levels, not
 
                # use the main one! The sub graphs will eventually
 
                # just be part of the one and only shared graph
 
                graph = Graph()
 
                graph.parse(showconfig.subFile(self.name), format="n3")
 
                inFile = showconfig.subFile(self.name)
 
                log.info("reading %s", inFile)
 
                graph.parse(inFile, format="n3")
 
            self.uri = L9['sub/%s' % self.name]
 
            for lev in graph.objects(self.uri, L9['lightLevel']):
 
                chan = graph.value(lev, L9['channel'])
 
                val = graph.value(lev, L9['level'])
 
                name = patchGraph.label(chan)
 
                if not name:
 
                    print "sub %r has channel %r with no name- leaving out that channel" % (self.name, chan)
 
                    log.error("sub %r has channel %r with no name- leaving out that channel" % (self.name, chan))
 
                    continue
 
                self.levels[name] = float(val)
 

	
 
            if (not quiet) and (oldlevels != self.levels):
 
                print "sub %s changed" % self.name
 
                log.info("sub %s changed" % self.name)
 
        except IOError, e:
 
            print "Can't read file for sub: %r (%s)" % (self.name, e)
 
            log.error("Can't read file for sub: %r (%s)" % (self.name, e))
 
    def save(self):
 
        if self.temporary:
 
            print "not saving temporary sub named",self.name
 
            log.info("not saving temporary sub named %s",self.name)
 
            return
 

	
 
        graph = Graph()
 
        subUri = L9['sub/%s' % self.name]
 
        graph.add((subUri, RDFS.label, Literal(self.name)))
 
        for chan in self.levels.keys():
 
            try:
 
                chanUri = Patch.get_channel_uri(chan)
 
            except KeyError:
 
                print "saving dmx channels with no :Channel node is not supported yet. Give channel %s a URI for it to be saved. Omitting this channel from the sub." % chan
 
                log.error("saving dmx channels with no :Channel node is not supported yet. Give channel %s a URI for it to be saved. Omitting this channel from the sub." % chan)
 
                continue
 
            lev = BNode()
 
            graph.add((subUri, L9['lightLevel'], lev))
 
            graph.add((lev, L9['channel'], chanUri))
 
            graph.add((lev, L9['level'],
 
                       Literal(self.levels[chan], datatype=XSD['decimal'])))
 

	
 
        graph.serialize(showconfig.subFile(self.name), format="nt")
 

	
 
    def set_level(self, channelname, level, save=True):
 
        self.levels[Patch.resolve_name(channelname)] = level
 
        if save:
 
@@ -132,25 +139,25 @@ class Submaster:
 
        levels = ' '.join(["%s:%.2f" % item for item in items])
 
        return "<'%s': [%s]>" % (self.name, levels)
 
    def get_dmx_list(self):
 
        leveldict = self.get_levels() # gets levels of sub contents
 

	
 
        levels = []
 
        for k, v in leveldict.items():
 
            if v == 0:
 
                continue
 
            try:
 
                dmxchan = Patch.get_dmx_channel(k) - 1
 
            except ValueError:
 
                print "error trying to compute dmx levels for submaster %s" % self.name
 
                log.error("error trying to compute dmx levels for submaster %s" % self.name)
 
                raise
 
            if dmxchan >= len(levels):
 
                levels.extend([0] * (dmxchan - len(levels) + 1))
 
            levels[dmxchan] = max(v, levels[dmxchan])
 

	
 
        return levels
 
    def normalize_patch_names(self):
 
        """Use only the primary patch names."""
 
        # possibly busted -- don't use unless you know what you're doing
 
        self.set_all_levels(self.levels.copy())
 
    def get_normalized_copy(self):
 
        """Get a copy of this sumbaster that only uses the primary patch 
 
@@ -218,25 +225,25 @@ class Submasters:
 
    "Collection o' Submaster objects"
 
    def __init__(self, graph):
 
        self.submasters = {}
 

	
 
        files = os.listdir(showconfig.subsDir())
 

	
 
        for filename in files:
 
            # we don't want these files
 
            if filename.startswith('.') or filename.endswith('~') or \
 
               filename.startswith('CVS'):
 
                continue
 
            self.submasters[filename] = Submaster(filename, graph=graph)
 
        print "loaded subs", self.submasters
 
        log.info("loaded subs %s", self.submasters)
 
    def get_all_subs(self):
 
        "All Submaster objects"
 
        l = self.submasters.items()
 
        l.sort()
 
        l = [x[1] for x in l]
 
        songs = []
 
        notsongs = []
 
        for s in l:
 
            if s.name.startswith('song'):
 
                songs.append(s)
 
            else:
 
                notsongs.append(s)
0 comments (0 inline, 0 general)