Files
@ 191387547a53
Branch filter:
Location: light9/light9/collector/collector.py
191387547a53
9.0 KiB
text/x-python
checkpoint show data
Ignore-this: 5c0a3ede6404976c11c28d27f24340d7
Ignore-this: 5c0a3ede6404976c11c28d27f24340d7
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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 | import time
import logging
from typing import cast, List, Dict, Tuple, Optional, Set
from rdflib import Graph, Literal
from light9.collector.device import toOutputAttrs, resolve
from light9.collector.output import Output as OutputInstance
from light9.collector.weblisteners import WebListeners
from light9.namespaces import L9, RDF
from rdfdb.syncedgraph import SyncedGraph
from light9.newtypes import ClientType, ClientSessionType, OutputUri, DeviceUri, DeviceClass, DmxIndex, DmxMessageIndex, DeviceAttr, OutputAttr, OutputValue, UnixTime, OutputRange
log = logging.getLogger('collector')
def outputMap(
graph: Graph, outputs: List[OutputInstance]
) -> Dict[Tuple[DeviceUri, OutputAttr], Tuple[OutputInstance, DmxMessageIndex]]:
"""From rdf config graph, compute a map of
(device, outputattr) : (output, index)
that explains which output index to set for any device update.
"""
ret = {}
outputByUri: Dict[OutputUri, OutputInstance] = {}
for out in outputs:
outputByUri[OutputUri(out.uri)] = out
for dc in graph.subjects(RDF.type, L9['DeviceClass']):
log.info('mapping DeviceClass %s', dc)
for dev in graph.subjects(RDF.type, dc):
dev = cast(DeviceUri, dev)
log.info(' mapping device %s', dev)
universe = cast(OutputUri, graph.value(dev, L9['dmxUniverse']))
try:
output = outputByUri[universe]
except Exception:
log.warn('dev %r :dmxUniverse %r', dev, universe)
raise
dmxBase = DmxIndex(
cast(Literal, graph.value(dev, L9['dmxBase'])).toPython())
for row in graph.objects(dc, L9['attr']):
outputAttr = cast(OutputAttr,
graph.value(row, L9['outputAttr']))
offset = DmxIndex(
cast(Literal, graph.value(row, L9['dmxOffset'])).toPython())
index = DmxMessageIndex(dmxBase + offset - 1)
ret[(dev, outputAttr)] = (output, index)
log.debug(' map %s to %s,%s', outputAttr, output, index)
return ret
class Collector:
def __init__(self,
graph: SyncedGraph,
outputs: List[OutputInstance],
listeners: Optional[WebListeners] = None,
clientTimeoutSec: float = 10):
self.graph = graph
self.outputs = outputs
self.listeners = listeners
self.clientTimeoutSec = clientTimeoutSec
self.initTime = time.time()
self.allDevices: Set[DeviceUri] = set()
self.graph.addHandler(self.rebuildOutputMap)
# client : (session, time, {(dev,devattr): latestValue})
self.lastRequest: Dict[Tuple[ClientType, ClientSessionType], Tuple[
UnixTime, Dict[Tuple[DeviceUri, DeviceAttr], float]]] = {}
# (dev, devAttr): value to use instead of 0
self.stickyAttrs: Dict[Tuple[DeviceUri, DeviceAttr], float] = {}
def rebuildOutputMap(self):
self.outputMap = outputMap(self.graph, self.outputs)
self.deviceType: Dict[DeviceUri, DeviceClass] = {}
self.remapOut: Dict[Tuple[DeviceUri, DeviceAttr], OutputRange] = {}
for dc in self.graph.subjects(RDF.type, L9['DeviceClass']):
for dev in map(DeviceUri, self.graph.subjects(RDF.type, dc)):
self.allDevices.add(dev)
self.deviceType[dev] = dc
for remap in self.graph.objects(dev, L9['outputAttrRange']):
attr = OutputAttr(self.graph.value(remap, L9['outputAttr']))
start = cast(Literal,
self.graph.value(remap,
L9['start'])).toPython()
end = cast(Literal, self.graph.value(remap,
L9['end'])).toPython()
self.remapOut[(dev, attr)] = OutputRange((start, end))
def _forgetStaleClients(self, now):
# type: (float) -> None
staleClientSessions = []
for c, (t, _) in self.lastRequest.items():
if t < now - self.clientTimeoutSec:
staleClientSessions.append(c)
for c in staleClientSessions:
log.info('forgetting stale client %r', c)
del self.lastRequest[c]
# todo: move to settings.py
def resolvedSettingsDict(
self, settingsList: List[Tuple[DeviceUri, DeviceAttr, float]]
) -> Dict[Tuple[DeviceUri, DeviceAttr], float]:
out: Dict[Tuple[DeviceUri, DeviceAttr], float] = {}
for d, da, v in settingsList:
if (d, da) in out:
out[(d, da)] = resolve(d, da, [out[(d, da)], v])
else:
out[(d, da)] = v
return out
def _warnOnLateRequests(self, client, now, sendTime):
requestLag = now - sendTime
if requestLag > .1 and now > self.initTime + 10 and getattr(
self, '_lastWarnTime', 0) < now - 3:
self._lastWarnTime = now
log.warn(
'collector.setAttrs from %s is running %.1fms after the request was made',
client, requestLag * 1000)
def _merge(self, lastRequests):
deviceAttrs: Dict[DeviceUri, Dict[DeviceAttr, float]] = {
} # device: {deviceAttr: value}
for _, lastSettings in lastRequests:
for (device, deviceAttr), value in lastSettings.items():
if (device, deviceAttr) in self.remapOut:
start, end = self.remapOut[(device, deviceAttr)]
value = Literal(start + float(value) * (end - start))
attrs = deviceAttrs.setdefault(device, {})
if deviceAttr in attrs:
value = resolve(device, deviceAttr,
[attrs[deviceAttr], value])
attrs[deviceAttr] = value
# list should come from the graph. these are attrs
# that should default to holding the last position,
# not going to 0.
if deviceAttr in [L9['rx'], L9['ry'], L9['zoom'], L9['focus']]:
self.stickyAttrs[(device, deviceAttr)] = value
# e.g. don't let an unspecified rotation go to 0
for (d, da), v in self.stickyAttrs.items():
daDict = deviceAttrs.setdefault(d, {})
if da not in daDict:
daDict[da] = v
return deviceAttrs
def setAttrs(self, client: ClientType, clientSession: ClientSessionType,
settings: List[Tuple[DeviceUri, DeviceAttr, float]],
sendTime: UnixTime):
"""
settings is a list of (device, attr, value). These attrs are
device attrs. We resolve conflicting values, process them into
output attrs, and call Output.update to send the new outputs.
client is a string naming the type of client. (client,
clientSession) is a unique client instance.
Each client session's last settings will be forgotten after
clientTimeoutSec.
"""
now = UnixTime(time.time())
self._warnOnLateRequests(client, now, sendTime)
self._forgetStaleClients(now)
uniqueSettings = self.resolvedSettingsDict(settings)
self.lastRequest[(client, clientSession)] = (now, uniqueSettings)
deviceAttrs = self._merge(iter(self.lastRequest.values()))
outputAttrs: Dict[DeviceUri, Dict[OutputAttr, OutputValue]] = {}
for d in self.allDevices:
try:
devType = self.deviceType[d]
except KeyError:
log.warn("request for output to unconfigured device %s" % d)
continue
try:
outputAttrs[d] = toOutputAttrs(devType, deviceAttrs.get(d, {}))
if self.listeners:
self.listeners.outputAttrsSet(d, outputAttrs[d],
self.outputMap)
except Exception as e:
log.error('failing toOutputAttrs on %s: %r', d, e)
pendingOut: Dict[OutputUri, Tuple[OutputInstance, bytearray]] = {}
for out in self.outputs:
pendingOut[OutputUri(out.uri)] = (out, bytearray(512))
for device, attrs in outputAttrs.items():
for outputAttr, value in attrs.items():
output, _index = self.outputMap[(device, outputAttr)]
outputUri = OutputUri(output.uri)
index = DmxMessageIndex(_index)
_, outArray = pendingOut[outputUri]
if outArray[index] != 0:
raise ValueError(f"someone already wrote to index {index}")
outArray[index] = value
dt1 = 1000 * (time.time() - now)
for uri, (out, buf) in pendingOut.items():
out.update(bytes(buf))
dt2 = 1000 * (time.time() - now)
if dt1 > 30:
log.warn(
"slow setAttrs: %.1fms -> flush -> %.1fms. lr %s da %s oa %s" %
(dt1, dt2, len(
self.lastRequest), len(deviceAttrs), len(outputAttrs)))
|