Exemplo n.º 1
0
    def __init__(self, absPath):

        EventEngine.configFile = 'server.properties'
        EventEngine.root = Container("root", "root", "this is the root node")

        #print "initializing EventEngine..."
        EventEngine.root.addContainer("instance", Config.jid, "this is the tree instance "+Config.jid)

        # assign me node to Eventengine.root.me
        EventEngine.root.me = EventEngine.root.getChild(Config.jid)

        # generate all plugins
        p = PlugIns(Config.plugInsFolder, EventEngine.configFile).getChildList()

        # load plugin tree into me-node
        EventEngine.root.me.addChildList(p)

        # starting xmppEngine
        if Config.get("server", "jabber").__eq__("on"):
            print "starting xmppEngine"
            xmpp = XMPPEngineStart(EventEngine.root)
        else:
            print "jabber not active"

        # start webEngine
        if Config.get("server", "web").__eq__("on"):
            print "starting webEngine"
            webserver = WebEngine(EventEngine.root)
Exemplo n.º 2
0
 def __init__(self, token, configFile):
     PlugIn.__init__(self)
     self.architecture = "all"
     self.override_dict ={}
     self.jid = Config.get("jabber","jid")
     global backend
     backend = Config.get("Defaults","backend")
     global scenario
     scenario = "default"
     #plugin itself
     self.content = Container("plugin", token, "This is a Defaults Plugin")
     self.content.addContainer("cmd","getBackend","getBackend", self.getBackend)
     for pair in Config.getSection("Defaults"):
         if pair[0].endswith('_plain'):
             title= pair[0].replace('_plain','')
             container = Container("cmd",title,pair[1],self.general)
             container.rendering = Container.PLAIN
         else:
             container = Container("cmd",pair[0],pair[1],self.general)
             container.setUseArgs(backend)
         self.content.addChild(container)
         
         #self.content.addContainer("cmd", pair[0], pair[1], use=self.general, args="test")
         
     self.content.addContainer("cmd","set","set",self.override)
     self.content.addContainer("cmd","setScenario","set a Scenario", self.setScenario)
     self.content.addContainer("cmd","getScenario", "get current Scenario", self.getScenario)
Exemplo n.º 3
0
    def __init__(self, type, token, information="empty"):
        ThreadContainer.__init__(self, type, token, information="empty")
        self.lastval = 0
        self.information = information

        ##
        # Hardware Initialization
        ##

        try: #try:
            lib=Config.absPath+Config.get("avrBridge", "lib")
	    #print lib
            self.mega=cdll.LoadLibrary(lib)
            self.mega.initUsbLib()
            self.port = 1



            #print '!-!-!-!-! PLANTMONITOR sucessfully initialized'

            for tuple in Config.getSection("Plantmonitor"):
                tmpcont = Container("plugin", tuple[0], tuple[1])
                tmpcont.pin = tuple[1]
                tmpcont.setUse(self.leafuse)

                self.mega.setPortPinDir(self.port,tmpcont.pin,0)
                self.mega.setPortPin(self.port,tmpcont.pin,1)

                self.addChild(tmpcont)


        except Exception,e:
            print "[PLANTMONITOR ERROR] Could not init plugin\n"+str(e)
Exemplo n.º 4
0
 def send(self):
     my_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
     my_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
     print 'start Broadcasting ...'
 
     while True :
         my_socket.sendto(Config.get("server", "token"), ('<broadcast>' , 8081))
         time.sleep(60)
Exemplo n.º 5
0
    def execAlarm():
        global alarmEvent
        alarmEvent = None
        print "ALARM ALARM"

        addr = Address(Config.get("AlarmClock", "exec"))
        print addr.__str__()
        print EventEngine.root.getByAddress(addr.__str__()).use()
        
        time.sleep(1)
        print AlarmClock.schedAlarm()
Exemplo n.º 6
0
    def __init__(self, pluginsFolder, configFile):

        #absolute folder to plugins
        absPluginsFolder = Config.absPath + "/" + Config.get("Plugins", "PlugInsFolder")

        #creating list whrer all plugins are loaded in
        self.content = []

        # load all plugins into container
        print "loading all plugins..."
        self.content = self.loadPlugins(absPluginsFolder, pluginsFolder, configFile)

        print "loaded all plugins sucessfully"
Exemplo n.º 7
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        self.architecture = "macos"


        if self.architecture.__eq__(Config.get("server", "architecture")):

            # plugin itself
            self.content = avrContainer("plugin", token, "This hopefully will be a Threaded SoftKey  Plugin")
            self.content.rendering = Container.PLAIN
            self.content.start()

        else:
            self.content = Container("plugin", token, "not supported")
Exemplo n.º 8
0
    def processRoster(self):

        self.rosterTree = {}

        self.roster = self.client.getRoster()

        # DIRTY!!!!
        XMPPEngine.roster = self.roster

        for elem in self.roster.getItems():
            if not self.rosterTree.has_key(elem) and not elem.__eq__(Config.get("jabber", "jid")):
                self.rosterTree[elem]=elem
                self.send("#type help to explore me.", elem)
                self.root.addChild(BuddyContainer("buddy", str(elem), "Buddy, maybe over the sea...", self.send))

                print elem
Exemplo n.º 9
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        self.architecture = "all"

        #plugin itself
        self.content = Container("plugin", token, "this is a Prowl plugin")
		
		#get platform we're running on
	platform = Config.get('server','architecture')
		
	if (platform == "macos"):
        # set add container
        	self.content.addContainer("cmd","Prowl", "send Push notification", self.prowl)
        else:
        	import pynotify
        	self.content.addContainer("cmd","Ubuntu", "show Ubuntu Notification", self.unotify)
