Exemple #1
0
def interner_befehl(befehl):
    time.sleep(1)
    if befehl == "deactivate_usb_keys":
        anw_status.deactivate_keys()
    if befehl == "activate_usb_keys":
        anw_status.activate_keys() 
    if befehl == "restart_homecontrol":
        zeit =  time.time()
        now = (strftime("%Y-%m-%d %H:%M:%S",localtime(zeit)))  
        setting_s("Laststart", str(now))        
        exectext = "sudo /home/chris/homecontrol/restart_services.sh"
        os.system(exectext)
    if befehl == "keys_in_hub":
        anw_status.keys_in_hub()
    if befehl == "firew_TV_close":
        router.close_fw("192.168.192.26")
        router.close_fw("192.168.192.29")
    if befehl == "firew_TV_open":
        router.open_fw("192.168.192.26")
        router.open_fw("192.168.192.29") 
    if befehl == "update_filme":
        pass
        #plex.
    if befehl == "send_wc_pix":        
        send_wc_pix()
    if befehl == "poweroff":       
        exectext = "sudo poweroff"
        os.system(exectext)          
Exemple #2
0
def main():
    setting_s("Master_Slave","Slave")
    if constants.redundancy_.typ == 'Master':
        set_master()
    elif constants.redundancy_.typ == 'Slave':
        aes.new_event(description="Running as slave", prio=0, durchsage="", karenz=0)
        constants.redundancy_.master = False
        redundancy = Timer(constants.redundancy_.timeout_receive, set_master_fake)
        redundancy.start() 
        while constants.run:
                (data,addr) = mySocket.recvfrom(SIZE)            
                if (data == "master"):         
                    redundancy.cancel()
                    redundancy = Timer(constants.redundancy_.timeout_receive, set_master_fake)
                    redundancy.start()       
    elif constants.redundancy_.typ == 'auto':
        redundancy = Timer(constants.redundancy_.timeout_receive, set_master)
        redundancy.start() 
        aes.new_event(description="Master-Slave redundancy started", prio=0, durchsage="", karenz=0)
        while constants.run:
                (data,addr) = mySocket.recvfrom(SIZE)            
                if (data == "master"):         
                    redundancy.cancel()
                    redundancy = Timer(constants.redundancy_.timeout_receive, set_master)
                    redundancy.start()       
Exemple #3
0
def set_master():
    constants.redundancy_.master = True
    time.sleep(1)
    aes.new_event(description="Master-Slave changeover, " + constants.name + " ist Master", prio=5, durchsage="", karenz=0)
    setting_s("Master_Slave","Master")
    while constants.run:
        mySocket.sendto("master",(constants.redundancy_.partner_IP,constants.redundancy_.PORT))
        time.sleep(constants.redundancy_.timeout_send)
 def itera(self,some_object, only_change = False):
     dicti = {}
     if self.check_iter(some_object):
         if some_object.get('type') == 'group':
             seting = some_object.get('name')
             if seting <> None:
                 for seti in sets:
                     for kind in some_object.get('children').get('Settings').get('children'):
                         wert = some_object.get('children').get('Settings').get('children').get(kind).get('value')
                         if wert == '': wert = None
                         dicti[kind] = wert
                 for setting in dicti:
                     setting_s(setting,dicti.get(setting))
             else:
                 self.itera(some_object.get('children'))
         else:
             for item in some_object: 
                 self.itera(some_object.get(item))
Exemple #5
0
def main():  
    global heartbeat
    global ldt
    zeit =  time.time()
    now = (strftime("%Y-%m-%d %H:%M:%S",localtime(zeit)))  
    setting_s("Laststart", str(now))
    if selfsupervision:
        while not ping(constants.router_IP):
            #reset_wlan()
            time.sleep(60)        
    heartbeat = Timer(constants.heartbt, heartbeat_sup)
    heartbeat.start()
    ezcontrol.SetSwitchFunction("heartbeat", "1") 
    ldt = Timer(2, last_data_reset)
    conn = pycurl.Curl()  
    conn.setopt(pycurl.URL, constants.xs1_.STREAM_URL)  
    conn.setopt(pycurl.WRITEFUNCTION, on_receive)
    #aes.new_event(description="XS1inputs neugestartet", prio=0)
    conn.perform()
