comparison service/reasoning/reasoning.py @ 916:e8cce78a79d6

switch reasoning from restkit to async cyclone http client Ignore-this: d7b8d0dba6374315a6eba63ca13e7c69 darcs-hash:20130903035718-312f9-fd247d06bb6d1c88f1f79557e676e3c3b91e834c
author drewp <drewp@bigasterisk.com>
date Mon, 02 Sep 2013 20:57:18 -0700
parents 1e2a3f85c61a
children bab30d0fb240
comparison
equal deleted inserted replaced
915:1e7dd498fa60 916:e8cce78a79d6
20 from twisted.web.client import getPage 20 from twisted.web.client import getPage
21 from twisted.python.filepath import FilePath 21 from twisted.python.filepath import FilePath
22 import time, traceback, sys, json, logging 22 import time, traceback, sys, json, logging
23 from rdflib.Graph import Graph, ConjunctiveGraph 23 from rdflib.Graph import Graph, ConjunctiveGraph
24 from rdflib import Namespace, URIRef, Literal, RDF, StringInputSource 24 from rdflib import Namespace, URIRef, Literal, RDF, StringInputSource
25 import restkit
26 from FuXi.Rete.RuleStore import N3RuleStore 25 from FuXi.Rete.RuleStore import N3RuleStore
26 from cyclone.httpclient import fetch
27 import cyclone.web, cyclone.websocket 27 import cyclone.web, cyclone.websocket
28 from inference import addTrig, infer 28 from inference import addTrig, infer
29 from graphop import graphEqual 29 from graphop import graphEqual
30 30
31 sys.path.append("../../lib") 31 sys.path.append("../../lib")
69 # think I want to have a separate graph for the output 69 # think I want to have a separate graph for the output
70 # handling 70 # handling
71 log.debug("read file graphs") 71 log.debug("read file graphs")
72 for fp in FilePath("input").walk(): 72 for fp in FilePath("input").walk():
73 if fp.isdir(): 73 if fp.isdir():
74 continue
75 if fp.splitext()[1] != '.n3':
74 continue 76 continue
75 log.debug("read %s", fp) 77 log.debug("read %s", fp)
76 # todo: if this fails, leave the report in the graph 78 # todo: if this fails, leave the report in the graph
77 self._fileGraph.parse(fp.open(), format="n3") 79 self._fileGraph.parse(fp.open(), format="n3")
78 self._combinedGraph = None 80 self._combinedGraph = None
217 t1 = time.time() 219 t1 = time.time()
218 out = infer(inputGraph, self.ruleStore) 220 out = infer(inputGraph, self.ruleStore)
219 inferenceTime = time.time() - t1 221 inferenceTime = time.time() - t1
220 222
221 out.add((ROOM['reasoner'], ROOM['inferenceTime'], 223 out.add((ROOM['reasoner'], ROOM['inferenceTime'],
222 Literal(inferenceTime))) 224 Literal(inferenceTime)))
223 return out 225 return out
224 226
225 def _postToMagma(self, inputGraph): 227 def _postToMagma(self, inputGraph):
226 try: 228
227 inputGraphNt = inputGraph.serialize(format="nt") 229 inputGraphNt = inputGraph.serialize(format="nt")
228 inferredNt = self.inferred.serialize(format="nt") 230 inferredNt = self.inferred.serialize(format="nt")
229 body = json.dumps({"input": inputGraphNt, 231 body = json.dumps({"input": inputGraphNt,
230 "inferred": inferredNt}) 232 "inferred": inferredNt})
231 restkit.Resource("http://bang:8014/").post( 233 def err(e):
232 "reasoningChange", payload=body,
233 headers={"content-type" : "application/json"})
234 except Exception, e:
235 traceback.print_exc()
236 log.error("while sending changes to magma:") 234 log.error("while sending changes to magma:")
237 log.error(e) 235 log.error(e)
236
237 fetch("http://bang:8014/reasoningChange",
238 method="POST",
239 timeout=2,
240 payload=body,
241 headers={"content-type" : ["application/json"]}).addErrback(err)
242
243 def _put(self, url, payload):
244 def err(e):
245 outlog.warn("put %s falied", url)
246 outlog.info("PUT %s payload=%r", url, payload)
247 fetch(url, method="PUT", payload=payload, timeout=2).addErrback(err)
238 248
239 def putResults(self, inferred): 249 def putResults(self, inferred):
240 """ 250 """
241 some conclusions in the inferred graph lead to PUT requests 251 some conclusions in the inferred graph lead to PUT requests
242 getting made 252 getting made
259 (URIRef('http://bigasterisk.com/host/bang/monitor'), ROOM.powerState), 269 (URIRef('http://bigasterisk.com/host/bang/monitor'), ROOM.powerState),
260 (URIRef('http://bigasterisk.com/host/dash/monitor'), ROOM.powerState), 270 (URIRef('http://bigasterisk.com/host/dash/monitor'), ROOM.powerState),
261 ]: 271 ]:
262 url = deviceGraph.value(dev, ROOM.putUrl) 272 url = deviceGraph.value(dev, ROOM.putUrl)
263 273
264 if dev == DEV.theaterDoorLock: # ew 274 if url and dev == DEV.theaterDoorLock: # ew
265 restkit.request(url=url+"/mode", method="PUT", body="output") 275 self._put(url+"/mode", payload="output")
266 276
267 inferredObjects = list(inferred.objects(dev, pred)) 277 inferredObjects = list(inferred.objects(dev, pred))
268 if len(inferredObjects) == 0: 278 if len(inferredObjects) == 0:
269 self.putZero(deviceGraph, dev, pred, url) 279 self.putZero(deviceGraph, dev, pred, url)
270 elif len(inferredObjects) == 1: 280 elif len(inferredObjects) == 1:
304 def putZero(self, deviceGraph, dev, pred, putUrl): 314 def putZero(self, deviceGraph, dev, pred, putUrl):
305 # zerovalue should be a function of pred as well. 315 # zerovalue should be a function of pred as well.
306 value = deviceGraph.value(dev, ROOM.zeroValue) 316 value = deviceGraph.value(dev, ROOM.zeroValue)
307 if value is not None: 317 if value is not None:
308 outlog.info("put zero (%r) to %s", value, putUrl) 318 outlog.info("put zero (%r) to %s", value, putUrl)
309 restkit.request(url=putUrl, method="PUT", body=value) 319 self._put(putUrl, payload=value)
310 # this should be written back into the inferred graph 320 # this should be written back into the inferred graph
311 # for feedback 321 # for feedback
312 322
313 def putInferred(self, deviceGraph, dev, pred, putUrl, obj): 323 def putInferred(self, deviceGraph, dev, pred, putUrl, obj):
314 value = deviceGraph.value(obj, ROOM.putValue) 324 value = deviceGraph.value(obj, ROOM.putValue)
315 if value is not None: 325 if value is not None:
316 outlog.info("put %s to %s", value, putUrl) 326 outlog.info("put %s to %s", value, putUrl)
317 restkit.request(url=putUrl, method="PUT", body=value) 327 self._put(putUrl, payload=value)
318 else: 328 else:
319 outlog.warn("%s %s %s has no :putValue" % 329 outlog.warn("%s %s %s has no :putValue" %
320 (dev, pred, obj)) 330 (dev, pred, obj))
321 331
322 def frontDoorPuts(self, deviceGraph, inferred): 332 def frontDoorPuts(self, deviceGraph, inferred):
324 brt = inferred.value(DEV.frontDoorLcd, ROOM.brightness) 334 brt = inferred.value(DEV.frontDoorLcd, ROOM.brightness)
325 if brt is None: 335 if brt is None:
326 return 336 return
327 url = deviceGraph.value(DEV.frontDoorLcdBrightness, ROOM.putUrl) 337 url = deviceGraph.value(DEV.frontDoorLcdBrightness, ROOM.putUrl)
328 outlog.info("put lcd %s brightness %s", url, brt) 338 outlog.info("put lcd %s brightness %s", url, brt)
329 def failed(err): 339 self._put(str(url) + "?brightness=%s" % str(brt))
330 outlog.error("lcd brightness: %s", err)
331 getPage(str(url) + "?brightness=%s" % str(brt),
332 method="PUT").addErrback(failed)
333 340
334 msg = "open %s motion %s" % ( 341 msg = "open %s motion %s" % (
335 inferred.value(DEV['frontDoorOpenIndicator'], ROOM.text), 342 inferred.value(DEV['frontDoorOpenIndicator'], ROOM.text),
336 inferred.value(DEV['frontDoorMotionIndicator'], ROOM.text)) 343 inferred.value(DEV['frontDoorMotionIndicator'], ROOM.text))
337 # this was meant to be 2 chars in the bottom row, but the 344 # this was meant to be 2 chars in the bottom row, but the