Changeset - bee1c0747242
[Not reviewed]
default
0 7 0
Drew Perttula - 6 years ago 2019-05-27 10:46:29
drewp@bigasterisk.com
switch from cyclone.httpclient to treq everywhere
Ignore-this: 60dbd235b745a1198b14c90be9d4abe2
7 files changed with 50 insertions and 40 deletions:
0 comments (0 inline, 0 general)
light9/curvecalc/curveedit.py
Show inline comments
 
"""
 
this may be split out from curvecalc someday, since it doesn't
 
need to be tied to a gui """
 
import cgi
 
from twisted.internet import reactor
 
import cyclone.web, cyclone.httpclient, cyclone.websocket
 

	
 
from louie import dispatcher
 
from rdflib import URIRef
 
from twisted.internet import reactor
 
import cyclone.web
 

	
 
from cycloneerr import PrettyErrorHandler
 
from louie import dispatcher
 

	
 

	
 
def serveCurveEdit(port, hoverTimeResponse, curveset):
 
    """
 
    /hoverTime requests actually are handled by the curvecalc gui
 
    """
 
    curveEdit = CurveEdit(curveset)
 

	
 
    class HoverTime(PrettyErrorHandler, cyclone.web.RequestHandler):
 

	
 
        def get(self):
 
            hoverTimeResponse(self)
light9/effect/edit.py
Show inline comments
 
import json
 
import cyclone.httpclient
 
from rdflib import URIRef, Literal
 
from twisted.internet.defer import inlineCallbacks, returnValue
 
from rdflib import URIRef, Literal
 
import treq
 

	
 
from light9 import networking
 
from light9.curvecalc.curve import CurveResource
 
from light9.namespaces import L9, RDF, RDFS
 
from rdfdb.patch import Patch
 
from light9.curvecalc.curve import CurveResource
 

	
 

	
 
def clamp(x, lo, hi):
 
    return max(lo, min(hi, x))
 

	
 

	
 
@inlineCallbacks
 
def getMusicStatus():
 
    returnValue(
 
        json.loads(
 
            (yield cyclone.httpclient.fetch(networking.musicPlayer.path('time'),
 
                                            timeout=.5)).body))
 
    resp = yield treq.get(networking.musicPlayer.path('time'), timeout=.5)
 
    body = yield resp.json_content()
 
    returnValue(body)
 

	
 

	
 
@inlineCallbacks
 
def songEffectPatch(graph, dropped, song, event, ctx):
 
    """
 
    some uri was 'dropped' in the curvecalc timeline. event is 'default' or 'start' or 'end'.
 
    """
 
    with graph.currentState(tripleFilter=(dropped, None, None)) as g:
 
        droppedTypes = list(g.objects(dropped, RDF.type))
 
        droppedLabel = g.label(dropped)
 
        droppedCodes = list(g.objects(dropped, L9['code']))
 

	
light9/effecteval/effectloop.py
Show inline comments
 
import time, json, logging, traceback
 
import numpy
 
import serial
 
import time, logging, traceback
 

	
 
from rdflib import URIRef
 
from twisted.internet import reactor
 
from twisted.internet.defer import inlineCallbacks, returnValue, succeed
 
from twisted.internet.error import TimeoutError
 
from rdflib import URIRef
 
import cyclone.httpclient
 
from light9.namespaces import L9, RDF
 
from light9.effecteval.effect import EffectNode
 
import numpy
 
import serial
 
import treq
 

	
 
from light9 import Effects
 
from light9 import networking
 
from light9 import Submaster
 
from light9 import dmxclient
 
from light9 import networking
 
from light9.effecteval.effect import EffectNode
 
from light9.namespaces import L9, RDF
 

	
 
log = logging.getLogger('effectloop')
 

	
 

	
 