Exemple #6
0
def on_receive(data):
    if not constants.run:
        sys.exit("Error message")
    global heartbeat
    global last_data
    global ldt
    if False:
        ldt.cancel()
        ldt = Timer(1, last_data_reset)
        ldt.start() 
        if last_data == data:
            return
    count = int(setting_r("NumRestart"))
    if count > 0:
        setting_s("NumRestart", str(0))
    if count > 1:
        aes.new_event(description="XS1 wieder erreichbar", prio=3)
        setting_s("XS1_off", "inactive")
#Zerlegung des Empfangs
    value = float(data.split(" ")[-1])
    name = str(data.split(" ")[-3])
    #now = datetime.datetime.now().strftime("%H:%M:%S.%f") 
    #aes.new_event(description="Empfangen: " + name + " " + str(now), prio=0)
#####################
#Heartbeat & Server Steuerung
#####################
    if (("heartbeat" == name) and (value == 0)):
        heartbeat.cancel()
        heartbeat = Timer(constants.heartbt, heartbeat_sup)
        heartbeat.start()   
        ezcontrol.SetSwitchFunction("heartbeat", "1") 
    szns = inputs(name,value)
    for szene in szns:
        if szene <> None:
            scenes.threadExecute(szene, check_bedingung=False, wert = value)
    last_data = data
 def check_all(self):
     Bewohner = self.read_mysql("Bewohner")
     Besucher = self.read_mysql("Besucher")
     Anwesenheit = 0
     Besuch = 0
     Urlaub = True
     Einbruch = True
     dicti = {}
     for name in Bewohner:
         ping_wert_o = name.get("Handy_State")
         ping_wert = self.check_handy(name.get("Handy_IP"), ping_wert_o)
         self.write_mysql(table="Bewohner",name=name.get("Name"),setting="Handy_State",wert=ping_wert)
         usb_wert = name.get("USB_State")
         if (ping_wert > ping_weg or usb_wert >usb_weg): #ansonsten alles aus sobald der schluessel gezogen wird and not(usb_wert < usb_wert_o):
             Anwesenheit += 1
             if str(setting_r(name.get("Name")+"_anwesend")) == "0":
                 aes.new_event(description=name.get("Name")+" heimgekommen", prio=0)
             setting_s(name.get("Name")+"_anwesend","1")
         else:
             if str(setting_r(name.get("Name")+"_anwesend")) == "1":
                 aes.new_event(description=name.get("Name")+" weggegangen", prio=0)                    
             setting_s(name.get("Name")+"_anwesend","0")
         if ping_wert > ping_urlaub or usb_wert > usb_min:    
             Urlaub = False
         if (ping_wert_o < ping_wert):
             Einbruch = False 
     for name in Bewohner:
         usb_wert = name.get("USB_State")
         if (usb_wert >usb_weg):
             Anwesenheit += 1
     if Urlaub:
         Anwesenheit = -1
     if str(setting_r("Einbruch")) == "True" and not Einbruch:
         setting_s("Einbruch","False")
     dicti['Anwesenheit'] = Anwesenheit
     setting_s("Anwesenheit", Anwesenheit)
     dicti['Besuch'] = Besuch
     dicti['Einbruch'] = Einbruch
     return dicti
Exemple #8
0
def heartbeat_sup():
  if selfsupervision:
    zeit =  time.time()
    now = (strftime("%Y-%m-%d %H:%M:%S",localtime(zeit)))  
    setting_s("Autorestart", str(now))
    count = int(setting_r("NumRestart"))
    if count == 0:
        aes.new_event(description="Verbindung unterbrochen XS1inputs", prio=1)
    if ((count > 0) and (setting_r("XS1_off") == "inactive")):
        aes.new_event(description="XS1 nicht erreichbar", prio=2)
        setting_s("XS1_off", "Active")
    setting_s("NumRestart", str(count + 1))
    exectext = "sudo killall python"
    print "connection lost"
    if ping(constants.router_IP):
        os.system(exectext)
    else:
        reset_wlan()
        os.system(exectext)   
