Esempio n. 1
0
 def list_devices(self):
     comands = mdb_read_table_entry(constants.sql_tables.szenen.name,"Device_Type")
     liste = []
     for comand in comands:
         if comands.get(comand) == "HUE":
             liste.append(comand)
     #liste.remove("Name")
     return liste
Esempio n. 2
0
def send_cmd_satellite(device, szene):
    if szene in ["man", "auto"]:
        mysql_con.set_automode(device=device, mode=szene)
        return
    for item in pies:
        if item.name == str(device):
            command = mdb_read_table_entry(str(item.command_set),szene)
            command["device"] = device
            item.send_udp_cmd(command)
Esempio n. 3
0
 def list_commands(self,device='alle'):
     liste = [] 
     list_cmds_of = []
     if device == 'alle':
         list_cmds_of = self.list_devices()
     else:
         list_cmds_of.append(device)
     for sates in list_cmds_of:
         cmds_table=mdb_read_table_entry(table.name,sates).get('command_set')
         if self.__check_table_exists__(cmds_table):           
             comands = mdb_get_table(cmds_table)
             for comand in comands:
                 liste.append(comand.get("Name"))
     return liste        
Esempio n. 4
0
 def set_device(self, device, commd): 
     if commd in ["man", "auto"]:
         set_val_in_szenen(device=device, szene="Auto_Mode", value=commd)
         return True      
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     satellit=mdb_read_table_entry(table.name,device)
     command = {}
     if satellit.get('command_set') == 'server':
         command['Szene'] = commd
     else:
         command = mdb_read_table_entry(satellit.get('command_set'),commd)
     command["Device"]=device
     data = ""
     print command
     if str(satellit.get('PORT')) <> 'None':
         try:
             satelliten.mysocket_old.sendto(str(command),(satellit.get('IP'),satellit.get('PORT')))
             return True
         except:
             pass
     if str(satellit.get('BiPORT')) <> 'None':
         for i in range(0,3):
             try:
                 satelliten.mysocket.settimeout(10)
                 s.connect((satellit.get('IP'),satellit.get('BiPORT')))
                 s.send(str(command))
                 data=s.recv(1024)
                 s.close()
             except:
                 s.close()
             if data  == "True":
                 break
     if data  == "True":
         return True
     else:
         return False
Esempio n. 5
0
 def listCommandTable(self,device='alle', nameReturn = True):
     liste = [] 
     list_cmds_of = []
     if device == 'alle':
         list_cmds_of = self.list_devices()
     elif device=="forSave":
         list_cmds_of = mdb_read_table_column(table.name,"Name")            
     else:
         list_cmds_of.append(device)
     for sates in list_cmds_of:
         cmds_table=mdb_read_table_entry(table.name,sates)
         if self.__check_table_exists__(cmds_table.get('command_set')):           
             if nameReturn:
                 liste.append(cmds_table.get('Name'))
             else:
                 liste.append(cmds_table.get('command_set'))
     return liste
Esempio n. 6
0
 def dict_commands(self,device='alle'):
     liste = {'':1,'man':2,'auto':3}
     itera = 3
     list_cmds_of = []
     if device == 'alle':
         list_cmds_of = self.list_devices()
     else:
         list_cmds_of.append(device)
     for sates in list_cmds_of:
         cmds_table=mdb_read_table_entry(table.name,sates).get('command_set')
         if self.__check_table_exists__(cmds_table):           
             comands = mdb_get_table(cmds_table)
             for comand in comands:
                 itera +=1
                 liste[comand.get("Name")] = itera 
         elif cmds_table == 'server':
             comands = mdb_read_table_column(constants.sql_tables.szenen.name, 'Name')
             for comand in comands:
                 itera +=1
                 liste[comand] = itera                 
     return liste        
Esempio n. 7
0
from PyQt4 import QtGui, QtCore
from PyQt4.Qt import *
import sys
import git
import pyqtgraph as pg
import numpy as np
from threading import Timer
import time
import datetime
import os

import pyqtgraph.parametertree.parameterTypes as pTypes
from pyqtgraph.parametertree import Parameter, ParameterTree

descs = mdb_read_table_entry(constants.sql_tables.szenen.name,"Description")

aes = alarm_event()