class EffectLoop(object):
 
    """maintains a collection of the current EffectNodes, gets time from
 
    music player, sends dmx"""
 

	
 
    def __init__(self, graph, stats):
 
        self.graph, self.stats = graph, stats
 
        self.currentSong = None
 
        self.currentEffects = [
 
        ]  # EffectNodes for the current song plus the submaster ones
 
@@ -57,26 +60,26 @@ class EffectLoop(object):
 
        for sub in self.graph.subjects(RDF.type, L9['Submaster']):
 
            for effectUri in self.graph.objects(sub, L9['drivesEffect']):
 
                self.currentEffects.append(EffectNode(self.graph, effectUri))
 

	
 
        log.info('now we have %s effects', len(self.currentEffects))
 

	
 
    @inlineCallbacks
 
    def getSongTime(self):
 
        now = time.time()
 
        old = now - self.requestTime
 
        if old > self.coastSecs:
 
            try:
 
                response = json.loads((yield cyclone.httpclient.fetch(
 
                    networking.musicPlayer.path('time'), timeout=.5)).body)
 
                r = yield treq.get(networking.musicPlayer.path('time'), timeout=.5)
 
                response = yield r.json_content()
 
            except TimeoutError:
 
                log.warning("TimeoutError: using stale time from %.1f ago", old)
 
            else:
 
                self.requestTime = now
 
                self.currentPlaying = response['playing']
 
                self.songTimeFromRequest = response['t']
 
                returnValue((response['t'], (response['song'] and
 
                                             URIRef(response['song']))))
 

	
 
        estimated = self.songTimeFromRequest
 
        if self.currentSong is not None and self.currentPlaying:
 
            estimated += now - self.requestTime
light9/greplin_cyclone.py
Show inline comments
 
import cyclone.web, cyclone.websocket, cyclone.httpclient
 
import cyclone.web
 

	
 
import greplin.scales.twistedweb, greplin.scales.formats
 
from greplin import scales
 

	
 

	
 
# Like scales.twistedweb.StatsResource, but modified for cyclone. May
 
# be missing features.
 