Exemple #9
0
def Tuer_auf():
    Anwesend_init = setting_r("Anwesenheit")
    if str(setting_r("Status")) in ["Schlafen", "Abwesend", "Urlaub"]:
        einbruch = True
        setting_s("Einbruch","True")
        set_szene("Einbruch_1")
        set_szene("Einbruch_Sofort")
        #setting_s("Status","Einbruch")
    else:
        einbruch = False
    #alle weggewesen     
    i = 0
    while i < 7:
        i = i + 1    
        akt_status = anw_status.check_all()
        if akt_status.get("Einbruch") == False:
            einbruch = False
            setting_s("Einbruch","False") 
            if str(setting_r("Status")) in ["Abwesend", "Urlaub"]: 
                set_szene("Heimgekommen")
            if str(setting_r("Status")) in ["Schlafen"]: 
                set_szene("einer_heimgekommen")                
            i = 60
        if str(setting_r("Status")) in ["Wach", "Besuch"]:
            einbruch = False
            setting_s("Einbruch","False") 
            i = 60  
        if Anwesend_init > akt_status.get("Anwesenheit"):
            aes.new_event(description="Jemand gegangen", prio=0)
            Anwesend_init = akt_status.get("Anwesenheit")
            #!!!!!!!!!!!!!achtung noch die passenden Szenen setzen
            #einer gegangen einer schlaeft check if this gets even executed then            
        time.sleep(10)
    #if einbruch:
    #    setting_s("Einbruch","True")
    #else:
    #    setting_s("Einbruch","False")
    if str(setting_r("Einbruch")) == "True":
        aes.new_event(description="Einbruch", prio=3.1)
        Tuer_auf()
Exemple #10
0
#syncliste += ["gcm_users"]
##syncliste += ["Szenen"]
#syncliste += ["Wecker"]
##syncliste += ["Sideboard"]
#for table in syncliste:
#    try:
#        ssync.export(table, "XS1DB")
#        ssync.trunc_import(table, "XS1DB") 
#        aes.new_event(description="Success sync "+table, prio=0)
#    except:
#        aes.new_event(description="Error sync "+table, prio=0)

# init
init_settings = {'V00WOH1SRA1DI01':1,'V00WOH1SRA1DI04':1,'V00WOH1SRA1DI05':1}
for setting in init_settings:
    setting_s(setting, init_settings[setting])


threadliste = []

t = threading.Thread(name="xs1", target=inp_xs1.main, args = [])
threadliste.append(t)
t.start()

#t = threading.Thread(name="udp",target=inp_udp.main, args = [])
#threadliste.append(t)
#t.start()

t = threading.Thread(name="udp.bidirekt", target=inp_udp.bidirekt, args = [])
threadliste.append(t)
t.start()
Exemple #11
0
    def __bedingung__(self,bedingungen, verbose = False):
        erfuellt = True
        settings = settings_r() 
        if type(bedingungen) == dict:
#==============================================================================
#             Deprecated
#==============================================================================
            for bedingung in bedingungen:
                if settings.get(bedingung) == None:
                    setting_s(bedingung, '')
                try:
                    groesser = bedingungen.get(bedingung).find('>')
                    kleiner = bedingungen.get(bedingung).find('<')
                    if groesser >-1 and kleiner >-1:
                        schwelle_u = float(bedingungen.get(bedingung)[groesser+1:kleiner])
                        if float(settings.get(bedingung)) <= schwelle_u:
                            erfuellt = False
                        schwelle_o = float(bedingungen.get(bedingung)[kleiner+1:len(bedingungen.get(bedingung))])
                        if float(settings.get(bedingung)) >= schwelle_o:
                            erfuellt = False    
                    elif groesser >-1:
                        schwelle = float(bedingungen.get(bedingung)[groesser+1:len(bedingungen.get(bedingung))])
                        if float(settings.get(bedingung)) <= schwelle:
                            erfuellt = False                     
                    elif kleiner >-1:
                        schwelle = float(bedingungen.get(bedingung)[kleiner+1:len(bedingungen.get(bedingung))])
                        if float(settings.get(bedingung)) >= schwelle:
                            erfuellt = False        
                    else:
                        if not(str(settings.get(bedingung)) in bedingungen.get(bedingung)):
                            erfuellt = False
                except Exception:
                    if not(str(settings.get(bedingung)) in bedingungen.get(bedingung)):
                        erfuellt = False      
        elif type(bedingungen) == list:
