def runNow(self):
		try:
			if ((self._ruleUID is not None) and (getRuleManager() is not None)):
				getLogger().debug(("Manual execute rule '{}' UID='{}'").format(self.getConfigName(), self._ruleUID))
				getRuleManager().runNow(self._ruleUID)
		except:
			LogException()
Exemplo n.º 2
0
	def to_java_calendar(cls, value):
		try:
			if isinstance(value, Calendar):
				return value
    
			if isinstance(value, datetime.datetime):
				c = Calendar.getInstance()
				c.set(Calendar.YEAR, value.year)
				c.set(Calendar.MONTH, value.month - 1)
				c.set(Calendar.DAY_OF_MONTH, value.day)
				c.set(Calendar.HOUR_OF_DAY, value.hour)
				c.set(Calendar.MINUTE, value.minute)
				c.set(Calendar.SECOND, value.second)
				c.set(Calendar.MILLISECOND, value.microsecond / 1000)
				return c

			if isinstance(value, Date):
				c = Calendar.getInstance()
				c.time = value
				return c
			
			if isinstance(value, DateTime):
				return value.toGregorianCalendar()
				
			if isinstance(value, DateTimeType):
				return value.calendar
		except:
			LogException()
 def EventHandler_TriggerStateChanged(self, event):
     try:
         #TODO:: Find a better way than calling the full Cron Job
         self.getManager().onCronJobMaintain()
     except:
         LogException()
         return
Exemplo n.º 4
0
 def __init__(self, _itemName):
     try:
         ItemEventCore.__init__(self, _itemName)  #, moduleName)
         self.oldState = ""
         self.newState = ""
     except:
         LogException()
    def onCronJob(self):
        getLogger().debug(
            ("'onCronJob' called for '{}'....").format(self.getName()))
        try:
            curConditionState = self.GetConditionActiveStatus()
            curRequestedState = self.GetRequestedTriggerState()
            curAllowedState = curConditionState & curRequestedState

            getLogger().debug(
                ("'onCronJob' called for '{}'....").format(self.getName()))
            if (curConditionState):
                for itemName, curItem in self._arrVirtualSwitches.items():
                    getLogger().debug(
                        ("'onCronJob' processing item '{}' ('{}')....").format(
                            itemName, curItem))
                    physicalItem = itemRegistry.getItem(itemName)
                    #events.sendCommand(curItem, self.getStateInactive())getLogger().debug(("Calling 'forceState for '{}' requestedState='{}' curState='{}' conditionState='{}'....").format(itemName, curRequestedState, str(curItem.state).upper(), curConditionState))
                    newState = curItem._physicalDevice.getStateInactive()
                    if (curRequestedState):
                        newState = curItem._physicalDevice.getStateActive()

                    if (newState != physicalItem.state):
                        events.sendCommand(physicalItem, newState)

            else:
                getLogger().debug(
                    "'onCronJob' skipping (ConditionState is FALSE)")
        except:
            LogException()
            return
    def __init__(self,
                 name,
                 arrTimeSchedule,
                 arrOutputItems,
                 arrConditions=[],
                 description=''):

        try:
            getLogger().debug((
                "Initialize 'ScheduleRule': Name='{}, TimeSchedule='{}', OutputItems='{}', Conditions='{}'"
            ).format(name, arrTimeSchedule, arrOutputItems, arrConditions))

            #Validate TimeIntervals
            for idx in range(len(arrTimeSchedule)):
                if (isinstance(arrTimeSchedule[idx], TimeInterval) == False):
                    getLogger().error(
                        "'" + name + "' has invalid TimeInterval at index " +
                        str(idx) +
                        ", a valid parameter must be of type 'TimeInterval'")
                    self._configValid = False

            #First add conditions (assume they are easiest to evaluate)
            conditions = arrConditions
            conditions.append(TimeScheduleCondition(arrTimeSchedule))

            #No TriggerItems!
            BaseRule.__init__(self, name, description, [], arrOutputItems,
                              conditions)

        except:
            LogException()
            return
    def EvaluateTrigger(self, event):
        try:
            ruleUID = None
            if (self._proxyHandler is not None):
                ruleUID = self._proxyHandler.getRuleUID()

            getLogger().debug(
                "EvaluateTrigger called for rule '{}' because item '{}' was changed or updated to state '{}' (Event='{}' RuleUID='{}')"
                .format(self.getName(), event.itemName, str(event.getState()),
                        event.event, ruleUID))

            newActiveState = False
            for curTriggerName, curTrigger in self._arrVirtualTriggers.iteritems(
            ):
                newActiveState = newActiveState or curTrigger.isActive()

            if (self.GetRequestedTriggerState() != newActiveState):
                self.SetRequestedTriggerState(newActiveState)

            #Do the update (which checks both Trigger and Conditions)
            self.UpdateState()

        except:
            LogException()
            return