Exemplo n.º 10
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        self.architecture = "all"
        
        global active, ringTime, wday, scheduler, alarmEvent
        wday = []
        alarmEvent = None
        #Read from Config
        active = AlarmClock.strToBool(Config.get("AlarmClock", "active"))
        ringTime = Config.get("AlarmClock", "time")
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "monday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "tuesday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "wednesday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "thursday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "friday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "saturday")))
        wday.append(AlarmClock.strToBool(Config.get("AlarmClock", "sunday")))
        
        scheduler = sched.scheduler(time.time, time.sleep)
        AlarmClock.schedAlarm()

        #Build Tree
        #plugin itself
        self.content = Container("plugin", token, "Alarm Clock")
        #ON/OFF
        self.content.addChild(SwitchContainer("cmd", "TurnOnAlarm", "Turn On Alarm", self.toogleAlarm, on=Config.jid + "/AlarmClock/TurnOnAlarm?string=True", off=Config.jid + "/AlarmClock/TurnOnAlarm?string=False", checked=active))
        #Time
        self.content.addChild(TimefieldContainer("cmd", "Time", "Set Time", self.setTime, target=Config.jid + "/AlarmClock/Time", value=ringTime))
        #Days
        self.content.addChild(CheckBoxContainer("cmd", "Monday", "Alarm on Monday", self.checkMonday, toogle=Config.jid + "/AlarmClock/Monday", checked=wday[0]))
        self.content.addChild(CheckBoxContainer("cmd", "Tuesday", "Alarm on Tuesday", self.checkTuesday, toogle=Config.jid + "/AlarmClock/Tuesday", checked=wday[1]))
        self.content.addChild(CheckBoxContainer("cmd", "Wednesday", "Alarm on Wednesday", self.checkWednesday, toogle=Config.jid + "/AlarmClock/Wednesday", checked=wday[2]))
        self.content.addChild(CheckBoxContainer("cmd", "Thursday", "Alarm on Thursday", self.checkThursday, toogle=Config.jid + "/AlarmClock/Thursday", checked=wday[3]))
        self.content.addChild(CheckBoxContainer("cmd", "Friday", "Alarm on Friday", self.checkFriday, toogle=Config.jid + "/AlarmClock/Friday", checked=wday[4]))
        self.content.addChild(CheckBoxContainer("cmd", "Saturday", "Alarm on Saturday", self.checkSaturday, toogle=Config.jid + "/AlarmClock/Saturday", checked=wday[5]))
        self.content.addChild(CheckBoxContainer("cmd", "Sunday", "Alarm on Sunday", self.checkSunday, toogle=Config.jid + "/AlarmClock/Sunday", checked=wday[6]))
        #Save
        self.content.addContainer("cmd", "save", "save alarm", self.save)
Exemplo n.º 11
0
    def loadPlugins(self, PluginsPath, PackagePath, configFile):


        # get all elements in folder into list
        pluginFiles = os.listdir(PluginsPath)
        #print pluginFiles
        #print PluginsPath, PackagePath

        result = []

        for elem in pluginFiles:
            # add plugin files
            if elem[-3:].__eq__(".py") and not (elem[:1].__eq__("_")):
                print "*** loading: " + PackagePath + "." + elem
                #print("from "+PackagePath+"."+elem[:-3]+" import "+elem[:-3])

                try:
                    exec("from " + PackagePath + "." + elem[:-3] + " import " + elem[:-3])
                    #print("plugin = "+elem[:-3]+"(\""+elem[:-3]+"\", \""+configFile+"\")")
                    exec("plugin = " + elem[:-3] + "(\"" + elem[:-3] + "\", \"" + configFile + "\")")
                    #print("result.append(plugin.getTree())")
                    #print plugin.architecture


                    # If its a Master Plugin, it only should loaded by Masters, else, check architecture
                    if plugin.master == True:
                        #Check if it amiServer is configured as master
                        if Config.get("server", "master").__eq__("on"):
                            result.append(plugin.getTree())

                    elif plugin.architecture.__eq__("all") or plugin.architecture.__eq__(Config.architecture):
                        result.append(plugin.getTree())

                except Exception,e:
                    print "[PLUGIN ERROR] Counld not load Plugin", elem
                    print e

            # add folders as plugin
            if os.path.isdir(PluginsPath + "/" + elem):
                print "+++ loding folder: " + PluginsPath + "." + elem
                tmpcont = Container("folder", elem, "this is the tree representation of a folder")
                tmpcont.setUse(self.display)
                tmpcont.addChildList(self.loadPlugins(PluginsPath + "/" + elem, PackagePath + "." + elem, configFile))
                result.append(tmpcont)
Exemplo n.º 12
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        self.architecture = "all"
        self.jid = Config.get("jabber","jid")
        #plugin itself
        self.content = Container("plugin", token, "This is a Sensors Plugin")
	cmd=""
        for pair in Config.getSection("Sensors"):
            if '?' in pair[1]:
            	tmp = pair[1].split('?')
            	self.content.arg = tmp[1].replace('string=','')
		cmd = tmp[0]
            else:
            	self.content.arg=""
            
            if pair[0].endswith('_plain'):
                title= pair[0].replace('_plain','')
                container = Container("cmd",title,pair[1],self.general)
                container.rendering = Container.PLAIN
            else:
                container = Container("cmd",pair[0],cmd,self.general)
            self.content.addChild(container)
Exemplo n.º 13
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        # set plugins "hardware" architecture for system dependencies
        self.architecture = "all"

        # create plugin itself
        self.content = ThreadContainer("plugin", token, "Listening to Broadcasts for Client amiServers")
        
        if Config.get("server", "master").__eq__("on"):
            method = self.listen
            ThreadName = "ClientListener"
        else:
            method = self.send
            ThreadName = "Broadcaster"
            
            
        self.content.setDo(method)
        # dont know wheather it works, shold set the name of the thread
        self.content.name = ThreadName

        # start thread
        self.content.start()
Exemplo n.º 14
0
    def __init__(self, type, token, information="empty"):
        ThreadContainer.__init__(self, type, token, information="empty")
        self.information = "hehehehe, arschloch"
        self.lastval = 0

        ##
        # Hardware Initialization
        ##

        try:
            lib=Config.absPath+Config.get("avrBridge", "lib")
	    print lib
            self.mega=cdll.LoadLibrary(lib)

            self.mega.initUsbLib()

            # init poti
            self.mega.setPortPinDir(1,1,0)
            self.mega.setPortPin(1,1,1)

            # set pins input
            self.mega.setPortPinDir(0,0,0)
            self.mega.setPortPinDir(0,1,0)
            self.mega.setPortPinDir(0,2,0)

            # enable internal pullup
            self.mega.setPortPin(0,0,1)
            self.mega.setPortPin(0,1,1)
            self.mega.setPortPin(0,2,1)

            #LED output
            self.mega.setPortPinDir(2,7,1)

            # light up the led
            self.mega.setPortPin(2,7,1)
	except Exception,e:
            print "[SOFTKEY ERROR] Could not init plugin\n"+str(e)
Exemplo n.º 15
0
 def vol_up(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" vol up")
Exemplo n.º 16
0
 def prev(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" prev")
Exemplo n.º 17
0
 def next(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" next")
Exemplo n.º 18
0
 def pause(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" pause")
Exemplo n.º 19
0
 def play(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" play")
Exemplo n.º 20
0
 def mute(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" mute")
Exemplo n.º 21
0
 def unotify(self, text="Notification"):
     text = self.getText(text)
     pynotify.init(Config.get('server', 'token'))
     n=pynotify.Notification(Config.get('server', 'token'), text)
     n.show()
     return text