xs1 = myezcontrol(constants.xs1_.IP)
hue = hue_lights()
sn = sonos()
tv = TV()
sat = satelliten()
scenes = szenen()
crons = cron()
xs1_devs = xs1.list_devices()
hue_devs = hue.list_devices()
sns_devs = sn.list_devices()
tvs_devs = tv.list_devices()
sat_devs = sat.list_devices()
Esempio n. 8
0
def neuTrig():
    vals = mdb_read_table_entry(db="cmd_inputs",entry=str(comboBox3.currentText()),column='Description')
    mdb_add_table_entry("cmd_inputs",vals)
Esempio n. 9
0
 def newSzene(self):
     global szenen
     self.szenen = [mdb_read_table_entry(db='LeereVorlage',entry=self.szene_to_read)]
     self.set_paratree()        
Esempio n. 10
0
    def set_paratree(self):
        global p, name
        #szenen = mdb_get_table(db='set_Szenen')
        tipps = mdb_read_table_entry(db='set_Szenen',entry='Description')
        stock_list = []
        stockwerke = []
        zimmer_list = []
        zimmer = []
        for szene in self.szenen:
            for item in szene:
                if str(item) in cmd_devs:
                    name = str(item)
                    stock_list.append(name[0:3])
                    zimmer_list.append(name[0:6])
        stock_list = list(set(stock_list))
        zimmer_list = list(set(zimmer_list))
        for stock in stock_list:
            stockwerke.append(StockRaum(stock))
        for zim in zimmer_list:
            zimmer.append(StockRaum(zim))            
        params = []
        for szene in self.szenen:
            if szene.get('Name') == 'LeereVorlage' or self.neue_szene:
                szene['Name']= 'NeueSzene'
                szene['Id'] = maxSzenenId()-maxSzenenId()%10 +10
                self.neue_szene = False
            szn_dict = {}
            if str(szene.get('Beschreibung')) <> 'None':
                self.name = szene.get('Beschreibung')
            else:
                self.name = 'Szenen Name: '+str(szene.get('Name'))
            szn_dict['name'] = self.name
            szn_dict['type']='group'
            szn_dict['expanded'] = True
            szn_l_child = []    
            #del szene['Name']
            for item in szene:
                szn_d_child = {}
                szn_d_child_l = []
                if str(item) in cmd_devs:
                    zwname = szenen_beschreibung.get(item)
                    if zwname == None:
                        zwname = str(item)
                    kom_group = KommandoGroup(name=str(item), title = zwname,cmds=self.get_commando_set(str(item)), children=self.dict_constructor_(str(item),self.__return_enum__(szene.get(item))))
                    for zim in zimmer:
                        if zim.name in str(item):
                            zim.addChild(kom_group)
                            if kom_group.shouldExpand():
                                zim.expand(True)
                                #Stockwerke auch expandieren                                   
                elif str(item) in ['Setting']: 
                    for child in self.__return_enum__(szene.get(item)):
                        if type(self.__return_enum__(szene.get(item))) == dict:
                            szn_d_child_l.append({'name': child, 'type': 'str', 'value': self.__return_enum__(szene.get(item)).get(child)})
                    szn_d_child = ScalableGroup(name= item, children= szn_d_child_l, expanded = False) 
                    szn_l_child.append(szn_d_child) 
                elif str(item) in ['Bedingung']: 
                    szn_d_child = {'name': item, 'type': 'action', 'expanded': True} 
                    kinder = self.__return_enum__(szene.get(item))
                    for child in kinder:
                        if type(kinder) == dict:
                            szn_d_child_l.append({'name': 'Bedingung %d' % (len(szn_d_child_l)+1), 'type': 'group', 'children':[{'name': 'Setting', 'type': 'str', 'value': child},
                        {'name': 'Operand', 'type': 'list', 'values':['==','=','<','>','<=','>=','in','!'], 'value': '='},{'name': 'Bedingung', 'type': 'str', 'value': kinder.get(child)}],'tip': "This is a checkbox"})
                        else:
                            if child <> None:
                                szn_d_child_l.append({'name': 'Bedingung %d' % (len(szn_d_child_l)+1), 'type': 'group', 'children':[{'name': 'Setting', 'type': 'list','values':['']+sorted(settings_r()), 'value': child[0]},
                        {'name': 'Operand', 'type': 'list', 'values':['==','=','<','>','<=','>=','in','!'],'value': child[1]},{'name': 'Bedingung', 'type': 'str', 'value': child[2]}]})
                    szn_d_child['children']= szn_d_child_l
                    szn_l_child.append(szn_d_child)                             
                elif str(item) in ['setTask']: 
                    szn_d_child = {'name': 'Befehl an Handys', 'type': 'action', 'expanded': True} 
                    kinder = self.__return_enum__(szene.get(item))  
                    for kind in kinder:       
                        if kind <> None:
                            szn_d_child_l.append({'name': 'Befehl %d' % (len(szn_d_child_l)+1), 'type': 'group', 'children':[{'name': 'An wen', 'type': 'str', 'value': kind[0]},
                        {'name': 'Befehl', 'type': 'str', 'value': kind[1]}]})  
                    szn_d_child['children']= szn_d_child_l
                    szn_l_child.append(szn_d_child)                             
                elif str(item) in ['Follows']: 
                    szn_d_child = {'name': 'Szene folgt', 'type': 'action', 'expanded': True} 
                    kinder = self.__return_enum__(szene.get(item))  
                    for kind in kinder:       
                        if kind <> None:
                            if len(kind)<4:
                                immer = True
                            else:
                                immer = kind[3]
                            if len(kind)<5:
                                depErfolg = 0
                            else:
                                depErfolg = kind[4]                            
                            szn_d_child_l.append({'name': 'Szene %d' % (len(szn_d_child_l)+1), 'type': 'action', 'children':[{'name': 'Szene', 'type': 'list','value': kind[0], 'values':szn_lst},
                        {'name': 'nach [s]', 'type': 'str', 'value': kind[1]},{'name': 'Verlaengerbar', 'type': 'list', 'values':{'Verlaengerbar':0,'nur exact':1,'fest':2}, 'value': kind[2]},{'name': 'Abhaengig Bedingung', 'type': 'bool', 'value': immer}
                        ,{'name': 'Abhaengig Erfolg', 'type': 'list', 'values':{'egal':0,'bei Erfolg':1,'bei Nichterfolg':2}, 'value': depErfolg}]})  
                    szn_d_child['children']= szn_d_child_l
                    szn_l_child.append(szn_d_child) 
                elif str(item) in ['Cancels']: 
                    szn_d_child = {'name': 'Folgende stoppen', 'type': 'action', 'expanded': True} 
                    kinder = self.__return_enum__(szene.get(item))  
                    for kind in kinder:       
                        if kind <> None:
                            szn_d_child_l.append({'name': 'Stops %d' % (len(szn_d_child_l)+1), 'type': 'list','value': kind, 'values':szn_lst})
                    szn_d_child['children']= szn_d_child_l
                    szn_l_child.append(szn_d_child)                     
                elif str(item) in ['AutoMode']: 
                    szn_d_child['name'] = str(item)
                    szn_d_child['type'] = 'bool'
                    szn_d_child['expanded'] = False
                    if str(szene.get(item)) <> "None":
                        szn_d_child['value'] = eval(szene.get(item))
                    else:
                        szn_d_child['value'] = False
                    szn_l_child.append(szn_d_child)                     
                else:
                    szn_d_child['name'] = str(item)
                    if str(item) in ['Delay']:
                        szn_d_child['type'] = 'float'
                        szn_d_child['step'] = 0.1
                        if str(szene.get(item)) <> "None":
                            szn_d_child['value'] = float(szene.get(item))
                        else:
                            szn_d_child['value'] = None
                    elif str(item) in ['Prio']:
                        szn_d_child['type'] ='list'
                        szn_d_child['values'] = {'Kein Event':-1,'Normales Event':0,'Problem ohne Hinweis':1,'Hinweis wenn zuhause':2,'immer Hinweis':3,'Hinweis wenn wach':4,
                                                 'Achtung wenn wach':5,'Alarm':6}
                        if str(szene.get(item)) <> "None":
                            szn_d_child['value'] = float(szene.get(item))                          
                    elif str(item) in ['Gruppe']:
                        szn_d_child['type'] ='list'
                        szn_d_child['values'] = szn_typs
                        if str(szene.get(item)) <> "None":
                            szn_d_child['value'] = str(szene.get(item))
                        else:
                            szn_d_child['value'] = ''                          
                    else:
                        szn_d_child['type'] = 'str'
                        if str(szene.get(item)) <> "None":
                            szn_d_child['value'] = str(szene.get(item))
                        else:
                            szn_d_child['value'] = ''
                        try:
                            if tipps[str(item)] <> None:
                                szn_d_child['tip'] = str(tipps[str(item)])
                        except:
                            pass
                    szn_d_child['expanded'] = False
                    szn_l_child.append(szn_d_child)         

            for stock in stockwerke:
                for zim in zimmer:
                    if stock.name in zim.name:
                        stock.addChild(zim.build())
                        if zim.expanded:
                            stock.expand(True)
                szn_l_child.append(stock.build())
            szn_dict['children']= szn_l_child
            params.append(szn_dict)
        ichilds, schilds = [], []
        iquellen, squellen = getSzenenSources(self.szene_to_read)
        for quelle in iquellen:
            ichilds.append({'name': quelle.get('Name'), 'type': 'action', 'value': quelle.get('Name'),'autoIncrementName':True})
        for quelle in squellen:
            schilds.append({'name': quelle.get('Name'), 'type': 'action', 'value': quelle.get('Name'),'autoIncrementName':True})   
        szn_dict = {'name': 'Sources', 'type': 'group', 'children': [
                {'name': 'Inputs', 'type': 'group', 'autoIncrementName':True, 'children':ichilds },
                {'name': 'Szenen', 'type': 'group', 'autoIncrementName':True, 'children':schilds }    
            ]}       
        params.append(szn_dict)  
        szn_dict =     {'name': 'Save/Restore functionality', 'type': 'group', 'children': [
                {'name': 'Speichere Szene', 'type': 'action'},
                {'name': u'Prüfe Bedingung', 'type': 'action'},
                {'name': 'Execute', 'type': 'action'},
                {'name': 'Neue Szene', 'type': 'action'},
                {'name': 'Dupliziere Szene', 'type': 'action'}                 
            ]}
        params.append(szn_dict)
        self.p = Parameter.create(name='params', type='group', children=params)
        try:
            self.p.param('Save/Restore functionality', 'Speichere Szene').sigActivated.connect(self.save)
            self.p.param('Save/Restore functionality', u'Prüfe Bedingung').sigActivated.connect(self.check_bedingung)
            self.p.param('Save/Restore functionality', 'Execute').sigActivated.connect(self.execute)
            #self.p.param('Save/Restore functionality', 'Neue Szene').sigActivated.connect(self.newSzene)            
            self.p.param(self.name, 'Befehl an Handys').sigActivated.connect(self.add_task)
            self.p.param(self.name, 'Bedingung').sigActivated.connect(self.add_bedingung)
            self.p.param(self.name, 'Szene folgt').sigActivated.connect(self.addSzene)
            self.p.param(self.name, 'Folgende stoppen').sigActivated.connect(self.addCancels)
            self.linkSzene()
        except:
            pass
        return params
