aboutsummaryrefslogtreecommitdiff
path: root/util
diff options
context:
space:
mode:
Diffstat (limited to 'util')
-rw-r--r--util/Config.py60
-rw-r--r--util/Geo.py6
-rw-r--r--util/NetworkOps.py9
-rw-r--r--util/PacketComposition.py2
-rw-r--r--util/Search.py14
5 files changed, 74 insertions, 17 deletions
diff --git a/util/Config.py b/util/Config.py
index 33e6fee..4c1eb1e 100644
--- a/util/Config.py
+++ b/util/Config.py
@@ -1,25 +1,29 @@
from xml.etree.ElementTree import *
+import sys
import xml
import pdb
import util.Strings as Strings
+import util.Search as Search
+from logger import main_log, exception_log
classArgsMem = {}
CONFIG_PATH = 'config/'
+DEFAULT_OVERRIDE_MODE = 'Merge'
def loadParamRequirementDict(className):
if not className in classArgsMem: #WOO CACHING
classArgsMem[className] = fileToDict(CONFIG_PATH + className)
return classArgsMem[className]
#Loads a config file. If its an xml file, inheritances are automatically resolved.
def loadConfigFile(fileName): #TODO: error handling etc.
- #try:
- #fileName = CONFIG_PATH + fileName
+ try:
if '.params' in fileName:
return fileToDict(fileName)
if '.xml' in fileName:
- config = ElementTree() #use .fromstring, and resolve xincludes
+ config = ElementTree()
config.parse(fileName)
- config = ElementTree(resolveConfigInheritance(config.getroot()))
+ resolveDocumentInheritances(config.getroot())
return config
- #except:
+ except Exception as inst:
+ main_log.error('Error loading config file ' + fileName)#, inst) TODO: log exception too
return None
#Takes an Element or an ElementTree. If it is a tree, it returns its root. Otherwise, just returns
#it
@@ -28,9 +32,15 @@ def getElement(el):
return el
elif el.__class__ == ElementTree:
return el.getroot()
+#XML tree composition. Returns the resulting tree, but happens in-place in the overriding tree.
def compositeXMLTrees(parentTree, overridingTree): #TODO: break up into sub-methods, change it to
#use .find()
#type checking -- convert ElementTrees to their root elements
+ if parentTree == None:
+ return overridingTree
+ if overridingTree == None:
+ return parentTree #TODO: this will probably cause a bug since it isn't in-place on
+ #overridingTree
parentTree = getElement(parentTree)
overridingTree = getElement(overridingTree)
parentItems = parentTree.getchildren()
@@ -44,13 +54,14 @@ def compositeXMLTrees(parentTree, overridingTree): #TODO: break up into sub-meth
#do we merge or replace?
intersectingElements = findElementsByTag(item.tag, overrideItems)
if len(intersectingElements) > 1:
- print 'ABUSE!'
+ main_log.warn('ABUSE! Override of multiple items isn\'t well defined. Don\'t do\
+ it!')
interEl = intersectingElements[0]
- mode = 'Replace'
+ mode = DEFAULT_OVERRIDE_MODE
if Strings.OVERRIDE_BEHAVIOR in interEl.attrib:
mode = interEl.attrib[Strings.OVERRIDE_BEHAVIOR]
if mode != 'Replace' and mode != 'Merge':
- print 'Bad Mode. Choosing to replace.'
+ main_log.warn('Bad Override Mode. Choosing to replace.')
mode = 'Replace'
if mode == 'Replace':
pass #we don't need to do anything
@@ -68,16 +79,31 @@ def findElementsByTag(tag, eList):
def fileToDict(fileName):
fileText = ''
try:
- print 'File Read'
with open(fileName) as f:
for line in f:
fileText += line.rstrip('\n').lstrip('\t') + ' '
except IOError:
+ exception_log.exception('Failure reading ' + fileName)
return {}
if fileText == '':
return {}
+ try:
+ resultDict = eval(fileText)
+ main_log.info(fileName + ' read and parsed')
+ return resultDict
+ except:
+ exception_log.info(fileName + ' is not a well formed python dict. Parsing failed')
return eval(fileText)
#parses arguments into python objects if possible, otherwise leaves as strings
+def pullArgsFromItem(parentNode):
+ attribArgs = {}
+ for arg in parentNode.attrib: #automatically pull attributes into the argdict
+ attribArgs[arg] = parentNode.attrib[arg]
+ argNode = parentNode.find('Args')
+ args = generateArgDict(argNode)
+ for key in attribArgs:
+ args[key] = attribArgs[key]
+ return args
def generateArgDict(parentNode, recurse=False):
args = {}
for arg in parentNode.getchildren():
@@ -100,11 +126,19 @@ def generateArgDict(parentNode, recurse=False):
if len(args.keys()) == 1 and recurse:
return args[args.keys()[0]]
return args
-
-def resolveConfigInheritance(el):
+#In place resolution of document inheritances. Doesn't return anything.
+def resolveDocumentInheritances(el):
+ abstractMembers = Search.parental_tree_search(el, '.getchildren()', '.tag==\'InheritsFrom\'')
+ for subel in abstractMembers:
+ subel = resolveInheritance(subel)
+#In place resolution of inheritence. Doesn't return anything.
+def resolveInheritance(el):
parentClass = el.find('InheritsFrom')
if parentClass != None:
parentTree = loadConfigFile(parentClass.text)
- el = compositeXMLTrees(el, parentTree)
+ if parentTree == None:
+ main_log.warn('Inheritance Failed. ' + parentClass.text + 'does not exist')
+ main_log.error('Inheritance Failed. ' + parentClass.text + 'does not exist')
+ return el
+ el = compositeXMLTrees(parentTree, el)
el.remove(parentClass) #get rid of the inheritance flag
- return el
diff --git a/util/Geo.py b/util/Geo.py
index 885c585..a9243de 100644
--- a/util/Geo.py
+++ b/util/Geo.py
@@ -1,6 +1,7 @@
#Geometry code
import math
from bisect import *
+import random
def pointWithinBoundingBox(point, bb): #this could be in 4 lines, but I'm lazy.
return sum([(point[i % 2] <= bb[i]) == (i>1) for i in range(4)]) == 4
print pointWithinBoundingBox((118,21), (10,8,298,42))
@@ -13,3 +14,8 @@ def gaussian(x,height,center,width):
return a*math.exp(-((x-b)**2)/(2*c**2))
def dist(l1, l2):
return math.sqrt(sum([(l1[i]-l2[i])**2 for i in range(len(l1))]))
+def randomLoc(boundingBox): #TODO: make less shitty
+ loc = []
+ loc.append(random.randint(0, boundingBox[0]))
+ loc.append(random.randint(0, boundingBox[1]))
+ return tuple(loc)
diff --git a/util/NetworkOps.py b/util/NetworkOps.py
index 0404975..6c50c6d 100644
--- a/util/NetworkOps.py
+++ b/util/NetworkOps.py
@@ -1,8 +1,11 @@
import socket
+from logger import main_log, exception_log
def getConnectedSocket(ip,port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
sock.connect((ip, port))
- except:
- print 'network down'
- return sock
+ return sock
+ except Exception as inst:
+ main_log.error('Network down. All network based renderers and sensors will not function.',
+ inst)
+ print (ip, port)
diff --git a/util/PacketComposition.py b/util/PacketComposition.py
index 2563c61..73eefff 100644
--- a/util/PacketComposition.py
+++ b/util/PacketComposition.py
@@ -6,6 +6,7 @@ DEEPMAGIC = 0xc001d00d
MAGICHASH = 0x69000420
PORTOUT = 0x0108
UNI = 0
+import pdb
kinetDict = {'flags': 0, 'startcode': 0, 'pad':0}
def composePixelStripData(pixelStrip):
packet = bytearray()
@@ -44,7 +45,6 @@ def kinetPortOut():
def kinetPortOutPayload(argDict):
payload = bytearray()
payload.extend(struct.pack('B', argDict['port']))
- #payload.append(0x00) #somepadding? lolwtf.
payload.extend(struct.pack('H', argDict['flags']))
#payload.append(0x00) #somepadding? lolwtf.
payload.extend(struct.pack('H', argDict['len']))
diff --git a/util/Search.py b/util/Search.py
index 25882da..f7e4b81 100644
--- a/util/Search.py
+++ b/util/Search.py
@@ -6,3 +6,17 @@ def find_le(a, x):
def find_ge(a, x):
'Find leftmost value greater than x'
return bisect_left(a, x)
+#returns parents of nodes that meed a given condition
+def parental_tree_search(root, childrenstr, conditionstr):
+ ret = []
+ queue = [root]
+ while queue:
+ current = queue.pop()
+ children = eval('current'+childrenstr)
+ for child in children:
+ if eval('child'+conditionstr):
+ ret.append(current)
+ #we know have a tree, so there are no back-edges etc, so no checking of that kind is
+ #necessary
+ queue += children
+ return ret