Exemplo n.º 22
0
    def index(self):
        self.contentType('text/html')

        addr = Config.get("server", "token")

        #Muss vom Plugin generiert werden, damit es zu jeder zeit neu dynamisch geladen werden kann!
        navigationbar = '''
        <div class='floaty'>
            <ul>
                <li><a href='/'''+addr+'''/Dashboard' class="slideup">Dashboard</a></li>
                <li><a href='#'''+addr.replace('@', '_').replace('.', '_')+'''' class="">Home</a></li>
                <li><a href='/'''+addr+'''/Filesystem/interfaces/Map.interface' class="">Map</a></li>
                <li><a href='/'''+addr+'''/Filesystem/interfaces/Player.interface' class="">Audio</a></li>
            </ul>
        </div>
        '''

        addr = Config.get("server", "token")

        head = '''
        <meta charset="UTF-8" />

        <style type="text/css" media="screen">@import "'''+addr+'''/Filesystem/html/jqtouch/jqtouch.css";</style>
        <style type="text/css" media="screen">@import "'''+addr+'''/Filesystem/html/themes/jqt/theme.css";</style>
        <style type="text/css" media="screen">@import "'''+addr+'''/Filesystem/html/ami.css";</style>
        <style type="text/css" media="screen">@import "'''+addr+'''/Filesystem/interfaces/css/player.css";</style>
        <script src="'''+addr+'''/Filesystem/html/jqtouch/jquery.1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
        <!--script src="'''+addr+'''/Filesystem/html/jqtouch/jqtouch.transitions.js" type="text/javascript" charset="utf-8"></script-->
        <script src="'''+addr+'''/Filesystem/html/jqtouch/jqtouch.js" type="application/x-javascript" charset="utf-8"></script>
        <!--script src="'''+addr+'''/Filesystem/html/extensions/jqt.offline.js" type="application/x-javascript" charset="utf-8"></script-->
        <script src="'''+addr+'''/Filesystem/html/extensions/jqt.floaty.js" type="application/x-javascript" charset="utf-8"></script>
        <script type="text/javascript" charset="utf-8">
            var jQT = new $.jQTouch({
                icon: '/'''+addr+'''/Filesystem/html/images/appIcon.png',
                addGlossToIcon: true,
                cacheGetRequests: false,
                startupScreen: '/'''+addr+'''/Filesystem/html/images/startup.png',
                statusBar: 'black-translucent'
            });


            $(function(){

                $('.togglefloaty').click(function(){
                    $('.floaty').toggleFloaty();
                    $(this).removeClass('active');
                    return false;
                });


                $('.floaty').makeFloaty({
                    spacing: 0,
                    time: '0.2s',
                    align: 'bottom'
                });

                $('.arrow').bind("swipe",function(event, data){
                    if(data.direction=='right') {
                        if (true){
                            alert($(this).children(".removebutton").html())
                            $(this).append("<small class='counter removebutton' onClick='$(this).parent().hide();'>remove</small>");
                        } else {
                            alert('there is already a button')
                        }
                    }else {
                        print
                        $('.removebutton').hide();
                    }
                });                

            });
            
        </script>
        '''

        result = self.root.toJqHtml()
        
        # control caching
        caching = False
        if caching:
            manifest=' manifest="/cache.manifest"'
        else:
            manifest=''
        return '<html'+manifest+'><head>' + head + '</head><body>' + result + navigationbar + '</body></html>'
Exemplo n.º 23
0
    def element(self, var=''):
        #declarations
        file_name = 'MyEstate'
        requestArray = {}
        
        #open and parse the file 
        try:
            file = codecs.open(Config.absPath + Config.get('XML', file_name), "r")
            xmlString = file.read()
            file.close()
            xml_object = parseString(xmlString)
        except:
            return "ERROR: FILE NOT FOUND"
        print var
        
        list = xml_object
        #building the json
        try:
            requestString = json.loads(var)
        except:
            return "ERROR: JSON SYNTAX"

        #filling the JSON into the requestArray
        for key, value in requestString.items():
            requestArray[key] = value
            print key + ': ' + value
            
        #if level is defined
        if requestArray.has_key('l'):
            #searching the levels
            for level in xml_object.getElementsByTagName('level'):
                #if requested id is in xml
                if int(requestArray['l']) >= int(xml_object.getElementsByTagName('level').length):
                    return "ERROR: OUT OF RANGE"
                #if level id == requested id
                elif level.getElementsByTagName('id')[0].firstChild.data == requestArray['l']:
                    #print level id and name to the console
                    print 'level ' + level.getElementsByTagName('id')[0].firstChild.data + ": " + level.getElementsByTagName('name')[0].firstChild.data
                    list = level
                    #if room is defined
                    if requestArray.has_key('r'):
                        #searching the rooms on the requested level
                        for room in level.getElementsByTagName('room'):
                            #if requested id is in xml
                            if int(requestArray['r']) >= int(level.getElementsByTagName('room').length):
                                return "ERROR: OUT OF RANGE"
                            #if level id == requested id 
                            elif room.getElementsByTagName('id')[0].firstChild.data == requestArray['r']:
                                #print room id and name to the console
                                print 'room ' + room.getElementsByTagName('id')[0].firstChild.data + ": " + room.getElementsByTagName('name')[0].firstChild.data
                                list = room
                                #if device is defined
                                if requestArray.has_key('d'):
                                    #searching the devices
                                    for device in room.getElementsByTagName('device'):
                                        #if requested id is in xml
                                        if int(requestArray['d']) >= int(room.getElementsByTagName('device').length):
                                            return "ERROR: OUT OF RANGE"
                                        #if device id == requested id 
                                        elif device.getElementsByTagName('id')[0].firstChild.data == requestArray['d']:
                                            #print device id and name to the console
                                            print 'device ' + device.getElementsByTagName('id')[0].firstChild.data + ": " + device.getElementsByTagName('name')[0].firstChild.data
                                            list = device
                                            #if state is defined
                                            if requestArray.has_key('s'):
                                                #searching the state
                                                for state in device.getElementsByTagName('state'):
                                                    #if requested id is in xml
                                                    if int(requestArray['s']) >= int(device.getElementsByTagName('state').length):
                                                        return "ERROR: OUT OF RANGE"
                                                    #if state id == requested id
                                                    elif state.getElementsByTagName('id')[0].firstChild.data == requestArray['s']:
                                                            #print state id and dimension to the console
                                                            print 'state ' + state.getElementsByTagName('id')[0].firstChild.data
                                                            list = state
  
        print 'old value'
        print requestArray['e'] + ': ' + list.getElementsByTagName(requestArray['e'])[0].firstChild.data
        list.getElementsByTagName(requestArray['e'])[0].firstChild.data = requestArray['nv']
        
        print 'new value'
        print requestArray['e'] + ': ' + list.getElementsByTagName(requestArray['e'])[0].firstChild.data
        
        #try to open the file and write new data
        try:
            file = open(Config.absPath + Config.get('XML', file_name), "w")
            print 'open file'
            tmp = xml_object.toxml()
            print 'object parsed'
            file.write(tmp)
            print 'file written'
            file.close()
            print 'file closed'
        except:
            return 'ERROR: NOTHING WRITTEN'
        
        print "SUCCESSFUL"
        return "SUCCESSFUL"     
