Files
@ 54027815c6cc
Branch filter:
Location: light9/bin/effecteval
54027815c6cc
6.1 KiB
text/plain
rdfdb can return 'application/n-quads' response
Ignore-this: 3ab9cdd77f1c088af031c714b3ca2804
Ignore-this: 3ab9cdd77f1c088af031c714b3ca2804
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 | #!bin/python
from run_local import log
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
import cyclone.web, cyclone.websocket, cyclone.httpclient
import sys, optparse, logging, subprocess, json, re
from rdflib import URIRef, RDF
sys.path.append(".")
from light9 import networking, showconfig, Submaster
from light9.rdfdb.syncedgraph import SyncedGraph
from light9.curvecalc.curve import Curve
from light9.namespaces import L9, DCTERMS
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 EffectData(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
def uriFromCode(s):
# i thought this was something a graph could do with its namespace manager
if s.startswith('sub:'):
return URIRef('http://light9.bigasterisk.com/show/dance2014/sub/' + s[4:])
if s.startswith('song1:'):
return URIRef('http://ex/effect/song1/' + s[6:])
raise NotImplementedError
class EffectNode(object):
def __init__(self, graph, uri):
self.graph, self.uri = graph, uri
def eval(self, songTime):
with self.graph.currentState(tripleFilter=(self.uri, L9['code'], None)) as g:
code = g.value(self.uri, L9['code'])
# consider http://waxeye.org/ for a parser that can be used in py and js
m = re.match(r'^out = sub\((.*?), intensity=(.*?)\)', code)
if not m:
raise NotImplementedError
sub = uriFromCurie(m.group(1))
intensityCurve = uriFromCurie(m.group(2))
print vars()
def effectDmxDict(graph, effect, songTime):
subs = Submaster.get_global_submasters(graph)
curve = URIRef("http://ex/effect/song1/opening")
c = Curve()
with graph.currentState(tripleFilter=(curve, None, None)) as g:
c.set_from_string(g.value(curve, L9['points']))
with graph.currentState(tripleFilter=(effect, None, None)) as g:
print 'got code', g.value(effect, L9['code'])
en = EffectNode(graph, effect)
en.eval(songTime)
sub = subs.get_sub_by_uri(URIRef("http://light9.bigasterisk.com/show/dance2014/sub/stageleft"))
level = c.eval(songTime)
scaledSubs = [sub * level]
out = Submaster.sub_maxes(*scaledSubs)
levels_dict = out.get_levels()
dmx = out.get_dmx_list()
return json.dumps(dmx)
class EffectEval(PrettyErrorHandler, cyclone.web.RequestHandler):
@inlineCallbacks
def get(self):
# return dmx dict for that effect
uri = URIRef(self.get_argument('uri'))
response = yield cyclone.httpclient.fetch(
networking.musicPlayer.path('time'))
songTime = json.loads(response.body)['t']
self.write(effectDmxDict(self.settings.graph, uri, songTime))
class SongEffectsEval(PrettyErrorHandler, cyclone.web.RequestHandler):
def get(self):
song = URIRef(self.get_argument('song'))
effects = effectsForSong(self.settings.graph, song)
self.write(maxDict(effectDmxDict(e) for e in effects))
# return dmx dict for all effects in the song, already combined
class App(object):
def __init__(self, show):
self.show = show
self.graph = SyncedGraph("effectEval")
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'/(knockout-2\.2\.1\.js)', SFH, {'path': 'light9/subserver/'}),
(r'/effect\.js', StaticCoffee, {'src': 'light9/effecteval/effect.coffee'}),
(r'/effectData', EffectData),
(r'/static/(.*)', SFH, {'path': 'static/'}),
(r'/effect/eval', EffectEval),
(r'/songEffects/eval', SongEffectsEval),
], debug=True, graph=self.graph)
#graph.initiallySynced.addCallback(
# see bin/subserver
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.listenTCP(networking.effectEval.port, app.cycloneApp)
log.info("listening on %s" % networking.effectEval.port)
reactor.run()
|