aboutsummaryrefslogtreecommitdiff
path: root/util
diff options
context:
space:
mode:
authorGravatar rcoh <rcoh@mit.edu>2010-12-20 15:42:13 -0500
committerGravatar rcoh <rcoh@mit.edu>2010-12-20 15:42:13 -0500
commita1d9b85320c9b07d62470d78ef0c5f9015baf813 (patch)
tree8df16aec8de793ba0f2e4b330b764a6f6a49f59a /util
parent17577b1b19387b2cefb7ac777ed1323dd36be086 (diff)
parent2736307c1d6d67868ca54a3df951f9e959efedd0 (diff)
Merge branch 'master' into pixelregions
Conflicts: Util.py pixelmappers/SimpleMapper.py
Diffstat (limited to 'util')
-rw-r--r--util/ColorOps.py11
-rw-r--r--util/ComponentRegistry.py17
-rw-r--r--util/Config.py53
-rw-r--r--util/Geo.py15
-rw-r--r--util/NetworkOps.py6
-rw-r--r--util/PacketComposition.py59
-rw-r--r--util/Search.py8
-rw-r--r--util/Strings.py1
-rw-r--r--util/TimeOps.py19
-rw-r--r--util/__init__.py0
10 files changed, 189 insertions, 0 deletions
diff --git a/util/ColorOps.py b/util/ColorOps.py
new file mode 100644
index 0000000..b0d64a7
--- /dev/null
+++ b/util/ColorOps.py
@@ -0,0 +1,11 @@
+import random
+def randomColor():
+ return [random.randint(0,255) for i in range(3)]
+def chooseRandomColor(colorList):
+ return random.choice(colorList)
+def safeColor(c):
+ return [min(channel,255) for channel in c]
+def combineColors(c1,c2):
+ return safeColor([c1[i]+c2[i] for i in range(min(len(c1),len(c2)))])
+def multiplyColor(color, percent):
+ return safeColor([channel*(percent) for channel in color])
diff --git a/util/ComponentRegistry.py b/util/ComponentRegistry.py
new file mode 100644
index 0000000..f8fe00d
--- /dev/null
+++ b/util/ComponentRegistry.py
@@ -0,0 +1,17 @@
+import pdb
+#Registry of all components of the light system
+#TODO: pick a graceful failure behavior and implement it
+registry = {}
+def registerComponent(component, cid=None):
+ if cid != None:
+ registry[cid] = component
+ else:
+ try:
+ cid = component['Id']
+ registry[cid] = component
+ except:
+ raise Exception('Must specify Id, component did not store it')
+def removeComponent(cid):
+ registry.pop(cid)
+def getComponent(cid):
+ return registry[cid]
diff --git a/util/Config.py b/util/Config.py
new file mode 100644
index 0000000..4cf2ed5
--- /dev/null
+++ b/util/Config.py
@@ -0,0 +1,53 @@
+from xml.etree.ElementTree import ElementTree
+classArgsMem = {}
+CONFIG_PATH = 'config/'
+def loadParamRequirementDict(className):
+ if not className in classArgsMem: #WOO CACHING
+ classArgsMem[className] = fileToDict(CONFIG_PATH + className)
+ return classArgsMem[className]
+def loadConfigFile(fileName): #TODO: error handling etc.
+ try:
+ fileName = CONFIG_PATH + fileName
+ if '.params' in fileName:
+ return fileToDict(fileName)
+ if '.xml' in fileName:
+ config = ElementTree()
+ config.parse(fileName)
+ return config
+ except:
+ return None
+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:
+ return {}
+ if fileText == '':
+ return {}
+ return eval(fileText)
+#parses arguments into python objects if possible, otherwise leaves as strings
+def generateArgDict(parentNode, recurse=False):
+ args = {}
+ for arg in parentNode.getchildren():
+ key = arg.tag
+ if arg.getchildren() != []:
+ value = generateArgDict(arg, True)
+ else:
+ #convert into python if possible, otherwise don't
+ try:
+ value = eval(arg.text)
+ except (NameError,SyntaxError):
+ value = str(arg.text)
+ if key in args: #build of lists of like-elements
+ if type(args[key]) != type([]):
+ args[key] = [args[key]]
+ args[key].append(value)
+ else:
+ args[key]=value
+ #if we should be a list but we aren't:
+ if len(args.keys()) == 1 and recurse:
+ return args[args.keys()[0]]
+ return args
diff --git a/util/Geo.py b/util/Geo.py
new file mode 100644
index 0000000..885c585
--- /dev/null
+++ b/util/Geo.py
@@ -0,0 +1,15 @@
+#Geometry code
+import math
+from bisect import *
+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))
+def addLocations(l1,l2):
+ return tuple([l1[i]+l2[i] for i in range(len(l1))])
+def gaussian(x,height,center,width):
+ a=height
+ b=center
+ c=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))]))
diff --git a/util/NetworkOps.py b/util/NetworkOps.py
new file mode 100644
index 0000000..a247090
--- /dev/null
+++ b/util/NetworkOps.py
@@ -0,0 +1,6 @@
+import socket
+def getConnectedSocket(ip,port):
+ sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
+ print (ip, port)
+ sock.connect((ip, port))
+ return sock
diff --git a/util/PacketComposition.py b/util/PacketComposition.py
new file mode 100644
index 0000000..5133459
--- /dev/null
+++ b/util/PacketComposition.py
@@ -0,0 +1,59 @@
+import struct
+VERSION = 0x0001
+MAGIC = 0x4adc0104
+MOREMAGIC = 0xdeadbeef
+DEEPMAGIC = 0xc001d00d
+MAGICHASH = 0x69000420
+PORTOUT = 0x0108
+UNI = 0
+kinetDict = {'flags': 0, 'startcode': 0, 'pad':0}
+def composePixelStripData(pixelStrip):
+ packet = bytearray()
+ for light in pixelStrip:
+ color = light.state()
+ for channel in color: #skip the last value, its an
+ #alpha value
+ packet.append(struct.pack('B', channel))
+ return packet
+# packet = [0]*len(pixelStrip.pixels)*3 #preallocate for speed
+# for i in range(len(pixelStrip.pixels)):
+#color = pixelStrip.pixels[i].state()
+#packet[i:i+2] = color
+# return bytearray(packet)
+def composePixelStripPacket(pixelStrip,port):
+ packet = bytearray()
+ data = composePixelStripData(pixelStrip)
+ subDict = dict(kinetDict)
+ subDict['len'] = 38000 #I have no idea why this works.
+ subDict['port'] = port
+ #pdb.set_trace()
+ packet.extend(kinetPortOutPacket(subDict))
+ packet.append(0x0)
+ packet.extend(data)
+ return packet
+def kinetHeader():
+ header = bytearray()
+ header.extend(struct.pack('L', MAGIC))
+ header.extend(struct.pack('H', VERSION))
+ header.extend(struct.pack('H', PORTOUT))
+ header.extend(struct.pack('L', 0))
+ return header
+def kinetPortOut():
+ header = kinetHeader()
+ header.extend(struct.pack('L', UNI))
+ return header
+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']))
+ payload.extend(struct.pack('H', argDict['startcode']))
+ #pdb.set_trace()
+ return payload
+def kinetPortOutPacket(payloadArgs):
+ packet = bytearray()
+ packet.extend(kinetPortOut())
+ packet.extend(kinetPortOutPayload(payloadArgs))
+ return packet
diff --git a/util/Search.py b/util/Search.py
new file mode 100644
index 0000000..25882da
--- /dev/null
+++ b/util/Search.py
@@ -0,0 +1,8 @@
+from bisect import *
+def find_le(a, x):
+ 'Find rightmost value less than or equal to x'
+ return bisect_right(a, x)-1
+
+def find_ge(a, x):
+ 'Find leftmost value greater than x'
+ return bisect_left(a, x)
diff --git a/util/Strings.py b/util/Strings.py
new file mode 100644
index 0000000..1331db4
--- /dev/null
+++ b/util/Strings.py
@@ -0,0 +1 @@
+LOCATION = 'Location'
diff --git a/util/TimeOps.py b/util/TimeOps.py
new file mode 100644
index 0000000..dcd5038
--- /dev/null
+++ b/util/TimeOps.py
@@ -0,0 +1,19 @@
+import time as clock
+def time():
+ return clock.time()*1000 #all times in MS
+class Stopwatch:
+ def __init__(self):
+ self.running = False
+ self.startTime = -1
+ self.stopTime = -1
+ def start(self):
+ self.startTime = time()
+ self.running = True
+ def elapsed(self):
+ if self.running:
+ return time()-self.startTime
+ else:
+ return self.stopTime - self.startTime
+ def stop(self):
+ self.stopTime = time()
+ self.running = False
diff --git a/util/__init__.py b/util/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/util/__init__.py