Files @ b370618ce723
Branch filter:

Location: light9/bin/effecteval - annotation

Drew Perttula
split EffectNode out of effecteval
Ignore-this: 38003ca0e42aca8aedff2709e5f44f2b
e28a443bd153
e28a443bd153
b5ee7aa9341a
a38414bd3929
a38414bd3929
b370618ce723
be016cd5e5c5
e28a443bd153
e28a443bd153
b5ee7aa9341a
e28a443bd153
b370618ce723
a2081b9adfe4
b370618ce723
e28a443bd153
a38414bd3929
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
be016cd5e5c5
be016cd5e5c5
be016cd5e5c5
be016cd5e5c5
be016cd5e5c5
a2081b9adfe4
be016cd5e5c5
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
be016cd5e5c5
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
a38414bd3929
5939fce98fad
5939fce98fad
a38414bd3929
5939fce98fad
b5ee7aa9341a
5939fce98fad
a38414bd3929
a38414bd3929
a38414bd3929
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
5939fce98fad
5939fce98fad
5939fce98fad
5939fce98fad
b5ee7aa9341a
5939fce98fad
5939fce98fad
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
b5ee7aa9341a
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
b5ee7aa9341a
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
a2081b9adfe4
b5ee7aa9341a
b5ee7aa9341a
b5ee7aa9341a
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
aa45e5379c5a
aa45e5379c5a
aa45e5379c5a
be016cd5e5c5
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
a4632a7b2e17
a4632a7b2e17
a4632a7b2e17
e28a443bd153
5939fce98fad
a2081b9adfe4
5939fce98fad
e28a443bd153
aa45e5379c5a
aa45e5379c5a
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
e28a443bd153
#!bin/python
from run_local import log
from twisted.internet import reactor, task
from twisted.internet.defer import inlineCallbacks
import cyclone.web, cyclone.websocket, cyclone.httpclient
import sys, optparse, logging, subprocess, json, time, traceback
from rdflib import URIRef, Literal

sys.path.append(".")
from light9 import networking, showconfig, Submaster, dmxclient
from light9.rdfdb.syncedgraph import SyncedGraph
from light9.namespaces import L9, RDF, RDFS
from light9.rdfdb.patch import Patch
from light9.effecteval.effect import EffectNode

sys.path.append("/my/proj/homeauto/lib")
sys.path.append("/home/drewp/projects/homeauto/lib")
from cycloneerr import PrettyErrorHandler

class EffectEdit(cyclone.web.RequestHandler):
    def get(self):
        self.write(open("light9/effecteval/effect.html").read())

class SongEffects(PrettyErrorHandler, cyclone.web.RequestHandler):
    def post(self):
        song = URIRef(self.get_argument('uri'))
        drop = URIRef(self.get_argument('drop'))
        ctx = song
        now = time.time()
        effect = song + "/effect/e-%f" % now
        curve = song + "/curve/c-%f" % now

        with self.settings.graph.currentState(
                tripleFilter=(drop, RDFS.label, None)) as g:
            dropSubLabel = g.label(drop)
        
        self.settings.graph.patch(Patch(addQuads=[
            (song, L9['curve'], curve, ctx),
            (song, L9['effect'], effect, ctx),
            (effect, RDF.type, L9['Effect'], ctx),
            (effect, L9['code'],
             Literal('out = sub(%s, intensity=%s)' % (drop.n3(), curve.n3())),
             ctx),
            (curve, RDF.type, L9['Curve'], ctx),
            (curve, RDFS.label, Literal('sub %s' % dropSubLabel), ctx),
            (curve, L9['points'], Literal('0 0'), ctx),
            ]))
        
class SongEffectsUpdates(cyclone.websocket.WebSocketHandler):
    def connectionMade(self, *args, **kwargs):
        self.graph = self.settings.graph
        self.graph.addHandler(self.updateClient)
        
    def updateClient(self):
        # todo: abort if client is gone
        playlist = self.graph.value(showconfig.showUri(), L9['playList'])
        songs = list(self.graph.items(playlist))
        out = []
        for s in songs:
            out.append({'uri': s, 'label': self.graph.label(s)})
            out[-1]['effects'] = sorted(self.graph.objects(s, L9['effect']))
        self.sendMessage({'songs': out})
        
        
class EffectUpdates(cyclone.websocket.WebSocketHandler):
    """
    stays alive for the life of the effect page
    """
    def connectionMade(self, *args, **kwargs):
        log.info("websocket opened")
        self.uri = URIRef(self.get_argument('uri'))
        self.sendMessage({'hello': repr(self)})

        self.graph = self.settings.graph
        self.graph.addHandler(self.updateClient)

    def updateClient(self):
        # todo: if client has dropped, abort and don't get any more
        # graph updates
        self.sendMessage({'code': self.graph.value(self.uri, L9['code'])})
        
    def connectionLost(self, reason):
        log.info("websocket closed")

    def messageReceived(self, message):
        log.info("got message %s" % message)
        # write a patch back to the graph
        
        