#==============================================================================
#             new way
#==============================================================================
        #[('Temperatur_Rose','>',['sett','Temperatur_Balkon'])]
            for bedingung in bedingungen:
                if settings.get(bedingung[0]) == None:
                    setting_s(bedingung, '')                
                item, operand, wert = bedingung
                item = settings.get(item)
                if verbose: print item, operand, wert
                if operand == '=':
                    if not float(item) == float(wert):
                        erfuellt = False 
                elif operand == '==':
                    if not str(item) == str(wert):
                        erfuellt = False                         
                elif operand == '<':
                    if not float(item) < float(wert):
                        erfuellt = False  
                elif operand == '>':
                    if not float(item) > float(wert):
                        erfuellt = False   
                elif operand == '<=':
                    if not float(item) <= float(wert):
                        erfuellt = False   
                elif operand == '>=':
                    if not float(item) >= float(wert):
                        erfuellt = False      
                elif operand == '!':
                    if (item) == (wert):
                        erfuellt = False    
                elif operand == 'in':
                    if not (item) in (wert):
                        erfuellt = False                          
        if verbose: print "Ergebniss: ",erfuellt
        return erfuellt
Exemple #12
0
    def execute(self, szene, check_bedingung=False, wert = 0):
        szene_dict = mdb_read_table_entry(constants.sql_tables.szenen.name, szene)
        start_t = datetime.datetime.now()
#        print start_t, szene_dict.get("Beschreibung"), szene_dict.get("Follows")
        #check bedingung
        bedingungen = {}
        global kommando_dict
        erfuellt = True
        erfolg = False
        szn_id = uuid.uuid4()
        self.kommando_dict[szn_id] = []
        if str(szene_dict.get("Bedingung")) <> "None":
            bedingungen = eval(str(szene_dict.get("Bedingung")))   
        erfuellt = self.__bedingung__(bedingungen)
        if str(szene_dict.get("Latching")) <> 'None':
            next_start = szene_dict.get("LastUsed") + datetime.timedelta(hours=0, minutes=int(szene_dict.get("Latching")), seconds=0)
            if start_t < next_start:
                erfuellt = False
        if str(szene_dict.get("Karenz")) <> 'None':
            Karenz = (szene_dict.get("Karenz"))
        else:
            Karenz = 0.03  
        Prio = (szene_dict.get("Prio"))            
        if check_bedingung:
            return erfuellt
#==============================================================================
# commandos to devices and internal commands        
#==============================================================================
        if erfuellt:
            if (str(szene_dict.get("Delay")) <> "None"):
                time.sleep(float(szene_dict.get("Delay")))
            if str(szene_dict.get("Beschreibung")) in ['None','']:
                aes.new_event(description="Szenen: " + szene, prio=Prio, karenz = Karenz)
            else:
                aes.new_event(description= str(szene_dict.get("Beschreibung")), prio=Prio, karenz = Karenz) 
            interlocks = {}  
            hue_count = 0
            hue_delay = 0            
            if str(szene_dict.get("AutoMode")) == "True":
                interlocks = mdb_read_table_entry(constants.sql_tables.szenen.name,"Auto_Mode")
            for idk, key in enumerate(szene_dict):        
                if ((szene_dict.get(key) <> "") and (str(szene_dict.get(key)) <> "None") and (str(interlocks.get(key)) in ["None", "auto"])):
                    kommandos = self.__return_enum__(szene_dict.get(key))
                    if constants.redundancy_.master:
                        for kommando in kommandos:
                            if key in cmd_devs:
                                t_list = self.kommando_dict.get(szn_id)
                                t_list.append([key,kommando])
                                self.kommando_dict[szn_id] = t_list
                            text=szene_dict.get("Durchsage")
                            t = threading.Thread(target=self.__sub_cmds__, args=[szn_id, key, kommando, text])
                            t.start()  