Exemplo n.º 24
0
    def __init__(self, token, configFile):
        PlugIn.__init__(self)
        self.architecture = "all"


        #plugin itself
        self.content = Container("plugin", token, "Boxee Plugin")

        # hide Plugin from showing up in xml, search, show...
        self.content.visible = True

        global user, host, port
        user = Config.get("Boxee", "user")
        host = Config.get("Boxee", "host")
        port = Config.get("Boxee", "port")

        global np
        np = ""
        #for pair in Config.getSection("LastFM"):
        #    global user,host,port
        #    if (pair[0] == "user"):
        #        user = pair[1]
        #    if (pair[0] == "host"):
        #        host = pair[1]
        #    if (pair[0] == "port"):
        #        port = pair[1]

        print user,host,port
        love = Container("cmd","Love","love")
        skip = Container("cmd","Skip","skip")
        ban = Container("cmd","Ban","ban")
        stop = Container("cmd","Stop","stop")
        playlist = Container("cmd","Playlist","playlist")
        library = Container("cmd","Library","Library")
        pause = Container("cmd","Pause","pause")
        now_playing = Container("cmd","Now Playing","get Now Playing Info")
        coverart = Container("cmd","CoverArt", "get CoverART")
        coverartimage = Container("cmd","CoverArtImage", "get CoverART Image")
        getstate = Container("cmd","State", "get Player State")
        tag = Container("cmd", "Tag", "find Music by Tag")
        similar = Container("cmd","Similar","Play similar artist")
        
        love.setUse(self.love)
        skip.setUse(self.skip)
        ban.setUse(self.ban)
        stop.setUse(self.stop)
        playlist.setUse(self.playlist)
        library.setUse(self.library)
        pause.setUse(self.pause)
        now_playing.setUse(self.getNp)
        similar.setUse(self.similar)
        coverart.setUse(self.getCoverArt)
        coverart.lastCover = ''
        coverart.lastImg = ''
        coverart.rendering = Container.PLAIN
        coverartimage.setUse(self.getCoverArtImage)
        coverartimage.rendering = Container.PLAIN

        getstate.setUse(self.getState)
        tag.setUse(self.tag)
        
        self.content.addChild(love)
        self.content.addChild(ban)
        self.content.addChild(skip)
        self.content.addChild(stop)
        self.content.addChild(playlist)
        self.content.addChild(library)
        self.content.addChild(pause)
        self.content.addChild(now_playing)
        self.content.addChild(coverart)
        self.content.addChild(coverartimage)
        self.content.addChild(getstate)
        self.content.addChild(tag)
        self.content.addChild(similar)
        
        # UI Elements
        self.content.addChild(TextfieldContainer("ui", "SimilarArtist", "PlaySimilarArtiest", target=Config.jid+"/Audio/LastFM/Similar"))
Exemplo n.º 25
0
 def saveEnergy(timestamp, level, room, device, watt):
     #declarations
     level = 'level'+level
     room = 'room'+room
     device = 'device'+device   
     #time the device was on         
     hours = float(time.mktime(time.localtime()) - time.mktime(timestamp)) / 3600.0
     kw = float(watt) / 1000.0
     kwh = float(kw * hours)
     #e.g. Jan-2010
     currentMonth = str(time.strftime("%b-%Y",time.localtime()))
     
     #if the level node is in energy.xml
     if str(energy_object.getElementsByTagName(level)) != '[]':
         print 'level'
         #link the level node
         levelNode = energy_object.getElementsByTagName(level)[0]
         #and so on....
         if str(levelNode.getElementsByTagName(room)) != '[]':
             print 'room'
             roomNode = levelNode.getElementsByTagName(room)[0]
             if str(roomNode.getElementsByTagName(device)) != '[]':
                 print 'device'
                 deviceNode = roomNode.getElementsByTagName(device)[0]
                 if str(deviceNode.getElementsByTagName(currentMonth)) != '[]':
                     print 'month'
                     monthNode = deviceNode.getElementsByTagName(currentMonth)[0]
                     #adds the new kwh to the old value
                     monthNode.firstChild.data = float(monthNode.firstChild.data) + float(kwh)
                     print str(kwh) + ' kWh added'
                 else:
                     #create month with kwh
                     print 'no month'
                     newElement(deviceNode, currentMonth, str(kwh))
             else:
                 #create device, month with kwh
                 print 'no device'
                 newElement(roomNode, device, '')
                 deviceNode = roomNode.getElementsByTagName(device)[0]
                 newElement(deviceNode, currentMonth, str(kwh))
         else:
             #create room, device, month with kwh
             print 'no room'
             newElement(levelNode, room, '')   
             roomNode = levelNode.getElementsByTagName(room)[0]    
             newElement(roomNode, device, '')
             deviceNode = roomNode.getElementsByTagName(device)[0]
             newElement(deviceNode, currentMonth, str(kwh))
     else:
         #create level, room, device, month with kwh
         print 'no level'
         newElement(energy_object.firstChild, level, '')
         levelNode = energy_object.getElementsByTagName(level)[0]
         newElement(levelNode, room, '')   
         roomNode = levelNode.getElementsByTagName(room)[0]    
         newElement(roomNode, device, '')
         deviceNode = roomNode.getElementsByTagName(device)[0]
         newElement(deviceNode, currentMonth, str(kwh))
         
     #save file
     try:
         energy_file = open(Config.absPath + Config.get('XML', 'Energy'), "w")
         print 'open'
         tmp1 = energy_object.toxml()
         print 'new'
         energy_file.write(tmp1)
         print 'written'
         energy_file.close()
         print 'closed'
     except:
         return 'ERROR: NOTHING WRITTEN'
     
     return ''
