Пример #1
0
    def __init__(self, mockOutput=False):
        self.prevGraph = None

        self.rulesN3 = "(not read yet)"
        self.inferred = Graph()  # gets replaced in each graphChanged call
        self.outputGraph = PatchableGraph()  # copy of inferred, for now

        self.inputGraph = InputGraph([], self.graphChanged)
        self.actions = Actions(self.inputGraph,
                               sendToLiveClients,
                               mockOutput=mockOutput)
        self.inputGraph.updateFileData()
Пример #2
0
def main():
    arg = docopt("""
    Usage: tradfri.py [options]

    -v   Verbose
    """)
    log.setLevel(logging.WARN)
    if arg['-v']:
        from twisted.python import log as twlog
        twlog.startLogging(sys.stdout)
        log.setLevel(logging.DEBUG)

    masterGraph = PatchableGraph()
    hub = Hub(masterGraph, private.hubAddr, key=private.hubKey)

    reactor.listenTCP(10009, cyclone.web.Application([
        (r"/()", cyclone.web.StaticFileHandler, {
            "path": "/opt/static", "default_filename": "index.html"}),
        (r'/static/(.*)', cyclone.web.StaticFileHandler, {"path": "/opt/static"}),
        (r'/boards', Boards),
        (r"/graph/tradfri", CycloneGraphHandler, {'masterGraph': masterGraph}),
        (r"/graph/tradfri/events", CycloneGraphEventsHandler, {'masterGraph': masterGraph}),
        (r'/output', OutputPage),
        ], hub=hub, debug=arg['-v']), interface='::')
    log.warn('serving on 10009')
    reactor.run()
Пример #3
0
def main():
    arg = docopt("""
    Usage: arduinoNode.py [options]

    -v   Verbose
    -s   serial logging
    -l   slow polling
    """)
    log.setLevel(logging.WARN)
    if arg['-v']:
        from twisted.python import log as twlog
        twlog.startLogging(sys.stdout)

        log.setLevel(logging.DEBUG)
    if arg['-s']:
        logging.getLogger('serial').setLevel(logging.INFO)

    masterGraph = PatchableGraph()
    config = Config(masterGraph, slowMode=arg['-l'])
    static = pkg_resources.resource_filename('homeauto_anynode', 'static/')

    reactor.listenTCP(9059, cyclone.web.Application([
        (r"/(|output-widgets.html)", cyclone.web.StaticFileHandler, {
            "path": static, "default_filename": "index.html"}),
        (r'/static/(.*)', cyclone.web.StaticFileHandler, {"path": "static"}),
        (r'/stats/(.*)', StatsHandler, {'serverName': 'arduinoNode'}),
        (r'/boards', Boards),
        (r"/graph", CycloneGraphHandler, {'masterGraph': masterGraph}),
        (r"/graph/events", CycloneGraphEventsHandler, {'masterGraph': masterGraph}),
        (r'/output', OutputPage),
        (r'/arduinoCode', ArduinoCode),
        (r'/dot', Dot),
        ], config=config), interface='::')
    reactor.run()
Пример #4
0
def main():
    arg = docopt("""
    Usage: report.py [options]

    -v                    Verbose
    """)
    verboseLogging(arg['-v'])
    log.info('startup')

    masterGraph = PatchableGraph()
    eventsInGraph: Set[URIRef] = set()
    coll = MongoClient(
        'mongodb',
        tz_aware=True).get_database('timebank').get_collection('webproxy')

    class Application(cyclone.web.Application):
        def __init__(self):
            handlers = [
                (r"/()", cyclone.web.StaticFileHandler, {
                    "path": ".",
                    "default_filename": "index.html"
                }),
                (r'/build/(bundle\.js)', cyclone.web.StaticFileHandler, {
                    "path": "build"
                }),
                (r'/graph/webevents', CycloneGraphHandler, {
                    'masterGraph': masterGraph
                }),
                (r'/graph/webevents/events', CycloneGraphEventsHandler, {
                    'masterGraph': masterGraph
                }),
            ]
            cyclone.web.Application.__init__(self,
                                             handlers,
                                             masterGraph=masterGraph,
                                             coll=coll)

    task.LoopingCall(update, masterGraph, eventsInGraph, coll).start(10)
    reactor.listenTCP(10001, Application())
    log.info('serving')
    reactor.run()