Esempio n. 11
0
 def update(self, neue_szene):
     self.szene_to_read = neue_szene
     self.szenen = [mdb_read_table_entry(db='set_Szenen',entry=self.szene_to_read,recalc=False)]
     self.set_paratree()        
Esempio n. 12
0
sns_cmds = sn.dict_commands()
tvs_devs = tv.list_devices()
tvs_cmds = tv.dict_commands()
sat_devs = sat.list_devices()
sat_cmds = sat.dict_commands()
cmd_devs = xs1_devs + hue_devs + sns_devs + tvs_devs + sat_devs
szn_lst = sorted(szn.list_commands())

cmd_lsts = ['out_hue','out_Sonos']
cmd_lsts += sat.listCommandTable('alle',nameReturn = False)
cmd_lsts = list(set(cmd_lsts))

szn_typs = ['','Favorit','Intern','Scanner','Wecker','Lichter','Klima', 'Multimedia']
stockwerke = ['Vm1','V00','A00','V01','V02','']

szenen_beschreibung = mdb_read_table_entry(db='set_Szenen',entry='Description')
constants.redundancy_.master = True

#==============================================================================
# Todo:
#   all list to be updated (no need to use dicts)
#   gehe zu szenen
#   codes mit listen ersetzen
#==============================================================================