Exemplo n.º 26
0
    def energy(self, var=''):
        #declarations
        file_name = 'MyEstate'
        requestArray = {}
        #watt, kwh, costs
        wattsRoom = [0, 0, 0]
        
        #month as string: Jan-2010
        currentMonth = time.strftime("%b-%Y", time.localtime())
        #month as int: 6
        current_month = int(time.strftime("%m", time.localtime()))
        returnString = ''
        
        
        #open and parse the file 
        try:
            file = open(Config.absPath + Config.get('XML', file_name), "r")
            xmlString = file.read()
            file.close()
            xml_object = parseString(xmlString)
            
            energy_file = open(Config.absPath + Config.get('XML', 'Energy'), "r")
            energyString =  energy_file.read()
            energy_file.close()
            energy_object = parseString(energyString)
        except:
            return "ERROR: FILE NOT FOUND"
        print var
        
        #building the json
        try:
            requestString = json.loads(var)
        except:
            return "ERROR: JSON SYNTAX"

        #filling the JSON into the requestArray
        for key, value in requestString.items():
            requestArray[key] = value
            print key + ': ' + value
        
        #save the price
        price = float(xml_object.getElementsByTagName('pricePerkWh')[0].firstChild.data)
        
        #return watt, kwh and costs for the given device
        def getWatts(device, levelID, roomID, deviceID, currentMonth = currentMonth, energy_object = energy_object, requestArray = requestArray, price = price):
            #watt = watt, kWh, costs
            getwatts = [0,0,0]
            dim = 'null'
            act = 'null'
            levelID = 'level'+levelID
            roomID = 'room'+roomID
            deviceID = 'device'+deviceID
            #saves the brightness and activated states
            for state in device.getElementsByTagName('state'):
                if str(state.getElementsByTagName('dimension')[0].firstChild.data) == 'brightness':
                    dim = state.getElementsByTagName('currentValue')[0].firstChild.data
                if str(state.getElementsByTagName('dimension')[0].firstChild.data) == 'activated':
                    act = state.getElementsByTagName('currentValue')[0].firstChild.data
            #if device is turned on
            if act == '1':  
                #if device is dimable       
                if dim != 'null':
                    #calculate watt
                    watt = (int(device.getElementsByTagName('watt')[0].firstChild.data)*float(int(dim)/100.0))
                else:
                    #return watt
                    watt = device.getElementsByTagName('watt')[0].firstChild.data
                #calculations
                hours = float(time.mktime(time.localtime()) - time.mktime(time.strptime(str(device.getElementsByTagName('timestamp')[0].firstChild.data), "%d-%m-%Y %H:%M:%S"))) / 3600.0
                kw = float(watt) / 1000.0
                kwh = float(kw * hours)
                #fill in calculatet stuff
                getwatts[0] = int(watt)
                getwatts[1] = float(kwh)
            #search for older consumptions
            #try if the level is already there
            eLevel = energy_object.getElementsByTagName(levelID)
            if str(eLevel) != '[]':
                #and so on ...
                eRoom = eLevel[0].getElementsByTagName(roomID)
                if str(eRoom) != '[]':
                    eDevice = eRoom[0].getElementsByTagName(deviceID)
                    if str(eDevice) != '[]':
                        #so the device is already in energy file
                        if requestArray.has_key('m'):
                            #if older months are requested
                            months = int(requestArray['m'])
                            #calculate the oldest month
                            oldestMonth = current_month-months
                            #for each month between oldest month and current month
                            for months in range(oldestMonth, current_month):
                                #if months of last year are requested
                                if months < 1:
                                    months = 12 + months
                                    if months<10:
                                        #add a 0 and current year -1
                                        tmp = '0' + str(months) + '-' + str(int(time.strftime("%Y", time.localtime()))-1)
                                    else:
                                        #add current year -1
                                        tmp = str(months) + '-' + str(int(time.strftime("%Y", time.localtime()))-1)
                                else:
                                    if months<10:
                                        #add a 0 and current year
                                        tmp = '0' + str(months) + time.strftime("-%Y", time.localtime())
                                    else:
                                        #add current year
                                        tmp = str(months) + time.strftime("-%Y", time.localtime())
                                #node = get month in Jan-2010 format from tmp, which is in 01-2010 format
                                node = eDevice[0].getElementsByTagName(time.strftime("%b-%Y",time.strptime(tmp, "%m-%Y")))
                                print str(node)
                                #if month is there
                                if str(node) != '[]':
                                    txt = node[0].firstChild.data
                                    #add the consumption of this month to the consumption of the device
                                    getwatts[1] = float(getwatts[1]) + float(txt)
                        else:
                            #if no months are requested add only the current month
                            eMonth = eDevice[0].getElementsByTagName(currentMonth)
                            if str(eMonth) != '[]':
                                getwatts[1] = float(getwatts[1]) + float(eMonth[0].firstChild.data)
            
            #calculate the costs
            getwatts[2] = float(getwatts[1]) * float(price)
            #round the float values
            getwatts[0] = round(float(getwatts[0]), 3)
            getwatts[1] = round(float(getwatts[1]), 3)
            getwatts[2] = round(float(getwatts[2]), 3)
            print levelID + ' ' + roomID + ' ' + deviceID + ': ' + str(getwatts[0]) + ' watt; ' + str(getwatts[1]) + ' kWh; ' + str(getwatts[2]) + ' Euro'
            return getwatts
        

        #if more than 12 months are requestet return error
        if requestArray.has_key('m'):
            if int(requestArray['m']) > 12:
                return 'ERROR: TOO MANY MONTHS'
            if int(requestArray['m']) < 1:
                return 'ERROR: TOO FEW MONTHS'
        
        #if a level is requested
        if requestArray.has_key('l'):
            returnString = '{d:['
            #search the levels
            for level in xml_object.getElementsByTagName('level'):
                #if requested id is in xml
                if int(requestArray['l']) >= int(xml_object.getElementsByTagName('level').length):
                    return "ERROR: OUT OF RANGE"
                #save levelID
                levelID = str(level.getElementsByTagName('id')[0].firstChild.data)
                print 'level '+levelID
                if levelID == requestArray['l']:
                    #search the rooms
                    for room in level.getElementsByTagName('room'):
                        #if requested id is in xml
                        if int(requestArray['r']) >= int(level.getElementsByTagName('room').length):
                            return "ERROR: OUT OF RANGE"
                        #save room ID
                        roomID = str(room.getElementsByTagName('id')[0].firstChild.data)
                        if roomID == requestArray['r']:
                            print 'room '
                            #search the devices
                            for device in room.getElementsByTagName('device'):
                                deviceID = str(device.getElementsByTagName('id')[0].firstChild.data)
                                print'device '+deviceID
                                #get the watts, kwh and costs
                                tmp = getWatts(device, levelID, roomID, deviceID)
                                #build json return string with the consumption data
                                returnString += '{id:' + deviceID + ',watt:' + str(tmp[0]) + ',kwh:' + str(tmp[1]) + ',eur:' + str(tmp[2]) + '}'
                                #if this is the last deivce of this room
                                if deviceID == str(room.getElementsByTagName('device').length -1):
                                    returnString += ']}'
                                else:
                                    returnString += ','
                            break
                    break                          
        #if no level is requested
        else:
            returnString = '{l:['
            #for each level
            for level in xml_object.getElementsByTagName('level'):
                #save the ID
                levelID = str(level.getElementsByTagName('id')[0].firstChild.data)
                returnString += '{id:' + levelID + ',r:['
                #for each room
                for room in level.getElementsByTagName('room'):
                    #save the ID
                    roomID = str(room.getElementsByTagName('id')[0].firstChild.data)
                    returnString += '{id:' + roomID
                    #clear the arrays
                    wattsRoom[0] = 0
                    wattsRoom[1] = 0
                    wattsRoom[2] = 0
                    #for each device
                    for device in room.getElementsByTagName('device'):
                        #save the ID
                        deviceID = str(device.getElementsByTagName('id')[0].firstChild.data)
                        #get the consumption data
                        tmp = getWatts(device, levelID, roomID, deviceID)
                        #adds the consumption data of each device to the room arrays
                        wattsRoom[0] = float(wattsRoom[0]) + float(tmp[0])
                        wattsRoom[1] = float(wattsRoom[1]) + float(tmp[1])
                        wattsRoom[2] = float(wattsRoom[2]) + float(tmp[2])
                    #build json with the data
                    returnString += ',watt:' + str(wattsRoom[0]) + ',kwh:' + str(wattsRoom[1]) + ',eur:' + str(wattsRoom[2]) + '}'
                    #if this is the last room of this level
                    if roomID != str(level.getElementsByTagName('room').length -1):
                        returnString += ','
                #json: close the roomarray and write the level consumtions                       
                returnString += ']}'
                #if this is the last level
                if levelID == str(xml_object.getElementsByTagName('level').length -1):
                    #json: close the levelarray and write the "residence" consumtions                       
                    returnString += ']}'
                else:
                    returnString += ','
                    
        print 'return: ' + returnString
        return returnString