class EffectEval(PrettyErrorHandler, cyclone.web.RequestHandler):
    @inlineCallbacks
    def get(self):
        # return dmx list for that effect
        uri = URIRef(self.get_argument('uri'))
        response = yield cyclone.httpclient.fetch(
            networking.musicPlayer.path('time'))
        songTime = json.loads(response.body)['t']

        node = EffectNode(self.settings.graph, uri)
        outSub = node.eval(songTime)
        self.write(json.dumps(outSub.get_dmx_list()))


# Completely not sure where the effect background loop should
# go. Another process could own it, and get this request repeatedly:
class SongEffectsEval(PrettyErrorHandler, cyclone.web.RequestHandler):
    def get(self):
        song = URIRef(self.get_argument('song'))
        effects = effectsForSong(self.settings.graph, song)
        raise NotImplementedError
        self.write(maxDict(effectDmxDict(e) for e in effects))
        # return dmx dict for all effects in the song, already combined

# Or, we could own that loop, like this:
@inlineCallbacks
def effectLoop(graph):
    t1 = time.time()
    try:
        response = json.loads((yield cyclone.httpclient.fetch(
            networking.musicPlayer.path('time'))).body)
        if response['song'] is not None:
            song = URIRef(response['song'])
            songTime = response['t']
            # Possibilities to make this shut up about graph copies:
            # - implement the cheap readonly currentState response
            # - do multiple little currentState calls (in this code) over just
            #   the required triples
            # - use addHandler instead and only fire dmx when there is a data
            #   change (and also somehow call it when there is a time change)

            outSubs = []
            with graph.currentState(tripleFilter=(song, L9['effect'], None)) as g:
                for effectUri in g.objects(song, L9['effect']):
                    # these should be built once, not per (frequent) update
                    node = EffectNode(graph, effectUri)
                    outSubs.append(node.eval(songTime))
                out = Submaster.sub_maxes(*outSubs)
                # out.get_levels() for a more readable view
                dmx = out.get_dmx_list()

                if log.isEnabledFor(logging.DEBUG):
                    log.debug("send dmx: %r", out.get_levels())
                yield dmxclient.outputlevels(dmx, twisted=True)
    except Exception:
        traceback.print_exc()
        time.sleep(1)
        
    loopTime = time.time() - t1
    log.debug('loopTime %.1f ms', 1000 * loopTime)
    
class App(object):
    def __init__(self, show):
        self.show = show
        self.graph = SyncedGraph("effectEval")
        self.graph.initiallySynced.addCallback(self.launch)

    def launch(self, *args):
        task.LoopingCall(effectLoop, self.graph).start(.3)    
        SFH = cyclone.web.StaticFileHandler
        self.cycloneApp = cyclone.web.Application(handlers=[
            (r'/()', SFH,
             {'path': 'light9/effecteval', 'default_filename': 'index.html'}),
            (r'/effect', EffectEdit),
            (r'/(websocket\.js)', SFH, {'path': 'light9/rdfdb/web/'}),
            (r'/effect\.js', StaticCoffee, {'src': 'light9/effecteval/effect.coffee'}),
            (r'/index\.js', StaticCoffee, {'src': 'light9/effecteval/index.coffee'}),
            (r'/effectUpdates', EffectUpdates),
            (r'/songEffectsUpdates', SongEffectsUpdates),
            (r'/static/(.*)', SFH, {'path': 'static/'}),
            (r'/effect/eval', EffectEval),
            (r'/songEffects', SongEffects),
            (r'/songEffects/eval', SongEffectsEval),
        ], debug=True, graph=self.graph)
        reactor.listenTCP(networking.effectEval.port, self.cycloneApp)
        log.info("listening on %s" % networking.effectEval.port)

class StaticCoffee(PrettyErrorHandler, cyclone.web.RequestHandler):
    def initialize(self, src):
        super(StaticCoffee, self).initialize()
        self.src = src
    def get(self):
        self.set_header('Content-Type', 'application/javascript')
        self.write(subprocess.check_output([
            '/usr/bin/coffee', '--compile', '--print', self.src]))

        
if __name__ == "__main__":
    parser = optparse.OptionParser()
    parser.add_option('--show',
        help='show URI, like http://light9.bigasterisk.com/show/dance2008',
                      default=showconfig.showUri())
    parser.add_option("-v", "--verbose", action="store_true",
                      help="logging.DEBUG")
    parser.add_option("--twistedlog", action="store_true",
                      help="twisted logging")
    (options, args) = parser.parse_args()

    log.setLevel(logging.DEBUG if options.verbose else logging.INFO)

    if not options.show:
        raise ValueError("missing --show http://...")
            
    app = App(URIRef(options.show))
    if options.twistedlog:
        from twisted.python import log as twlog
        twlog.startLogging(sys.stderr)
    reactor.run()