Exemplo n.º 8
0
 def __init__(self, arrTimeInterval):
     try:
         self._schedules = arrTimeInterval
         BaseCriteria.__init__(self, "")
         #TODO:: Validate if all intervals actual is a TimeInterval
     except:
         LogException()
 def _isStateActive(self, activeStr):
     try:
         if (str(self._item.getState()) == activeStr):
             return True
     except:
         LogException()
     return False
Exemplo n.º 10
0
	def Add(self, newRule):

		try:
			if (isinstance(newRule, BaseRule)==False):
				#getLogger().error(u"Configuration '{}' is instance of '{}', it should be instance of class that inherits from 'BaseConfig'".format(newRule.getName().decode('utf8'), getClassName(newRule)))
				getLogger().error("Configuration '{}' is instance of '{}', it should be instance of class that inherits from 'BaseConfig'".format(newRule.getName(), getClassName(newRule)))
				return False

			getLogger().debug(("Adding Rule Type='{}',  ConfigName='{}', OutputItems='{}'").format(newRule.__class__.__name__, newRule.getName(), str(newRule.getOutputItems())))
						
			# Initialize rule 
			newRule.InitializeConfig(self)
			
			if (newRule.RequiresService(RequiredServiceEnum.ASTRO)):
				getLogger().debug("Rule '{}' requires 'Astro' service".format(newRule.getName()))
				self.astroUseCount = self.astroUseCount + 1
				
			getLogger().debug(("Adding Rule '{}' to dictionary (Id='{}')").format(newRule.getName(), newRule.getId()))
			self.dictRules[newRule.getId()] = newRule
			if (self.dictRules.has_key(newRule.getId())):
				getLogger().debug("Rule '{}' was added successfully (Id='{}')".format(newRule.getName(), newRule.getId()))
			else:
				getLogger().error("Rule '{}' was not added to dictionary (Id='{}')".format(newRule.getName(), newRule.getId()))
		except:
			LogException()
			return False	
Exemplo n.º 11
0
	def createVirtualOutputAdvanced(self, virtualItemName, physicalDeviceName, actualItem, strSwitchPurpose = ""):
		curVirtualSwitch = None
		try:
			getLogger().debug("Create VirtualSwitch '" + str(physicalDeviceName) + "' for virtualItem='" + virtualItemName +"'")
			
			# 1. Get/Create Physical Switch
			# ######################################################################
			physicalDevice = self.createPhysicalDevice(physicalDeviceName)
			if (physicalDevice == None):
				getLogger().error(("Unable to create PhysicalDevice for '{}'.").format(physicalDeviceName))
				return None
				
			# 1. Create VirutalSwitch
			# ######################################################################
			uniqueName = RuleManager.GenerateVirtualItemUniqueName(virtualItemName, physicalDevice.getName(), strSwitchPurpose)
								
			if (isinstance(actualItem, SwitchOutput)):
				curVirtualSwitch = VirtualSwitch(uniqueName, physicalDevice, actualItem.getActivateDelay(), actualItem.getDeactivateDelay())
				
			elif (isinstance(actualItem, DimmerOutput)):
				curVirtualSwitch = VirtualDimmer(uniqueName, physicalDevice, actualItem.getActiveState(), actualItem.getDeactiveState(), actualItem.getActivateDelay(), actualItem.getDeactivateDelay())

			else:
				curVirtualSwitch = VirtualSwitch(uniqueName, physicalDevice, actualItem.getActivateDelay(), actualItem.getDeactivateDelay())


			if (self.dictVirtualSwitches.has_key(curVirtualSwitch.getId())):
				getLogger().error("VirtualSwitch with name '" + uniqueName + "' already exist")
			else:
				self.dictVirtualSwitches[curVirtualSwitch.getId()] = curVirtualSwitch
				getLogger().info("Added new VirtualSwitch '" + curVirtualSwitch.getName() + "' to dictionary")
				getLogger().debug("New VirtualSwicth dictionary: '" + str(self.dictVirtualSwitches) + "'")
		except:
			LogException()
		return curVirtualSwitch