Exemplo n.º 27
0
 def vol_down(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" vol down")
Exemplo n.º 28
0
    def state(self, var=''):
        #declarations
        file_name = 'MyEstate'
        requestArray = {}
        response = "ERROR: OUT OF RANGE"
        
        #open and parse the file 
        try:
            file = codecs.open(Config.absPath + Config.get('XML', file_name), "r")
            xmlString = file.read()
            file.close()
            xml_object = parseString(xmlString)
        except:
            return "ERROR: FILE NOT FOUND"

        print var
        
        #building the json
        try:
            requestString = json.loads(var)
        except:
            return "ERROR: JSON SYNTAX"
        
        #filling the JSON into the requestArray
        for key, value in requestString.items():
            #check if the values are digits
            if value.isdigit():
                requestArray[key] = value
                print key + ': ' + value
            else:
                return "ERROR: VALUE IS NOT DIGIT"
        
        #searching the levels
        for level in xml_object.getElementsByTagName('level'): 
            #if level id == requested id
            if level.getElementsByTagName('id')[0].firstChild.data == requestArray['l']: 
                #print level id and name to the console
                print 'level ' + level.getElementsByTagName('id')[0].firstChild.data + ": " + level.getElementsByTagName('name')[0].firstChild.data
                #searching the rooms on the requested level
                for room in level.getElementsByTagName('room'):
                    #if level id == requested id 
                    if room.getElementsByTagName('id')[0].firstChild.data == requestArray['r']: 
                        #print room id and name on the console
                        print 'room ' + room.getElementsByTagName('id')[0].firstChild.data + ": " + room.getElementsByTagName('name')[0].firstChild.data
                        #overwrites the error text with the JSON start
                        response = '{d:['      
                        #searching the devices           
                        for device in room.getElementsByTagName('device'):
                            #print device id and name to the console 
                            print 'device ' + device.getElementsByTagName('id')[0].firstChild.data + ": " + device.getElementsByTagName('name')[0].firstChild.data
                            #JSON: device id and beginning of state
                            response += '{id:' + device.getElementsByTagName('id')[0].firstChild.data + ',s:['
                            #searching the states
                            for state in device.getElementsByTagName('state'):
                                #print state id and its current Value to the console
                                print 'state ' + state.getElementsByTagName('id')[0].firstChild.data + ": value: " + state.getElementsByTagName('currentValue')[0].firstChild.data
                                #JSON: state id and its current Value
                                response += '{id:' + state.getElementsByTagName('id')[0].firstChild.data + ',cv:' + state.getElementsByTagName('currentValue')[0].firstChild.data + '}'
                                #if this is the last state
                                if (str(state.getElementsByTagName('id')[0].firstChild.data) == str(device.getElementsByTagName('state').length - 1)):
                                    #JSON: close the device
                                    response += ']}'
                                else:
                                    #JSON: continue with next state
                                    response += ','
                            #if this is the last device
                            if (str(device.getElementsByTagName('id')[0].firstChild.data) == str(room.getElementsByTagName('device').length - 1)):
                                #JSON: close the room
                                response += ']}'
                            else:
                                #JSON continue with next device
                                response += ','            
        print 'return: ' + response
        return response 
Exemplo n.º 29
0
 def stop(self, string=""):
     os.system(Config.get("iTunes", "scriptpath")+" stop")