#==============================================================================
# Internal                               
#==============================================================================
            key = "intCmd"
            if ((szene_dict.get(key) <> "") and (str(szene_dict.get(key)) <> "None") ):#and (str(interlocks.get(key)) in ["None", "auto"])):
                kommandos = self.__return_enum__(szene_dict.get(key))
                for kommando in kommandos:
                    #print kommando, kommandos.get(kommando)
                    set_del = Timer(0, interna.execute, [kommando])
                    #timer set to 0 for following actions
                    set_del.start()                              
#==============================================================================
# change settings table                                
#==============================================================================
            key = "Setting"
            if ((szene_dict.get(key) <> "") and (str(szene_dict.get(key)) <> "None") and (str(interlocks.get(key)) in ["None", "auto"])):
                kommandos = self.__return_enum__(szene_dict.get(key))
                for kommando in kommandos:
#                    #print kommando, kommandos.get(kommando)
#                    set_del = Timer(0, setting_s, [str(kommando), str(kommandos.get(kommando))])
#                    #timer set to 0 for following actions
#                    set_del.start() 
                    # solution above could give timing issues
                    setting_s(str(kommando), str(kommandos.get(kommando)))
            mdb_set_table(table=constants.sql_tables.szenen.name, device=szene, commands={'LastUsed':start_t})
        else:
            if str(szene_dict.get("Beschreibung")) in ['None','']:
                aes.new_event(description="Szene nicht erfuellt: " + szene, prio=1, karenz = Karenz)
            else:
                aes.new_event(description="Szene nicht erfuellt: " + str(szene_dict.get("Beschreibung")), prio=1, karenz = Karenz)                 
#==============================================================================
# cacnel timers                              
#==============================================================================     
        if ((szene_dict.get("Cancels") <> "") and (str(szene_dict.get("Cancels")) <> "None")):
            kommandos = self.__return_enum__(szene_dict.get("Cancels"))   
            for kommando in kommandos:           
                self.sz_t.cancel_timer(parent = szene, child = kommando)
#==============================================================================
# start timer with following actions                               
#==============================================================================
        if ((szene_dict.get("Follows") <> "") and (str(szene_dict.get("Follows")) <> "None")):
            kommandos = self.__return_enum__(szene_dict.get("Follows"))
            for kommando in kommandos:
                szn = kommando[0]
                dlay = kommando[1]
                ex_re = kommando[2]
                immer = False
                depErfolg = 0
                if len(kommando) > 3:
                    immer = not kommando[3]
                if len(kommando) == 5:
                    depErfolg = kommando[4]
                if (immer or erfuellt) and depErfolg == 0:
                    if ex_re == 0:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = False, retrig = True)
                    elif ex_re == 1:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = True, retrig = True)
                    elif ex_re == 2:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = False, retrig = False)  
#==============================================================================
# Check for timeout
#==============================================================================
        while datetime.datetime.now() - start_t < self.timeout:
            t_list = self.kommando_dict.get(szn_id)
            time.sleep(.1)
            if len(t_list) == 0:
                erfolg = True
                # write back to table
                break
        t_list = self.kommando_dict.get(szn_id)
        for item in t_list:
            aes.new_event(description="CMD Timeout: " + str(item), prio=1, karenz = 0.03)
        del self.kommando_dict[szn_id]