class StatsForCyclone(cyclone.web.RequestHandler):
 

	
 
    def get(self):
 
        parts = []
 
        statDict = greplin.scales.twistedweb.util.lookup(
light9/networking.py
Show inline comments
 
from urllib.parse import urlparse
 

	
 
from rdflib import URIRef
 
from urllib.parse import urlparse
 

	
 
from .showconfig import getGraph, showUri
 
from .namespaces import L9
 

	
 

	
 
class ServiceAddress(object):
 

	
 
    def __init__(self, service):
 
        self.service = service
 

	
 
    def _url(self) -> URIRef:
 
        graph = getGraph()
 
        net = graph.value(showUri(), L9['networking'])
 
@@ -24,26 +26,26 @@ class ServiceAddress(object):
 
        return urlparse(self._url()).port
 

	
 
    @property
 
    def host(self):
 
        return urlparse(self._url()).hostname
 

	
 
    @property
 
    def url(self) -> URIRef:
 
        return self._url()
 

	
 
    value = url
 

	
 
    def path(self, more):
 
        return self.url + str(more)
 
    def path(self, more: str) -> URIRef:
 
        return URIRef(self.url + more)
 

	
 

	
 
captureDevice = ServiceAddress(L9['captureDevice'])
 
curveCalc = ServiceAddress(L9['curveCalc'])
 
dmxServer = ServiceAddress(L9['dmxServer'])
 
dmxServerZmq = ServiceAddress(L9['dmxServerZmq'])
 
collector = ServiceAddress(L9['collector'])
 
collectorZmq = ServiceAddress(L9['collectorZmq'])
 
effectEval = ServiceAddress(L9['effectEval'])
 
effectSequencer = ServiceAddress(L9['effectSequencer'])
 
keyboardComposer = ServiceAddress(L9['keyboardComposer'])
 
musicPlayer = ServiceAddress(L9['musicPlayer'])
light9/subcomposer/subcomposerweb.py
Show inline comments
 
import logging
 
import cyclone.web, cyclone.websocket, cyclone.httpclient
 

	
 
from rdflib import URIRef, Literal
 
from twisted.internet import reactor
 
import cyclone.web
 

	
 
from cycloneerr import PrettyErrorHandler
 
from light9 import networking
 
from rdflib import URIRef, Literal
 
from twisted.internet import reactor
 

	
 
log = logging.getLogger('web')
 

	
 

	
 
def init(graph, session, currentSub):
 
    SFH = cyclone.web.StaticFileHandler
 
    app = cyclone.web.Application(handlers=[
 
        (r'/()', SFH, {
 
            'path': 'light9/subcomposer',
 
            'default_filename': 'index.html'
 
        }),
 
        (r'/toggle', Toggle),
 
    ],
light9/vidref/musictime.py
Show inline comments
 
import time, json, logging
 
from light9 import networking
 
from typing import Dict
 

	
 
from twisted.internet import reactor
 
from cyclone.httpclient import fetch
 
from typing import Dict
 
import treq
 

	
 
from light9 import networking
 

	
 
log = logging.getLogger()
 

	
 

	
 
class MusicTime(object):
 
    """
 
    fetch times from ascoltami in a background thread; return times
 
    upon request, adjusted to be more precise with the system clock
 
    """
 

	
 
    def __init__(self,
 
                 period=.2,
 
                 onChange=lambda position: None,
 
@@ -71,25 +74,25 @@ class MusicTime(object):
 
            # fraction of the way through)
 
            self.positionFetchTime = time.time()
 

	
 
            self.position = position
 
            self.onChange(position)
 

	
 
            reactor.callLater(self.period, self.pollMusicTime)
 

	
 
        def eb(err):
 
            log.warn("talking to ascoltami: %s", err.getErrorMessage())
 
            reactor.callLater(2, self.pollMusicTime)
 

	
 
        d = fetch(networking.musicPlayer.path("time"))
 
        d = treq.get(networking.musicPlayer.path("time").toPython())
 
        d.addCallback(cb)
 
        d.addErrback(eb)  # note this includes errors in cb()
 

	
 
    def pollCurvecalcTime(self):
 
        """
 
        poll the curvecalc position when music isn't playing, so replay
 
        can track it.
 

	
 
        This would be better done via rdfdb sync, where changes to the
 
        curvecalc position are written to the curvecalc session and we
 
        can pick them up in here
 
        """
 
@@ -108,26 +111,25 @@ class MusicTime(object):
 
            if response.code != 200:
 
                raise ValueError("%s %s" % (response.code, response.body))
 
            self.lastHoverTime = json.loads(response.body)['hoverTime']
 

	
 
            reactor.callLater(self.hoverPeriod, self.pollCurvecalcTime)
 

	
 
        def eb(err):
 
            if self.lastHoverTime:
 
                log.warn("talking to curveCalc: %s", err.getErrorMessage())
 
            self.lastHoverTime = None
 
            reactor.callLater(2, self.pollCurvecalcTime)
 

	
 
        d = fetch(networking.curveCalc.path("hoverTime"))
 
        d = treq.get(networking.curveCalc.path("hoverTime"))
 
        d.addCallback(cb)
 
        d.addErrback(eb)  # note this includes errors in cb()
 

	
 
    def sendTime(self, t):
 
        """request that the player go to this time"""
 
        fetch(
 
            method=b'POST',
 
            url=networking.musicPlayer.path('time'),
 
            postdata=json.dumps({
 
                "t": t
 
            }).encode('utf8'),
 
            headers={b"content-type": [b"application/json"]},
 
        treq.post(networking.musicPlayer.path('time'),
 
                  data=json.dumps({
 
                      "t": time
 
                  }).encode('utf8'),
 
                  headers={b"content-type": [b"application/json"]},
 
        )
 
        
0 comments (0 inline, 0 general)