Пример #5
0
def main():
    arg = docopt("""
    Usage: environment.py [options]

    -v                    Verbose
    """)
    verboseLogging(arg['-v'])

    masterGraph = PatchableGraph()

    class Application(cyclone.web.Application):
        def __init__(self):
            handlers = [
                (r"/()", cyclone.web.StaticFileHandler, {
                    "path": ".",
                    "default_filename": "index.html"
                }),
                (r'/graph/environment', CycloneGraphHandler, {
                    'masterGraph': masterGraph
                }),
                (r'/graph/environment/events',
                 CycloneGraphEventsHandlerWithCors, {
                     'masterGraph': masterGraph
                 }),
                (r'/doc', Doc),  # to be shared
                (r'/stats/(.*)', StatsHandler, {
                    'serverName': 'environment'
                }),
            ]
            cyclone.web.Application.__init__(self,
                                             handlers,
                                             masterGraph=masterGraph)

    task.LoopingCall(update, masterGraph).start(1)
    reactor.listenTCP(9075, Application())
    reactor.run()
Пример #6
0
                'measurement': 'power',
                'tags': {
                    'device': '%sMonitor' % host
                },
                'fields': {
                    'value': 1 if state == 'on' else 0
                },
                'time': now
            }],
                                time_precision='s')

            self.lastSent = state
            self.lastSentTime = now


masterGraph = PatchableGraph()
poller = Poller()

reactor.listenTCP(9095,
                  cyclone.web.Application([
                      (r'/', Root),
                      (r'/monitor', Monitor),
                      (r'/graph/dpms', CycloneGraphHandler, {
                          'masterGraph': masterGraph
                      }),
                      (r'/graph/dpms/events', CycloneGraphEventsHandler, {
                          'masterGraph': masterGraph
                      }),
                  ]),
                  interface='::')
Пример #7
0
"""
see how a browser talks to this PatchableGraph
"""

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

from standardservice.logsetup import log, verboseLogging
from patchablegraph import PatchableGraph, CycloneGraphEventsHandler, CycloneGraphHandler

verboseLogging(True)

graph = PatchableGraph()
g = ConjunctiveGraph()
g.add((URIRef('http://example.com/s'), URIRef('http://example.com/p'),
       URIRef('http://example.com/o'), URIRef('http://example.com/g')))
graph.setToGraph(g)


class Application(cyclone.web.Application):
    def __init__(self):
        handlers = [
            (r'/graph', CycloneGraphHandler, {
                'masterGraph': graph
            }),
            (r'/graph/events', CycloneGraphEventsHandler, {
                'masterGraph': graph
            }),
        ]
        cyclone.web.Application.__init__(self, handlers)