Exemplo n.º 12
0
	def _subscribeTriggerEvent(self, ruleId, triggerName, trigger):
		try:
			getLogger().debug("'_subscribeTriggerEvent': ruleId='{}' triggerName='{}".format(ruleId, triggerName))
			# TODO:: Validate if item has a Physical Switch if it is a item related switch
			
			#register callback for item related switches (to PhysicalDevice)
			'''
			if (isinstance(trigger, CronTrigger)):
				triggerHandler = self._ruleCronMaintain

			el
			'''
			if (isinstance(trigger, StartupTrigger)):
				triggerHandler = self._ruleStartup
			else:
				if self._dictRuleProxies.has_key(ruleId):
					triggerHandler = self._dictRuleProxies[ruleId]
				
			if (triggerHandler is not None):
				getLogger().info("'subscribeTriggerEvent' - Adding '{}'".format(triggerName))
				triggerHandler._AddTriggerCore(trigger)
			else:
				getLogger().info("Failed to subscribe trigger event for '{}' (ruleId='{}')".format(triggerName, ruleId))
			

		except:
			LogException()
Exemplo n.º 13
0
	def createPhysicalDevice(self, deviceName):
		try:
			# 1. Check that items exist in openHAB
			# ######################################################################
				
		
			# 2. Check if it already exists in the dictionary, else create
			# ######################################################################
			if (self.dictPhysicalDevices.has_key(deviceName)==False):

				getLogger().info("Creating new PhysicalDevice '" + deviceName + "'")
				device = DeviceFactory.Create(deviceName)
				
				if (device is None):
					getLogger().error(("New PhysicalDevice '{}' could not be created!!!!").format(deviceName))
					return None
					
				self.dictPhysicalDevices[deviceName] = device
								
				getLogger().debug("New PhysicalDevice added to dictionary: '" + str(self.dictPhysicalDevices) + "'")
				getLogger().debug("Added new PhysicalDevice '" + deviceName + "' to triggers")
				

		except:
			LogException()
			return None
			
		# 3. return PhysicalDevice
		# ######################################################################
		return self.dictPhysicalDevices[deviceName]
Exemplo n.º 14
0
    def isIntervalActive(self):
        try:
            strBeginTime = self.getStartTime()
            strEndTime = self.getEndTime()
            dateToday = getDateToday()
            curTime = DateTime()

            calculatedStartTime = ParseTimeStringToDate(dateToday, self._begin)
            calculatedEndTime = ParseTimeStringToDate(dateToday, self._end)

            #End is before start -> interval is over midnight
            if calculatedEndTime.isBefore(calculatedStartTime):
                if (curTime.isAfter(calculatedStartTime)):
                    calculatedEndTime = calculatedEndTime.plusDays(1)

                elif (curTime.isBefore(calculatedEndTime)):
                    calculatedStartTime = calculatedStartTime.minusDays(1)

                else:
                    calculatedEndTime = calculatedEndTime.plusDays(1)

            getLogger().debug((
                "Processing interval '{}' - '{}' -> '{}' - '{}'  - Current Time '{}', isActive='{}'"
            ).format(self.getStartTime(), self.getEndTime(),
                     calculatedStartTime, calculatedEndTime, curTime,
                     (curTime.isAfter(calculatedStartTime)
                      and curTime.isBefore(calculatedEndTime))))

            return (curTime.isAfter(calculatedStartTime)
                    and curTime.isBefore(calculatedEndTime))

        except:
            LogException()

        return False
Exemplo n.º 15
0
	def subscribeItemStateChangedEvent(self, ruleUID, itemName):
		try:
			triggerName = itemName
			getLogger().info("Adding ItemStateChangeTrigger for item '{}', triggerName='{}', ruleUID='{}'".format(itemName, triggerName, ruleUID))
			self._subscribeTriggerEvent(ruleUID, itemName, ItemStateChangeTrigger(itemName, None, None, triggerName))
		except:
			LogException()