## test subclassing parameters
## This parameter automatically generates two child parameters which are always reciprocals of each other
class ComplexParameter(pTypes.GroupParameter):
    def __init__(self, **opts):
        opts['type'] = 'bool'
Esempio n. 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
Esempio n. 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() 
Esempio n. 15
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
Esempio n. 16
0
 def set_device(self, device, commd):
     h_dev = Light(hbridge, device)
     keys = ['bri', 'hue', 'sat', 'transitiontime']
     szene = mdb_read_table_entry(table.name,commd)
     success = False
     if szene.get('bri')<=0:
         szene['bri'] = 0
         szene['on'] = False
     if commd in ["man", "auto"]:
         set_val_in_szenen(device=device, szene="Auto_Mode", value=commd)
         return True
     elif commd == 'Save': 
         hue = hbridge.get_light(device, 'hue')
         bri = hbridge.get_light(device, 'bri')
         sat = hbridge.get_light(device, 'sat')
         an = hbridge.get_light(device, 'on') 
         #{'hue': '7', 'bri': '2', 'sat': 'True', 'on': 'False'}
         setting = {'hue': hue, 'bri': bri, 'sat': sat, 'an': an}
         mdb_set_table(table.name,device, setting)
         return True
     elif commd == 'Umschalten':
         an = hbridge.get_light(device, 'on') 
         if an:
             szene['on'] = False
         else:
             szene['on'] = True
     elif commd == 'sz_toggle':
         an = hbridge.get_light(device, 'on') 
         if an:
             commd="SZ_Aus"
         else:
             szene['on'] = True
     bright = szene.get('bri')
     if bright <> None and bright>0:
         szene['bri'] = int(bright)
     if bright <> None and bright<=0:
         pass            
     if str(szene.get('on')) == "1" or str(szene.get('on')) == "True":
         success = h_dev.on
         retry = 1
         while not success and retry < max_retry:
             try:
                 hbridge.set_light(device, {'on':True}) 
                 success = h_dev.on
             except:
                 time.sleep(1)
                 success = False
                 retry += 1
         if not success:
             return success            
         time.sleep(0.5)
     command = {}
     for key in keys:
         if ((szene.get(key) <> "") and (str(szene.get(key)) <> "None")):
             command[key] = int(szene.get(key))
     if command <> {} and h_dev.on:
         success = False
         retry = 1
         while not success and retry < max_retry:
             try:
                 hbridge.set_light(device, command)
                 success = True
             except:
                 time.sleep(1)
                 success = False 
                 retry += 1
     if str(szene.get('on')) == "0" or str(szene.get('on')) == "False":
         success = not h_dev.on
         retry = 1
         if 'transitiontime' in command:
             if command['transitiontime'] > 0:
                 time.sleep(command['transitiontime']/10)
         while not success and retry < max_retry:
             try:
                 hbridge.set_light(device, {'on':False})  
                 success = not h_dev.on
             except:
                 time.sleep(1)
                 success = False 
                 retry += 1
     set_val_in_szenen(device=device, szene="Value", value=szene.get('on'))
     if not h_dev.reachable:
         success = False
         aes.new_event(description=str(device) + " not reachable", prio=1)
     return success
Esempio n. 17
0
MarantzSocket = socket( AF_INET, SOCK_DGRAM )

BETT_IP   = '192.168.192.24'
BETT_PORT = 5000
BettSocket = socket( AF_INET, SOCK_DGRAM )

RaspBMC_IP   = '192.168.192.24'
PORT_NUMBER = 5000
RaspBMC = socket( AF_INET, SOCK_DGRAM )

TuerSPi_IP   = '192.168.192.32'
TuerSPi_sock = socket( AF_INET, SOCK_DGRAM )

#plex = PlexServer()

typ_dict = mdb_read_table_entry(constants.sql_tables.szenen.name,"Device_Typ")
ezcontrol_devices = []
TF_LEDs = []
hue_devices = []
setting = []
sat_names = []
for device in typ_dict:
    if typ_dict.get(device) == "EZControl":
        ezcontrol_devices.append(device)
    if typ_dict.get(device) == "TF_LEDs":
        TF_LEDs.append(device)
    if typ_dict.get(device) == "Hue":
        hue_devices.append(device)   
    if typ_dict.get(device) == "setting":
        setting.append(device)   
    if typ_dict.get(device) == "satellite":