aboutsummaryrefslogtreecommitdiff
path: root/util/ComponentRegistry.py
blob: 1db51351174ac0045f0607d51dc9c0435d0c05d2 (plain)
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
import hashlib 
from logger import main_log
import thread
#TODO: make component registry a singleton
def initRegistry():
    #TODO: don't overwrite existing registry
    if not 'Registry' in globals():
        globals()['Registry'] = {}
    makelock()
        
        
def makelock():
    global utilLock
    utilLock = thread.allocate_lock()
def clearRegistry():
    initRegistry()

def removeComponent(cid):
    global Registry
    Registry.pop(cid)

def getLock():
    global utilLock
    return utilLock
def getComponent(cid):
    global Registry
    return Registry[cid]

#Registry of all components of the light system
#TODO: pick a graceful failure behavior and implement it
def registerComponent(component, cid=None):
    global Registry
    if cid != None:
        Registry[cid] = component
    else:
        try:
            cid = component['Id']
        except KeyError:
            cid = getNewId() 
            component['Id'] = cid 
            main_log.debug(cid + 'automatically assigned')
        if cid in Registry:
            main_log.warn(cid + 'overwritten.')
        Registry[cid] = component
    return cid

def verifyUniqueId(cid):
    global Registry
    return not cid in Registry

def removeComponent(cid):
    global Registry
    Registry.pop(cid)

def getNewId():
    global Registry
    trialKey = len(Registry)
    trialId = hashlib.md5(str(trialKey)).hexdigest()
    while trialId in Registry:
        trialKey += 1
        trialId = hashlib.md5(str(trialKey)).hexdigest()
    return trialId