Exemplo n.º 16
0
	def updateState(self, newValue):
		try:
			getLogger().debug(("Calling 'updateState' with newValue='{}' for '{}' (ActivateDelay='{}', DeactivateDelay='{}')").format(newValue, self.getName(), self.delayActivate, self.delayDeactivate))
			if (newValue==True):
				if self.delayActivate==0:
					self.incrementUsage()
				else:
					getLogger().debug(("Calling Calling Timer to activate Delay='{}'").format(self.delayActivate))
					if (self._delayActivateTimer is not None):
						self._delayActivateTimer.cancel()
					self._delayActivateTimer = threading.Timer(self.delayActivate, self.incrementUsage)
					self._delayActivateTimer.start()
					
			else:
				if self.delayDeactivate==0:
					self.decrementUsage()
				else:
					getLogger().debug(("Calling Calling Timer to deactivate Delay='{}'").format(self.delayDeactivate))
					if (self._delayDeactivateTimer is not None):
						self._delayDeactivateTimer.cancel()
						
					self._delayDeactivateTimer = threading.Timer(self.delayDeactivate, self.decrementUsage)
					self._delayDeactivateTimer.start()
		except:
			LogException()
	def AddItemCommandTrigger(self, itemName):
		try:
			triggerName = itemName
			getLogger().info("Adding ItemCommandTrigger for item='{}', trigger='{}'".format(itemName, triggerName))
			self._AddTriggerCore(ItemCommandTrigger(itemName, triggerName=triggerName), triggerName)
		except:
			LogException()
Exemplo n.º 18
0
	def Create(cls, itemName):
		try:
			curItem = scope.itemRegistry.getItem(itemName)
			
			getLogger().debug(("DeviceFactory: Item accepts datatypes: '{}'").format(curItem.getAcceptedDataTypes()))

			#
			# BinaryDevice
			# #############################################
			
			#Check if we should create a OnOffDevice
			if (len(list(set(curItem.getAcceptedDataTypes()) & set(OnOffDevice.getAcceptedTypes())))>0):
				return OnOffDevice(itemName)

			#Check if we should create a OpenClosedDevice
			elif (len(list(set(curItem.getAcceptedDataTypes()) & set(OpenClosedDevice.getAcceptedTypes())))>0):
				return OpenClosedDevice(itemName)

			#Check if we should create a NumberDevice
			elif (len(list(set(curItem.getAcceptedDataTypes()) & set(NumberDevice.getAcceptedTypes())))>0):
				return NumberDevice(itemName, moduleName)
			
			#Check if we should create a StringDevice
			elif (len(list(set(curItem.getAcceptedDataTypes()) & set(StringDevice.getAcceptedTypes())))>0):
				return StringDevice(itemName)
			
			else:
				getLogger().error(("ItemType for '{}' not supported in DeviceFactory.Create()").format(itemName))
				
		except:
			LogException()
		
		return None
Exemplo n.º 19
0
    def Add(self, arrConditions):
        try:

            for current in arrConditions:
                isValid = False
                curCondition = current

                if (isinstance(curCondition, basestring)):
                    if (isItemBinaryType(curCondition)):
                        condition = BinaryCriteria.CreateInstance(curCondition)
                        curCondition = condition
                        self.conditions.append(condition)
                        isValid = True

                #TODO:: Do check if it supports conditions?
                elif (isinstance(curCondition, BaseCriteria)):
                    self.conditions.append(curCondition)
                    isValid = True

                if (isValid == False):
                    getLogger().error(
                        "Invalid condition added to ConditionManager. A string must refer to either a 'OnOff' or a 'OpenClosed' Item in openHAB (Condition='"
                        + str(curCondition) + "')")
                    return False

                getLogger().debug(
                    ("Condition '{}' added to ConditionManager.").format(
                        curCondition.getName()))

        except:
            LogException()
    def __init__(self, name, description, arrTriggerItems, arrOutputItems,
                 arrConditions):
        try:
            self.requestedTriggeredState = False
            self.actualTriggeredState = False

            BaseCore.__init__(self, name)
            self._description = description
            self._configValid = True
            self._mgr = None
            self._proxyHandler = None
            self._conditionMgr = ConditionManager()

            self._arrRequiredService = []
            self._arrVirtualTriggers = {}
            self._arrVirtualSwitches = {}

            self._arrOutputItems = arrOutputItems
            self._arrTriggerItems = arrTriggerItems
            self._conditionMgr.Add(arrConditions)

            getLogger().debug((
                "Created new rule '{}' - Triggers='{}', Outputs='{}', Conditions='{}'"
            ).format(name, self._arrTriggerItems, self._arrOutputItems,
                     arrConditions))
        except:
            LogException()