Exemplo n.º 30
0
    def state(self, var=''):
        #declarations
        AVR = False
        file_name = 'MyEstate'
        requestArray = {}
        channel = 'null'
        channelNumber = 'null'
        prev_temperature = 'null'
        prev_brightness = 'null'
        dimension_req = 'null'
        value_ok = False
        timestamp = ''
                
        #open and parse the file 
        try:
            file = open(Config.absPath + Config.get('XML', file_name), "r")
            xmlString = file.read()
            file.close()
            xml_object = parseString(xmlString)
            
            energy_file = open(Config.absPath + Config.get('XML', 'Energy'), "r")
            energyString =  energy_file.read()
            energy_file.close()
            energy_object = parseString(energyString)
        except:
            return "ERROR: FILE NOT FOUND"
        print var
        
        #building the json
        try:
            requestString = json.loads(var)
        except:
            return "ERROR: JSON SYNTAX"

        #filling the JSON into the requestArray
        for key, value in requestString.items():
            #check if the values are digits
            if value.isdigit():
                requestArray[key] = value
                print key + ': ' + value
            else:
                return "ERROR: VALUE IS NOT DIGIT"
        
        #creates a new element with content to the given node
        def newElement(where, element, content):
            new_element = energy_object.createElement(element)
            txt = energy_object.createTextNode(content)
            new_element.appendChild(txt)
            return where.appendChild(new_element)
        
        #writes the consumption of a device to the energy.xml
        def saveEnergy(timestamp, level, room, device, watt):
            #declarations
            level = 'level'+level
            room = 'room'+room
            device = 'device'+device   
            #time the device was on         
            hours = float(time.mktime(time.localtime()) - time.mktime(timestamp)) / 3600.0
            kw = float(watt) / 1000.0
            kwh = float(kw * hours)
            #e.g. Jan-2010
            currentMonth = str(time.strftime("%b-%Y",time.localtime()))
            
            #if the level node is in energy.xml
            if str(energy_object.getElementsByTagName(level)) != '[]':
                print 'level'
                #link the level node
                levelNode = energy_object.getElementsByTagName(level)[0]
                #and so on....
                if str(levelNode.getElementsByTagName(room)) != '[]':
                    print 'room'
                    roomNode = levelNode.getElementsByTagName(room)[0]
                    if str(roomNode.getElementsByTagName(device)) != '[]':
                        print 'device'
                        deviceNode = roomNode.getElementsByTagName(device)[0]
                        if str(deviceNode.getElementsByTagName(currentMonth)) != '[]':
                            print 'month'
                            monthNode = deviceNode.getElementsByTagName(currentMonth)[0]
                            #adds the new kwh to the old value
                            monthNode.firstChild.data = float(monthNode.firstChild.data) + float(kwh)
                            print str(kwh) + ' kWh added'
                        else:
                            #create month with kwh
                            print 'no month'
                            newElement(deviceNode, currentMonth, str(kwh))
                    else:
                        #create device, month with kwh
                        print 'no device'
                        newElement(roomNode, device, '')
                        deviceNode = roomNode.getElementsByTagName(device)[0]
                        newElement(deviceNode, currentMonth, str(kwh))
                else:
                    #create room, device, month with kwh
                    print 'no room'
                    newElement(levelNode, room, '')   
                    roomNode = levelNode.getElementsByTagName(room)[0]    
                    newElement(roomNode, device, '')
                    deviceNode = roomNode.getElementsByTagName(device)[0]
                    newElement(deviceNode, currentMonth, str(kwh))
            else:
                #create level, room, device, month with kwh
                print 'no level'
                newElement(energy_object.firstChild, level, '')
                levelNode = energy_object.getElementsByTagName(level)[0]
                newElement(levelNode, room, '')   
                roomNode = levelNode.getElementsByTagName(room)[0]    
                newElement(roomNode, device, '')
                deviceNode = roomNode.getElementsByTagName(device)[0]
                newElement(deviceNode, currentMonth, str(kwh))
                
            #save file
            try:
                energy_file = open(Config.absPath + Config.get('XML', 'Energy'), "w")
                print 'open'
                tmp1 = energy_object.toxml()
                print 'new'
                energy_file.write(tmp1)
                print 'written'
                energy_file.close()
                print 'closed'
            except:
                return 'ERROR: NOTHING WRITTEN'
            
            return ''

                  
        #searching the levels
        for level in xml_object.getElementsByTagName('level'):
            #if level id == requested id
            if level.getElementsByTagName('id')[0].firstChild.data == requestArray['l']:
                #print level id and name to the console
                print 'level ' + level.getElementsByTagName('id')[0].firstChild.data + ": " + level.getElementsByTagName('name')[0].firstChild.data
                #searching the rooms on the requested level
                for room in level.getElementsByTagName('room'):
                    #if level id == requested id 
                    if room.getElementsByTagName('id')[0].firstChild.data == requestArray['r']:
                        #print room id and name to the console
                        print 'room ' + room.getElementsByTagName('id')[0].firstChild.data + ": " + room.getElementsByTagName('name')[0].firstChild.data
                        #searching the devices
                        for device in room.getElementsByTagName('device'):
                            #if device id == requested id 
                            if device.getElementsByTagName('id')[0].firstChild.data == requestArray['d']:
                                #if a channel is defined for this device
                                if device.getElementsByTagName('channel').length != 0 :
                                    #save the channel
                                    channel = device.getElementsByTagName('channel')[0].firstChild.data
                                #if a channelNumber is defined for this device
                                if device.getElementsByTagName('channelNumber').length != 0 :
                                    #save the channelNumber
                                    channelNumber = device.getElementsByTagName('channelNumber')[0].firstChild.data
                                #print device id and name to the console
                                print 'device ' + device.getElementsByTagName('id')[0].firstChild.data + ": " + device.getElementsByTagName('name')[0].firstChild.data
                                #print channel and channelNumber to the console
                                print 'channel: ' + channel + channelNumber
                                #searching the state
                                for state in device.getElementsByTagName('state'):
                                    if state.getElementsByTagName('dimension')[0].firstChild.data == 'temperature':
                                        prev_temperature = state.getElementsByTagName('currentValue')[0].firstChild.data
                                    elif state.getElementsByTagName('dimension')[0].firstChild.data == 'brightness':
                                        prev_brightness = state.getElementsByTagName('currentValue')[0].firstChild.data
                                    #if state id == requested id
                                    if state.getElementsByTagName('id')[0].firstChild.data == requestArray['s']:
                                        #if this state is controllable
                                        if state.getElementsByTagName('controllable')[0].firstChild.data == 'true':
                                            #save the dimension
                                            dimension_req = state.getElementsByTagName('dimension')[0].firstChild.data
                                            #print state id and dimension to the console
                                            print 'state ' + state.getElementsByTagName('id')[0].firstChild.data + ": " + dimension_req
                                            #print old value to the console
                                            print 'old value: ' + state.getElementsByTagName('currentValue')[0].firstChild.data
                                            #if new and old value differs
                                            if state.getElementsByTagName('currentValue')[0].firstChild.data != requestArray['cv']:
                                                if int(requestArray['cv']) >= int(state.getElementsByTagName('minValue')[0].firstChild.data) and int(requestArray['cv']) <= int(state.getElementsByTagName('maxValue')[0].firstChild.data):
                                                    #write new value
                                                    state.getElementsByTagName('currentValue')[0].firstChild.data = requestArray['cv']
                                                    value_ok = True
                                                    #get the old timestamp
                                                    timestamp = time.strptime(str(device.getElementsByTagName('timestamp')[0].firstChild.data), "%d-%m-%Y %H:%M:%S")
                                                    #set timestamp
                                                    device.getElementsByTagName('timestamp')[0].firstChild.data = time.strftime("%d-%m-%Y %H:%M:%S", time.localtime())
                                                else:
                                                    #print error
                                                    print 'ERROR: VALUE IS OUT OF MIN/MAX'
                                                    #return error
                                                    return 'ERROR: VALUE IS OUT OF MIN/MAX' 
                                            else:
                                                #print error
                                                print 'ERROR: VALUE IS ALREADY SET'
                                                #return error
                                                return 'ERROR: VALUE IS ALREADY SET'
                                            #print new value to the console
                                            print 'new value: ' + state.getElementsByTagName('currentValue')[0].firstChild.data
                                        else:
                                            return 'ERROR: NOT CONTROLLABLE'
                                        break
                                break
        
        if value_ok:
            if AVR:
                #get a wrapper instance
                self.bridge = avrBridgePy.avrBridge()
                #get a direct reference to libavrBridgeC
                self.mega = self.bridge.mega
                
                self.mega.setPortPinDir(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "manual")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "plus")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "minus")), self.bridge.OUT)
                
                self.mega.setPortPinDir(int(Config.get("Remote", "channel")), int(Config.get("Remote", "a")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "channel")), int(Config.get("Remote", "b")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "channel")), int(Config.get("Remote", "c")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "channel")), int(Config.get("Remote", "d")), self.bridge.OUT)
                
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "1_0")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "1_1")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "2_0")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "2_1")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "3_0")), self.bridge.OUT)
                self.mega.setPortPinDir(int(Config.get("Remote", "device")), int(Config.get("Remote", "3_1")), self.bridge.OUT)
              
            #if the device is radio controlled
            if channel != 'null' and channelNumber != 'null':
                print 'channel: ' + channel + channelNumber
                print 'channel-Port: ' + Config.get('Remote', channel)
                if AVR: self.mega.setPortPin(int(Config.get("Remote", "channel")), int(Config.get("Remote", channel)), self.bridge.ON)
                
                #possible state values: 0, 1
                if dimension_req == 'activated':
                    print 'switch to ' + requestArray['cv']
                    print 'channelNumber-Port: ' + Config.get('Remote', channelNumber + '_' + requestArray['cv'])
                    if AVR:
                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_' + requestArray['cv'])), self.bridge.ON)
                        time.sleep(0.2)
                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_' + requestArray['cv'])), self.bridge.OFF)
                        self.mega.setPortPin(int(Config.get("Remote", "channel")), int(Config.get("Remote", channel)), self.bridge.OFF)
                    #if device is swiched to 0 the consumption should be saved
                    if str(requestArray['cv']) == '0':
                        if prev_brightness == 'null':
                            print 'no brightness'
                            #save the consumption to the energy file
                            saveEnergy(timestamp, requestArray['l'], requestArray['r'], requestArray['d'], device.getElementsByTagName('watt')[0].firstChild.data)
                        else:
                            print 'brightness'
                            #calculate the consumption and write it to the energy file
                            saveEnergy(timestamp, requestArray['l'], requestArray['r'], requestArray['d'], (int(device.getElementsByTagName('watt')[0].firstChild.data)*float(int(prev_brightness)/100.0)))
                            
                #possible state values: 0-100
                elif dimension_req == 'brightness':
                    #search for the state activated
                    for state in device.getElementsByTagName('state'):
                        if str(state.getElementsByTagName('dimension')[0].firstChild.data) == 'activated':
                            #change the dim value is only allowed if activated == 1
                            if str(state.getElementsByTagName('currentValue')[0].firstChild.data) == '1':
                                print 'dim to ' + requestArray['cv']
                                #if device is swiched to another dim level the consumption should be saved
                                saveEnergy(timestamp, requestArray['l'], requestArray['r'], requestArray['d'], (int(device.getElementsByTagName('watt')[0].firstChild.data)*float(int(prev_brightness)/100.0)))
                                
                                if int(requestArray['cv']) < int(prev_brightness):
                                    #dim darker
                                    print 'channelNumber-Port: ' + Config.get('Remote', channelNumber + '_0')
                                    if AVR:                
                                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_0')), self.bridge.ON)
                                        dimTime = float(9*((float(prev_brightness)-float(requestArray['cv']))/100))
                                        time.sleep(float(dimTime))
                                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_0')), self.bridge.OFF)
                                        self.mega.setPortPin(int(Config.get("Remote", "channel")), int(Config.get("Remote", channel)), self.bridge.OFF)
                                else:
                                    #dim brighter
                                    print 'channelNumber-Port: ' + Config.get('Remote', channelNumber + '_1')
                                    if AVR:
                                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_1')), self.bridge.ON)
                                        dimTime = float(9*((float(requestArray['cv'])-float(prev_brightness))/100))
                                        time.sleep(float(dimTime))
                                        self.mega.setPortPin(int(Config.get("Remote", "device")), int(Config.get('Remote', channelNumber + '_1')), self.bridge.OFF)
                                        self.mega.setPortPin(int(Config.get("Remote", "channel")), int(Config.get("Remote", channel)), self.bridge.OFF)                                   
                                    
                                break
                            else:
                                print 'activated is 0'
                                return 'ERROR SET ACTIVATED FIRST'
                else:
                    return 'ERROR: WRONG DIMENSION'
                    
            else:#no radio controlled device
                print 'no radio controlled device'
                #heater
                if dimension_req == 'temperature':
                    print 'heater was ' + prev_temperature + ' and is set to ' + requestArray['cv'] + ' degree'
                    print 'manual-Port: ' + Config.get('Heater', 'manual')
                    if AVR:
                        self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "manual")), self.bridge.ON)
                        time.sleep(0.1)
                        self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "manual")), self.bridge.OFF)
                        time.sleep(0.2)
                        
                    if int(prev_temperature) < int(requestArray['cv']):
                        #raise temperature
                        for i in range(int(prev_temperature), int(requestArray['cv']) + (int(requestArray['cv']) - int(prev_temperature))):
                            print i + 1                        
                            if AVR:
                                self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "plus")), self.bridge.ON)
                                time.sleep(0.1)
                                self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "plus")), self.bridge.OFF)
                                time.sleep(0.1)
                            
                    else:
                        #lower temperature
                        for i in range(int(requestArray['cv']), int(prev_temperature) + (int(prev_temperature) - int(requestArray['cv']))):
                            print i + 1
                            if AVR:
                                self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "minus")), self.bridge.ON)
                                time.sleep(0.1)
                                self.mega.setPortPin(int(Config.get("Heater", "bridgeport")), int(Config.get("Heater", "minus")), self.bridge.OFF)
                                time.sleep(0.1)                          
            
                    #try to open the file and write new data
            try:
                file = open(Config.absPath + Config.get('XML', file_name), "w")
                print 'open file'
                tmp = xml_object.toxml()
                print 'object parsed'
                file.write(tmp)
                print 'file written'
                file.close()
                print 'file closed'
            except:
                return 'ERROR: NOTHING WRITTEN'

            print 'SUCCESSFUL'
            return 'SUCCESSFUL'
        else:
            print 'ERROR: OUT OF RANGE'
            return 'ERROR: OUT OF RANGE'