#==============================================================================
# start timer with following actions nur wenn erfolg oder nicht erfolg                              
#==============================================================================
        if ((szene_dict.get("Follows") <> "") and (str(szene_dict.get("Follows")) <> "None")):
            kommandos = self.__return_enum__(szene_dict.get("Follows"))
            for kommando in kommandos:
                szn = kommando[0]
                dlay = kommando[1]
                ex_re = kommando[2]
                immer = False
                depErfolg = 0
                if len(kommando) > 3:
                    immer = kommando[3]
                if len(kommando) == 5:
                    depErfolg = kommando[4]
                if (immer or erfuellt) and ((depErfolg == 1 and erfolg) or (depErfolg == 2 and not erfolg)):
                    if ex_re == 0:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = False, retrig = True)
                    elif ex_re == 1:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = True, retrig = True)
                    elif ex_re == 2:
                        self.sz_t.retrigger_add(parent = szene,delay = float(dlay), child = szn, exact = False, retrig = False)           
        return erfolg
Exemple #13
0
 def set_device(self, player, command, text):
     if command in ["man", "auto"]:
         set_val_in_szenen(device=player, szene="Auto_Mode", value=command) 
     player, p_uid, playerName = self.get_addr(player)            
     if player in self.Devices:
         player = self.Devices.get(str(player))
     playerName = self.Names.get(player)
     if str(command) == "Pause":
         self.SetPause(player)
     elif str(command) == "Play":
         self.SetPlay(player)                
     elif str(command) == "Save":
         self.sonos_write_szene(player)                   
     elif str(command) == "Announce_Time":
         self.sonos_write_szene(player)
         lt = localtime()
         stunde = int(strftime("%H", lt))
         minute = int(strftime("%M", lt)) 
         if (minute <> 0) and (minute <> 30):
             text = "Es ist " + str(stunde) + " Uhr und " + str(minute) + " Minuten."
             laenge = downloadAudioFile(text)
             self.sonos_read_szene(player, mdb_read_table_entry(table.name,"TextToSonos"))
             time.sleep(laenge + 1)            
             self.sonos_read_szene(player, mdb_read_table_entry(table.name,playerName))
     elif str(command) == "Durchsage":
         self.durchsage(text)      
     elif str(command) == "Ansage":
         self.ansage(text,player)             
     elif str(command) == "Return":
         self.sonos_read_szene(player, mdb_read_table_entry(table.name,playerName), hergestellt = False)          
     elif ((str(command) == "resume") ):
         time.sleep(60)
         self.sonos_read_szene(player, mdb_read_table_entry(table.name,playerName))            
     elif (str(command) == "lauter"):
         ActVol = self.GetVolume(player)
         increment = 8
         VOLUME = ActVol + increment 
         self.SetVolume(player, VOLUME)
         return
     elif (str(command) == "leiser"):
         ActVol = self.GetVolume(player)
         increment = 8
         VOLUME = ActVol - increment 
         self.SetVolume(player, VOLUME)
         return
     elif (str(command) == "inc_lauter"):
         ActVol = self.GetVolume(player)
         if ActVol >= 20: increment = 8
         if ActVol < 20: increment = 4
         if ActVol < 8: increment = 2
         VOLUME = ActVol + increment 
         self.SetVolume(player, VOLUME)
     elif (str(command) == "inc_leiser"):
         ActVol = self.GetVolume(player)
         if ActVol >= 20: increment = 8
         if ActVol < 20: increment = 4
         if ActVol < 8: increment = 2
         VOLUME = ActVol - increment 
         self.SetVolume(player, VOLUME)                
     elif (str(command) == "WeckerAnsage"):
         self.SetPause(player)
         self.SetVolume(player, 20)
         setting_s("Durchsage", str(crn.next_wecker_heute_morgen()))
         text = setting_r("Durchsage")        
         laenge = downloadAudioFile(text)
         self.sonos_read_szene(player, mdb_read_table_entry(table.name,"TextToSonos"))
         time.sleep(laenge + 1)  
         self.SetPause(player) 
     elif (str(command) == "EingangWohnzi"):
         self.StreamInput(player, self.WohnZiZone)             
     elif ((str(command) <> "resume") and (str(command) <> "An") and (str(command) <> "None")):
         sonos_szene = mdb_read_table_entry(table.name,command)
         self.sonos_read_szene(player, sonos_szene)                                 
     return True