Пример #8
0
class Reasoning(object):
    ruleStore: ConjunctiveGraph

    def __init__(self, mockOutput=False):
        self.prevGraph = None

        self.rulesN3 = "(not read yet)"
        self.inferred = Graph()  # gets replaced in each graphChanged call
        self.outputGraph = PatchableGraph()  # copy of inferred, for now

        self.inputGraph = InputGraph([], self.graphChanged)
        self.actions = Actions(self.inputGraph,
                               sendToLiveClients,
                               mockOutput=mockOutput)
        self.inputGraph.updateFileData()

    @UPDATE_RULES_CALLS.time()
    def updateRules(self):
        rulesPath = 'rules.n3'
        try:
            t1 = time.time()
            self.rulesN3, self.ruleStore = readRules(
                rulesPath,
                outputPatterns=[
                    # Incomplete. See escapeoutputstatements.py for
                    # explanation.
                    (None, ROOM['brightness'], None),
                    (None, ROOM['playState'], None),
                    (None, ROOM['powerState'], None),
                    (None, ROOM['state'], None),
                ])
            ruleParseTime = time.time() - t1
        except ValueError:
            # this is so if you're just watching the inferred output,
            # you'll see the error too
            self.inferred = Graph()
            self.inferred.add((ROOM['reasoner'], ROOM['ruleParseError'],
                               Literal(traceback.format_exc())))
            self.copyOutput()
            raise
        return [(ROOM['reasoner'], ROOM['ruleParseTime'],
                 Literal(ruleParseTime))], ruleParseTime

    @GRAPH_CHANGED_CALLS.time()
    def graphChanged(self,
                     inputGraph: InputGraph,
                     oneShot=False,
                     oneShotGraph: Graph = None):
        """
        If we're getting called for a oneShot event, the oneShotGraph
        statements are already in inputGraph.getGraph().
        """
        log.info("----------------------")
        log.info("graphChanged (oneShot=%s %s stmts):", oneShot,
                 len(oneShotGraph) if oneShotGraph is not None else 0)
        if oneShotGraph:
            for stmt in oneShotGraph:
                log.info(" oneshot -> %s", ntStatement(stmt))
        t1 = time.time()
        oldInferred = self.inferred
        try:
            ruleStatStmts, ruleParseSec = self.updateRules()

            self.inferred, inferSec = self._makeInferred(inputGraph.getGraph())

            self.inferred += unquoteOutputStatements(self.inferred)

            self.inferred += ruleStatStmts

            if oneShot:
                # It's possible a oneShotGraph statement didn't
                # trigger a rule to do something, but was itself the
                # output statement. Probably we could just mix in the
                # whole inputGraph here and not special-case the
                # oneShotGraph.
                self.inferred += oneShotGraph

            t3 = time.time()
            self.actions.putResults(self.inferred)
            putResultsTime = time.time() - t3
        finally:
            if oneShot:
                self.inferred = oldInferred
        log.info(
            "graphChanged took %.1f ms (rule parse %.1f ms, infer %.1f ms, putResults %.1f ms)"
            % ((time.time() - t1) * 1000, ruleParseSec * 1000, inferSec * 1000,
               putResultsTime * 1000))
        if not oneShot:
            self.copyOutput()

    def copyOutput(self):
        self.outputGraph.setToGraph(
            (s, p, o, ROOM['inferred']) for s, p, o in self.inferred)

    def _makeInferred(self, inputGraph: ConjunctiveGraph):
        t1 = time.time()

        out = infer(inputGraph, self.ruleStore)
        for p, n in NS.items():
            out.bind(p, n, override=True)

        inferenceTime = time.time() - t1
        out.add(
            (ROOM['reasoner'], ROOM['inferenceTime'], Literal(inferenceTime)))
        return out, inferenceTime
Пример #9
0
                self.settings.masterGraph.patchObject(
                    attrs['ctx'],
                    stmt[0], stmt[1], stmt[2])
                ignored = False
        if ignored:
            log.warn("ignoring %s", stmt)
            
if __name__ == '__main__':
    arg = docopt("""
    Usage: mqtt_graph_bridge.py [options]

    -v   Verbose
    """)
    verboseLogging(arg['-v'])

    masterGraph = PatchableGraph()

    mqtt = MqttClient(clientId='mqtt_graph_bridge', brokerPort=1883)

    port = 10008
    reactor.listenTCP(port, cyclone.web.Application([
        (r"/()", cyclone.web.StaticFileHandler,
         {"path": ".", "default_filename": "index.html"}),
        (r"/graph", CycloneGraphHandler, {'masterGraph': masterGraph}),
        (r"/graph/events", CycloneGraphEventsHandler,
         {'masterGraph': masterGraph}),
        (r'/output', OutputPage),
        ], mqtt=mqtt, masterGraph=masterGraph, debug=arg['-v']), interface='::')
    log.warn('serving on %s', port)

    for dev, attrs in devs.items():