Exemplo n.º 21
0
 def doesMethodExist(self):
     try:
         if self._methodName in dir(custom_scripts):
             return True
     except:
         LogException()
     return False
Exemplo n.º 22
0
    def _evaluateViritualSwitch(self, curOffset, actSequence):
        activate = False
        getLogger().info((
            "_evaluateViritualSwitch: actSequence='{}' curOffset='{}'").format(
                actSequence, curOffset))

        try:
            for curSequence in actSequence:
                getLogger().info((
                    "Evaluate sequence '{}'  (begin='{}' end='{}', curOffset='{}')"
                ).format(curSequence.getName(), curSequence.getBeginOffset(),
                         curSequence.getEndOffset(), curOffset))

                if ((curSequence.getBeginOffset() <= curOffset)
                        and (curOffset < curSequence.getEndOffset())):
                    getLogger().debug(("  Light '{}' is ACTIVE").format(
                        curSequence.getName()))
                    activate = True
                    break
                else:
                    getLogger().debug(("  Light '{}' is INACTIVE").format(
                        curSequence.getName()))
        except:
            LogException()
        finally:
            getLogger().info(("_evaluateViritualSwitch: DONE! activate='{}'"
                              ).format(activate))

        return activate
Exemplo n.º 23
0
	def __init__(self, _name, _description):
		
		try:
			#Initialize empty dictionary for physical devices
			self.dictPhysicalDevices = {}
			self.dictVirtualSwitches = {}
			self._dictRuleProxies = {} 
			self.arrConditionalItems = []
			self.description = _description
			BaseCore.__init__(self, _name)
			
			
			# Create Housekeeping Cron Job
			#ruleCronMaintain = CronRuleFactory("IntelliSwitch - {} (Maintenance)".format(_name), _description, self)
			#ruleCronMaintain.AddCronTrigger(EVERY_MINUTE)
			#self._ruleCronMaintain = ruleCronMaintain
			
			# TODO:: Fix Startup Rule - Considder if it is really needed
			self._ruleCronMaintain = None
			self._ruleStartup = None 

			#StartupRuleFactory(_name, _description, self)
			#self._dictRuleProxies = {} 
		except:
			LogException()
Exemplo n.º 24
0
	def fireEvent(self, event):
		try:
			getLogger().debug("fireEvent called for '" + self.getName() + "' event='" + str(event) + "'")
			for key, value in self.callbacks.iteritems():
				getLogger().debug("Calling callback for subscriber='" + str(key) + "'")
				value(event)
		except:
			LogException()
Exemplo n.º 25
0
	def RegisterProxyRule(self, ruleProxy):
		try:
			if (ruleProxy.getId() not in self._dictRuleProxies):
				self._dictRuleProxies[ruleProxy.getId()] = ruleProxy
			return ruleProxy.getId()
		except:
			LogException()
		return None
Exemplo n.º 26
0
	def EventHandler_TriggerStateChanged(self, event):
		try:
		
			self.onEvent(event)
			if (self._eventCallback is not None):
				self._eventCallback(event)
		except:
			LogException()
	def AddItemStateUpdateTrigger(self, itemName):
		try:
			triggerName = itemName
			getLogger().info("Adding ItemStateUpdateTrigger for item='{}', trigger='{}'".format(itemName, triggerName))
			newTrigger = ItemStateUpdateTrigger(itemName, triggerName=triggerName)
			self._AddTriggerCore(newTrigger, triggerName)
		except:
			LogException()
Exemplo n.º 28
0
    def __init__(self, begin, end):
        try:
            self._begin = begin
            self._end = end

            BaseCore.__init__(self, "")
        except:
            LogException()
 def __init__(self, itemName, stateActivated, stateDeactivated,
              activateDelay, deactivateDelay):
     try:
         BaseOutput.__init__(self, itemName, stateActivated,
                             stateDeactivated, activateDelay,
                             deactivateDelay)
     except:
         LogException()
 def EventHandler_ServiceDataUpdated(self, serviceId, data):
     try:
         for curCondition in self._conditionMgr.conditions:
             if (curCondition.RequiresService(serviceId)):
                 curCondition.EventHandler_ServiceDataUpdated(
                     serviceId, data)
     except:
         LogException()