Exemple #14
0
def set_szene(name):
    global schlummern
    global bad_ir
    if str(name) == "None" or str(name) == "":
        return
    if "Tuer_auf" in str(name):
    #if str(name) == "Tuer_auf":
        t = threading.Thread(target=Tuer_auf)
        t.start()
    if str(name) == "Schluessel_weg":
        t = threading.Thread(target=Schluessel_weg)
        t.start()         
    szene = mdb_read_table_entry(constants.sql_tables.szenen.name,name)
    if str(szene) == "{}": return
    no_list = ["Priority", "Beschreibung", "Status", "Durchsage"]
    bedingungen = {}
    erfuellt = True
    if str(szene.get("Bedingung")) <> "None":
        bedingungen = eval(szene.get("Bedingung"))    
        erfuellt = True
    settings = settings_r()
    for bedingung in bedingungen:
        try:
            groesser = bedingungen.get(bedingung).find('>')
            kleiner = bedingungen.get(bedingung).find('<')
            if groesser >-1 and kleiner >-1:
                schwelle_u = float(bedingungen.get(bedingung)[groesser+1:kleiner])
                if float(settings.get(bedingung)) <= schwelle_u:
                    erfuellt = False
                schwelle_o = float(bedingungen.get(bedingung)[kleiner+1:len(bedingungen.get(bedingung))])
                if float(settings.get(bedingung)) >= schwelle_o:
                    erfuellt = False    
            elif groesser >-1:
                schwelle = float(bedingungen.get(bedingung)[groesser+1:len(bedingungen.get(bedingung))])
                if float(settings.get(bedingung)) <= schwelle:
                    erfuellt = False                     
            elif kleiner >-1:
                schwelle = float(bedingungen.get(bedingung)[kleiner+1:len(bedingungen.get(bedingung))])
                if float(settings.get(bedingung)) >= schwelle:
                    erfuellt = False        
            else:
                if not(str(settings.get(bedingung)) in bedingungen.get(bedingung)):
                    erfuellt = False
        except Exception as e:
            if not(str(settings.get(bedingung)) in bedingungen.get(bedingung)):
                erfuellt = False 
    if str(szene.get("XS1_Bedingung")) <> "None" :
         xs1_bedingung = eval(szene.get("XS1_Bedingung"))
         if str(ezcontrol.GetSwitch(str(xs1_bedingung.keys()[0]))) <> str(xs1_bedingung[xs1_bedingung.keys()[0]]):
             erfuellt = False
    if not(name in no_event) and erfuellt:
        if str(szene.get("Beschreibung")) in ['None','']:
            aes.new_event(description="Szenen: " + name, prio=eval(szene.get("Priority")), karenz = 0.03)
        else:
            aes.new_event(description= str(szene.get("Beschreibung")), prio=eval(szene.get("Priority")), karenz = 0.03)
    if erfuellt:
        interlocks = {}
        if str(szene.get("Auto_Mode")) == "True":
            interlocks = mdb_read_table_entry(constants.sql_tables.szenen.name,"Auto_Mode")
        hue_count = 0
        hue_delay = 0
        if str(szene.get("Durchsage")) <> "None":
            setting_s("Durchsage", str(szene.get("Durchsage"))) 
        if ((szene.get("Amp") <> "") and (str(szene.get("Amp")) <> "None")):
            setting_s("AV_cmd", "1")
            setting_s("Kommando", str(szene.get("Amp")))
        if name in ["WeckerMute", "WeckerPhase1"] or "Schlummern" in name:
            schlummern.cancel()
        if name in ["Bad_ir"]:
            bad_ir.cancel()   
        for idk, key in enumerate(szene):        
            if ((szene.get(key) <> "") and (str(szene.get(key)) <> "None") and (str(interlocks.get(key)) in ["None", "auto"])):
                if (type(szene.get(key)) == str) and (not(str(key) in no_list)):
                    try:
                        if type(eval(szene.get(key))) == list or type(eval(szene.get(key))) == dict:
                            kommandos = eval(szene.get(key))
                        else:
                            kommandos = [szene.get(key)]
                    except NameError as serr:
                        kommandos = [szene.get(key)]
                else:
                    kommandos = [szene.get(key)]
                if constants.redundancy_.master:
                    if key in ezcontrol_devices:
                        for kommando in kommandos:
                            t = threading.Thread(target=xs1_set_szene, args=[key, kommando])
                            t.start()
                    elif key == "set_Task":
                        for kommando in kommandos:
                            mes.send_direkt(to=mes.alle, titel="Setting", text=str(kommando))  
                    elif key == "set_Task_zuhause":
                        for kommando in kommandos:
                            mes.send_zuhause(to=mes.alle, titel="Setting", text=str(kommando))                          
                            #mes.send_direkt(mes.tf201,"Setting",str(kommando))                    
                    elif key in sonos_devices:
                        #for kommando in kommandos:
                        t = threading.Thread(target=sonos_set_szene, args=[sonos_devices.get(key), kommandos])
                        t.start()                
                    elif key in hue_devices:
                        for kommando in kommandos:
                            if hue_count > 1:
                                hue_delay += 0.75
                                hue_count = 0
                            hue_del = Timer(hue_delay, hue_set_szene, [key, kommando])
                            hue_del.start()
                            hue_count += 1
                    elif key in sat_names:
                        for kommando in kommandos:
                            t = threading.Thread(target=send_cmd_satellite, args=[key,kommando])
                            t.start()                          
                    elif key == "TV":
                        for idx, kommando in enumerate(kommandos):
                            folgen = Timer((float(idx)/5), tv_set_szene, [kommando])
                            folgen.start()                                                 
                    elif key == "Interner_Befehl":
                        for kommando in kommandos:
                            t = threading.Thread(target=interner_befehl, args=[kommando])
                            t.start()                            
        for idk, key in enumerate(szene):
            if ((szene.get(key) <> "") and (str(szene.get(key)) <> "None") and (str(interlocks.get(key)) in ["None", "auto"])):
                if (type(szene.get(key)) == str) and (not(str(key) in no_list)):
                    try:
                        if type(eval(szene.get(key))) == list or type(eval(szene.get(key))) == dict:
                            kommandos = eval(szene.get(key))
                        else:
                            kommandos = [szene.get(key)]
                    except NameError as serr:
                        kommandos = [szene.get(key)]
                else:
                    kommandos = [szene.get(key)]  
                if key in setting:
                    for kommando in kommandos:
                        aes.new_event(description=key + ": " + str(kommando), prio=0)
                        setting_s(key, str(kommando))
                elif key == "Zusatz_Status":
                    for kommando in kommandos:
                        set_del = Timer(1, setting_s, [str(kommando), str(kommandos.get(kommando))])
                        set_del.start()                                           
        if ((szene.get("Szene_folgt") <> "") and (str(szene.get("Szene_folgt")) <> "None")):
            try:
                if type(eval(szene.get("Szene_folgt"))) == list:
                    kommandos = eval(szene.get("Szene_folgt"))
                else:
                    kommandos = [szene.get("Szene_folgt")]
            except NameError as serr:
                kommandos = [szene.get("Szene_folgt")]
            try:
                if type(eval(szene.get("folgt_nach"))) == list:
                    delays = eval(szene.get("folgt_nach"))
                else:
                    delays = [szene.get("folgt_nach")]
            except NameError as serr:
                delays = [szene.get("folgt_nach")]       
            for index, kommando in enumerate(kommandos):
                if "Schlummern" in name:
                    schlummern = Timer(float(delays[index]), set_szene, [str(kommando)])
                    schlummern.start()   
                elif "Bad_ir" in name:
                    bad_ir = Timer(float(delays[index]), set_szene, [str(kommando)])
                    bad_ir.start()                      
                else:
                    folgen = Timer(float(delays[index]), set_szene, [str(kommando)])
                    folgen.start()
        con = mdb.connect(constants.sql_.IP, constants.sql_.USER, constants.sql_.PASS, constants.sql_.DB)
        with con:
            cur = con.cursor()
            sql = 'UPDATE Szenen SET LastUsed = CURRENT_TIMESTAMP WHERE Name = "'+ name + '"' 
            cur.execute(sql)
        con.close()