예제 #1
0
def getHistoricReference(log, itemName, valueTime, outdatetTime, messureTime,
                         intervalTime):
    endTime = getItemLastUpdate(itemName)
    endTimestampInMillis = endTime.getMillis()

    nowInMillis = getNow().getMillis()

    if endTimestampInMillis < nowInMillis - (outdatetTime * 1000):
        log.info(u"No consumption. Last value is too old.")
        return 0

    minMessuredTimestampInMillis = nowInMillis - (messureTime * 1000)

    endValue = getItemState(itemName).doubleValue()

    startTimestampInMillis = endTimestampInMillis
    startValue = 0

    currentTime = DateTime(startTimestampInMillis - 1)

    itemCount = 0

    while True:
        itemCount = itemCount + 1

        historicEntry = getHistoricItemEntry(itemName, currentTime)

        startValue = historicEntry.getState().doubleValue()

        _millis = historicEntry.getTimestamp().getTime()

        # current item is older then the allowed timeRange
        if _millis < minMessuredTimestampInMillis:
            log.info(u"Consumption time limit exceeded")
            startTimestampInMillis = startTimestampInMillis - (intervalTime *
                                                               1000)
            if _millis > startTimestampInMillis:
                startTimestampInMillis = _millis
            break
        # 2 items are enough to calculate with
        elif itemCount >= 2:
            log.info(u"Consumption max item count exceeded")
            startTimestampInMillis = _millis
            break
        else:
            startTimestampInMillis = _millis
            currentTime = DateTime(startTimestampInMillis - 1)

    durationInSeconds = round(
        float(endTimestampInMillis - startTimestampInMillis) / 1000.0)
    value = ((endValue - startValue) / durationInSeconds) * valueTime
    if value < 0:
        value = 0

    startTime = DateTime(startTimestampInMillis)
    log.info(u"Consumption {} messured from {} ({}) to {} ({})".format(
        value, startValue, dateTimeFormatter.print(startTime), endValue,
        dateTimeFormatter.print(endTime)))

    return value
예제 #2
0
파일: utils.py 프로젝트: jpg0/oh-config
def getLastUpdate(item_or_item_name):
    """
    Returns the Item's last update datetime as an 'org.joda.time.DateTime <http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html>`_.

    Args:
        item_or_item_name (Item or str): name of the Item

    Returns:
        DateTime: DateTime representing the time of the Item's last update
    """
    try:
        item = itemRegistry.getItem(item_or_item_name) if isinstance(
            item_or_item_name, basestring) else item_or_item_name
        lastUpdate = PersistenceExtensions.lastUpdate(item)
        if lastUpdate is None:
            log.warning(
                "No existing lastUpdate data for item: [{}], so returning 1970-01-01T00:00:00Z"
                .format(item.name))
            return DateTime(0)
        return lastUpdate.toDateTime()
    except:
        # There is an issue using the StartupTrigger and saving scripts over SMB, where changes are detected before the file
        # is completely written. The first read breaks because of a partial file write and the second read succeeds.
        log.warning(
            "Exception when getting lastUpdate data for item: [{}], so returning 1970-01-01T00:00:00Z"
            .format(item.name))
        return DateTime(0)
예제 #3
0
    def getLastReductionTime( self, currentOperatingModeUpdate ):
        lastOperatingMode = getHistoricItemEntry("Heating_Operating_Mode",currentOperatingModeUpdate.minusSeconds(1))
        #self.log.info(u"A {}".format(lastOperatingMode.getState().intValue()))
        
        # last mode was "Heizen mit WW"
        if lastOperatingMode.getState().intValue() == 2:
            lastOperatingModeUpdate = DateTime( lastOperatingMode.getTimestamp().getTime() )
            lastHeatingTime = currentOperatingModeUpdate.getMillis() - lastOperatingModeUpdate.getMillis()
            #self.log.info(u"B {}".format(lastHeatingTime))

            # last mode was running less then MIN_HEATING_TIME
            if lastHeatingTime < Heating.MIN_HEATING_TIME * 60 * 1000:
                # mode before was "Reduziert"
                previousOperatingMode = getHistoricItemEntry("Heating_Operating_Mode",lastOperatingModeUpdate.minusSeconds(1))
                #self.log.info(u"C {}".format(previousOperatingMode.getState().intValue()))

                if previousOperatingMode.getState().intValue() == 3:
                    # letzt calculate last "reduziert" runtime and increase it by 2
                    previousOperatingModeUpdate = DateTime( previousOperatingMode.getTimestamp().getTime() ) 
                    lastReducedRuntime = lastOperatingModeUpdate.getMillis() - previousOperatingModeUpdate.getMillis()
                    
                    return lastReducedRuntime
        return 0  
                                                
             
예제 #4
0
def exampleSolarTimeOfDay(event):
    time.sleep(2)  # wait for Items to update
    dawn_start = DateTime(items['V_CivilDawn'].toString())
    day_start = DateTime(items['V_Sunrise'].toString())
    dusk_start = DateTime(items['V_CivilDuskStart'].toString())
    night_start = DateTime(items['V_CivilDuskEnd'].toString())

    curr = None
    now = DateTime.now()
    exampleSolarTimeOfDay.log.debug("dawn_start  [{}]".format(dawn_start))
    exampleSolarTimeOfDay.log.debug("day_start   [{}]".format(day_start))
    exampleSolarTimeOfDay.log.debug("dusk_start  [{}]".format(dusk_start))
    exampleSolarTimeOfDay.log.debug("night_start [{}]".format(night_start))
    exampleSolarTimeOfDay.log.debug("now         [{}]".format(now))

    if now.isAfter(dawn_start) and now.isBefore(day_start):
        curr = SOLARTIME['DAWN']
    elif now.isAfter(day_start) and now.isBefore(dusk_start):
        curr = SOLARTIME['DAY']
    elif now.isAfter(dusk_start) and now.isBefore(night_start):
        curr = SOLARTIME['DUSK']
    else:
        curr = SOLARTIME['NIGHT']

    if postUpdateCheckFirst('V_SolarTime', curr):
        exampleSolarTimeOfDay.log.info("Solar time is now [{}]".format(
            kw(SOLARTIME, curr)))
예제 #5
0
 def __init__(self, input, output):
     self.regexTransform = re.compile("(?P<token>\$[A-Za-z]+\.[a-zA-Z0-9_]+)")
     self.input = input
     self.output = output
     self.openfiles = {}
     self.outplugin = {}
     self.runtime = {}
     self.started = None
     self.completed = None
     self.result = None
     self.thread_used = None
     self.exception = None
     self.datasource = None
     self.running    = False
     try:
         self.interval = int(input["interval"])
     except:
         self.interval = 60
     self.runtime["jodaStart"] = DateTime()
     self.runtime["jodaEnd"] = DateTime()
     self.cycle = { 
         "start": self.runtime["jodaStart"].getMillis(),
         "laststart": self.runtime["jodaStart"].getMillis(),
         "laststartdt": str(self.runtime["jodaEnd"]),
         "end": self.runtime["jodaStart"].getMillis(), 
         "elapsed": 0,
         "startdt": str(self.runtime["jodaEnd"]),
         "enddt": str(self.runtime["jodaEnd"]), 
         "numCycles": 0,
         "badCycles": 0,
         "goodCycles": 0,
     }
예제 #6
0
def create_timers(start_times):
    """Creates Timers to transition the time of day based on the passed in list
    of DateTime Item names. If an Item is dated with yesterday, the Item is
    updated to today. The ETOD_ITEM is commanded to the current time of day if
    it's not already the correct state.
    Arguments:
        - start_times: list of names for DateTime Items containing the start
        times for each time period
    """

    now = DateTime().now()
    most_recent_time = now.minusDays(1)
    most_recent_state = items[ETOD_ITEM]

    for time in start_times:

        item_time = DateTime(str(items[time]))
        trigger_time = to_today(items[time])

        # Update the Item with today's date if it was for yesterday.
        if item_time.isBefore(trigger_time):
            log.debug("Item {} is yesterday, updating to today".format(time))
            events.postUpdate(time, str(trigger_time))

        # Get the etod state from the metadata.
        state = get_value(time, NAMESPACE)

        # If it's in the past but after most_recent, update most_recent.
        if trigger_time.isBefore(now) and trigger_time.isAfter(
                most_recent_time):
            log.debug(
                "NOW:    {} start time {} is in the past but after {}".format(
                    state, trigger_time, most_recent_time))
            most_recent_time = trigger_time
            most_recent_state = get_value(time, NAMESPACE)

        # If it's in the future, schedule a Timer.
        elif trigger_time.isAfter(now):
            log.debug("FUTURE: {} Scheduleing Timer for {}".format(
                state, trigger_time))
            timers.check(state,
                         trigger_time,
                         function=lambda st=state: etod_transition(st))

        # If it's in the past but not after most_recent_time we can ignore it.
        else:
            log.debug(
                "PAST:   {} start time of {} is before now {} and before {}".
                format(state, trigger_time, now, most_recent_time))

    log.info("Created {} timers.".format(len(timers.timers)))
    log.info("The current time of day is {}".format(most_recent_state))
    send_command_if_different(ETOD_ITEM, most_recent_state)
예제 #7
0
def jdatetime(t):
    """
    Convert python date to joda DateTime.
    
    :param t: Python date
    
    :returns: Joda DateTime
    """
    if isinstance(t, (list, tuple)):
        r = []
        for tt in t:
            r.append(DateTime(tt.year, tt.month, tt.day, tt.hour, tt.minute, tt.second, tt.microsecond / 1000))
        return r
    else:
        return DateTime(t.year, t.month, t.day, t.hour, t.minute, t.second, t.microsecond / 1000)
예제 #8
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
 def convert_date(self, d):
     if d is not None:
         if isinstance(d, basestring):
             return Timestamp(ReleaseSqlPublisher.ISO_DATE_TIME_FORMAT.parseDateTime(d).getMillis())
         else:
             return Timestamp(DateTime(d).getMillis())
     return None
예제 #10
0
def getItemValue(itemName, defVal):
    '''
    Returns the items value if the item is initialized otherwise return the default value.
    itemRegistry.getItem will return an object also for uninitialized items but it has less methods.
    '''
    item = itemRegistry.getItem(itemName)
    if type(defVal) is int:
        return item.state.intValue() if item.state not in [NULL, UNDEF
                                                           ] else defVal
    elif type(defVal) is float:
        return item.state.floatValue() if item.state not in [NULL, UNDEF
                                                             ] else defVal
    elif defVal in [ON, OFF, OPEN, CLOSED]:
        return item.state if item.state not in [NULL, UNDEF] else defVal
    elif type(defVal) is str:
        return item.state.toFullString() if item.state not in [NULL, UNDEF
                                                               ] else defVal
    elif type(defVal) is DateTime:
        # We return a to a org.joda.time.DateTime from a org.eclipse.smarthome.core.library.types.DateTimeType
        return DateTime(
            item.state.calendar.timeInMillis) if item.state not in [
                NULL, UNDEF
            ] else defVal
    else:
        log.error('The type of the passed default value is not handled')
        return None
예제 #11
0
def to_joda_datetime(value):
    """
    Converts any of the supported date types to ``org.joda.time.DateTime``. If
    ``value`` does not have timezone information, the system default will be
    used.

    Examples:
        .. code-block::

            joda_time = to_joda_datetime(items["date_item"])

    Args:
        value: the value to convert

    Returns:
        org.joda.time.DateTime: the converted value

    Raises:
        TypeError: if the type of ``value`` is not suported by this package
    """
    if isinstance(value, DateTime):
        return value

    value_zoneddatetime = to_java_zoneddatetime(value)
    return DateTime(
        value_zoneddatetime.toInstant().toEpochMilli(),
        DateTimeZone.forID(value_zoneddatetime.getZone().getId())
    )
예제 #12
0
    def getBurnerStarts( self, now ):
        # max 5 min.
        minTimestamp = getHistoricItemEntry("Heating_Operating_Mode",now).getTimestamp().getTime()
        _minTimestamp = now.minusMinutes(5).getMillis()
        if minTimestamp < _minTimestamp:
            minTimestamp = _minTimestamp

        currentTime = now
        lastItemEntry = None
        burnerStarts = 0
        
        # check for new burner starts during this time periode
        # "Heating_Burner_Starts" is not useable because of wather heating
        while currentTime.getMillis() > minTimestamp:
            currentItemEntry = getHistoricItemEntry("Heating_Power", currentTime)
            if lastItemEntry is not None:
                currentHeating = ( currentItemEntry.getState().doubleValue() != 0.0 )
                lastHeating = ( lastItemEntry.getState().doubleValue() != 0.0 )
                
                if currentHeating != lastHeating:
                    burnerStarts = burnerStarts + 1
            
            currentTime = DateTime( currentItemEntry.getTimestamp().getTime() - 1 )
            lastItemEntry = currentItemEntry
            
        return burnerStarts
예제 #13
0
def getItemValue(itemName, defVal):
    '''
    Returns the Item's value if the Item exists and is initialized, otherwise returns the default value.
    itemRegistry.getItem will return an object also for uninitialized items but it has less methods.
    itemRegistry.getItem will throw an exception if the Item is not in the registry.
    '''
    item = scope.itemRegistry.getItem(itemName)
    if type(defVal) is int:
        return item.state.intValue() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif type(defVal) is float:
        return item.state.floatValue() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif defVal in [scope.ON, scope.OFF, scope.OPEN, scope.CLOSED]:
        return item.state if item.state not in [scope.NULL, scope.UNDEF
                                                ] else defVal
    elif type(defVal) is str:
        return item.state.toFullString() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif type(defVal) is DateTime:
        # We return a org.joda.time.DateTime from a org.eclipse.smarthome.core.library.types.DateTimeType
        return DateTime(
            item.state.calendar.timeInMillis) if item.state not in [
                scope.NULL, scope.UNDEF
            ] else defVal
    else:
        log.warn("The type of the passed default value is not handled")
        return None
예제 #14
0
def getItemValue(item_or_item_name, default_value):
    """
    Returns the Item's value if the Item exists and is initialized, otherwise
    returns the default value. ``itemRegistry.getItem`` will return an object
    for uninitialized items, but it has less methods. ``itemRegistry.getItem``
    will throw an ItemNotFoundException if the Item is not in the registry.

    Args:
        item_or_item_name (Item or str): name of the Item
        default_value (int, float, ON, OFF, OPEN, CLOSED, str, DateTime): the default
            value

    Returns:
        int, float, ON, OFF, OPEN, CLOSED, str, DateTime, or None: the state if
            the Item converted to the type of default value, or the default
            value if the Item's state is NULL or UNDEF
    """
    LOG.warn("The 'core.utils.getItemValue' function is pending deprecation.")
    item = itemRegistry.getItem(item_or_item_name) if isinstance(item_or_item_name, basestring) else item_or_item_name
    if isinstance(default_value, int):
        return item.state.intValue() if item.state not in [NULL, UNDEF] else default_value
    elif isinstance(default_value, float):
        return item.state.floatValue() if item.state not in [NULL, UNDEF] else default_value
    elif default_value in [ON, OFF, OPEN, CLOSED]:
        return item.state if item.state not in [NULL, UNDEF] else default_value
    elif isinstance(default_value, str):
        return item.state.toFullString() if item.state not in [NULL, UNDEF] else default_value
    elif isinstance(default_value, DateTime):
        # We return a org.joda.time.DateTime from a org.eclipse.smarthome.core.library.types.DateTimeType
        return DateTime(item.state.calendar.timeInMillis) if item.state not in [NULL, UNDEF] else default_value
    else:
        LOG.warn("The type of the passed default value is not handled")
        return None
예제 #15
0
 def finishCycle(self):
     self.runtime["jodaEnd"] = DateTime()
     self.cycle["end"] = self.runtime["jodaEnd"].getMillis()
     self.cycle["enddt"] = str(self.runtime["jodaEnd"])
     self.cycle["laststart"] = self.cycle["start"]
     self.cycle["laststartdt"] = self.cycle["startdt"]
     self.cycle["elapsed"] = self.runtime["jodaEnd"].getMillis() - self.cycle["start"]
     logger.info("Finished cycle at %s", self.cycle["enddt"])
예제 #16
0
def getLastUpdate(pe, item):
    '''
    Returns the items last update datetime as a 'org.joda.time.DateTime',
    http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
    '''
    try:
        if pe.lastUpdate(item) is None:
            log.warning('No existing lastUpdate data for item: ' +
                        unicode(item.name) +
                        ', returning 1970-01-01T00:00:00Z')
            return DateTime(0)
        return pe.lastUpdate(item).toDateTime()
    except:
        # I have an issue with OH file changes being detected (StartupTrigger only) before the file
        # is completely written. The first read breaks because of a partial file write and the second read succeeds.
        log.warning('Exception when getting lastUpdate data for item: ' +
                    unicode(item.name) + ', returning 1970-01-01T00:00:00Z')
        return DateTime(0)
예제 #17
0
def to_joda_datetime(value):
    '''Returns org.joda.time.DateTime type (with system timezone if none specified). 
    Accepts any date type used by this module'''
    if isinstance(value, DateTime):
        return value

    value_zoneddatetime = to_java_zoneddatetime(value)
    return DateTime(value_zoneddatetime.toInstant(),
                    DateTimeZone.forID(value_zoneddatetime.getZone().getId()))
예제 #18
0
 def tick(self):
     stream = subprocess.Popen(self.cmd,
                               shell=True,
                               bufsize=0,
                               stdout=subprocess.PIPE)
     dt = str(DateTime())
     ps = 0  #parser state
     fields = []
     state = 0
     out = {}
     nowStr = self.getCycleProperty("startdt")
     for line in stream.stdout:
         line = line.rstrip()
         out["@timestamp"] = nowStr
         out["host"] = platform.node()
         matchClass = re.search(self.regexClass, line)
         if (matchClass):
             logger.debug("Matched stats group")
             out["class"] = matchClass.group(1).lstrip()
             nowStr = str(DateTime())
             state = 10
             logger.debug(out)
         elif (state == 10):
             out["value"] = None
             matchColon = re.search(self.regexValueColon, line)
             if (matchColon):
                 out["metric"] = matchColon.group(1).lstrip()
                 out["value"] = float(matchColon.group(2))
             else:
                 matchValueAtStart = re.search(self.regexValueAtStart, line)
                 if (matchValueAtStart):
                     out["value"] = float(matchValueAtStart.group(1))
                     out["metric"] = matchValueAtStart.group(2).lstrip()
                 else:
                     matchValueAnywhere = re.search(self.regexMatchDigits,
                                                    line)
                     if (matchValueAnywhere):
                         out["value"] = float(matchValueAnywhere.group(1))
                         out["metric"] = re.sub(self.regexMatchDigits, "",
                                                line).lstrip()
             if (out["value"] != None):
                 self.processData(out)
예제 #19
0
    def isActive(self):
        try:
            getLogger().info(
                ("Calling 'isActive()' for '{}'").format(self.getName()))
            #diff = Minutes.minutesBetween(self._sequenceBaseTimestamp, DateTime())
            #curOffset = diff.getMinutes()
            activate = False

            diff = Seconds.secondsBetween(self._sequenceBaseTimestamp,
                                          DateTime())
            curOffset = diff.getSeconds()
            if (curOffset > self._sequenceDuration):
                self._sequenceBaseTimestamp = DateTime()
                curOffset = 0

            for curSwitchKey, actSequence in self._dictSequences.iteritems():
                #actSequence = self._dictSequences[curSwitchKey]
                activate = self._evaluateViritualSwitch(curOffset, actSequence)

                curVirtualSwitch = self._objRule.getVirtualSwitchByName(
                    curSwitchKey)
                getLogger().info((
                    "About to evaluate state of '{}':  curState='{}' newState='{}'"
                ).format(curVirtualSwitch.getName(),
                         curVirtualSwitch.isActive(), activate))

                #If state is wrong -> update
                if (((curVirtualSwitch.isActive() == True) and
                     (activate == False))
                        or ((curVirtualSwitch.isActive() == False) and
                            (activate == True))):

                    getLogger().info(
                        ("Change state of '{}' from '{}' to '{}'").format(
                            curVirtualSwitch.getName(),
                            curVirtualSwitch.isActive(), activate))
                    curVirtualSwitch.updateState(activate)
        except:
            LogException()

        return False
    def execute(self, module, input):
        now = getNow()
        
        # Dawn_Time
        # Sunrise_Time
        # Sunset_Time
        # Dusk_Time
        
        cloudCover = getItemState("Cloud_Cover_Current").intValue()
                
        if getItemState("State_Rollershutter") == ON:
            _upTime = getItemState("Sunrise_Time").calendar.getTimeInMillis()
            _upTime = int(_upTime + ( cloudCover * 30.0 / 9.0 ) * 60 * 1000)

            _lastDownTime = getItemState("State_Rollershutter_Down").calendar.getTimeInMillis()

            if now.getMillis() > _upTime and _upTime > _lastDownTime:
                postUpdate("State_Rollershutter", OFF)

            postUpdateIfChanged("State_Rollershutter_Up", DateTime(_upTime).toString() )
        else:
            _downTime = getItemState("Dusk_Time").calendar.getTimeInMillis()
            _downTime = int(_downTime - ( cloudCover * 30.0 / 9.0 ) * 60 * 1000)
            
            if now.getMillis() > _downTime:
                postUpdate("State_Rollershutter", ON)

            postUpdateIfChanged("State_Rollershutter_Down", DateTime(_downTime).toString() )




        if itemStateOlderThen("Sunset_Time", now) or itemStateNewerThen("Sunrise_Time", now):
            postUpdateIfChanged("State_Outdoorlights", ON)
        else:
            postUpdateIfChanged("State_Outdoorlights", OFF)
            
        if itemStateOlderThen("Dusk_Time", now) or itemStateNewerThen("Dawn_Time", now):
            postUpdateIfChanged("State_Solar", OFF)
        else:
            postUpdateIfChanged("State_Solar", ON)
예제 #21
0
 def getLastUpdate(self):
     '''
     Returns the sensors last update time (if available).
     type is 'org.joda.time.DateTime', http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
     '''
     try:
         lastUpdate = PersistenceExtensions.lastUpdate(
             itemRegistry.getItem(self.name)).toDateTime()
     except:
         lastUpdate = DateTime(0)
         self.log.info('Could not retrieve persistence data for sensor: ' +
                       self.name.decode('utf8'))
     return lastUpdate
예제 #22
0
    def isActive(self):

        try:
            curDateTime = DateTime()

            if (self._arrSunInfo is not None):
                sunInfoYesterday = self._arrSunInfo[0]
                sunInfoToday = self._arrSunInfo[1]
                sunInfoTomorrow = self._arrSunInfo[2]

                #After Sunset yesterday, Before sunrise Today -> Night
                if (curDateTime.isAfter(sunInfoYesterday.getSunsetStart()) and
                        curDateTime.isBefore(sunInfoToday.getSunriseEnd())):
                    getLogger().debug(
                        ("NIGHT -> '{}' is between '{}' - '{}'").format(
                            curDateTime, sunInfoYesterday.getSunsetStart(),
                            sunInfoToday.getSunriseEnd()))
                    return True

                #After Sunrise today, Before sunset Today -> Day
                if (curDateTime.isAfter(sunInfoToday.getSunriseEnd()) and
                        curDateTime.isBefore(sunInfoToday.getSunsetStart())):
                    getLogger().debug(
                        ("DAY -> '{}' is between '{}' - '{}'").format(
                            curDateTime, sunInfoToday.getSunriseEnd(),
                            sunInfoToday.getSunsetStart()))
                    return False

                #After Sunset today, Before Sunrise Tomorrow -> Night
                elif (curDateTime.isAfter(sunInfoToday.getSunsetStart()) and
                      curDateTime.isBefore(sunInfoTomorrow.getSunriseEnd())):
                    getLogger().debug(
                        ("NIGHT -> '{}' is between '{}' - '{}'").format(
                            curDateTime, sunInfoToday.getSunsetStart(),
                            sunInfoTomorrow.getSunriseEnd()))
                    return True

                getLogger().warn(
                    ("'{}' didn't evalute night/day '{}', '{}', '{}', '{}'"
                     ).format(curDateTime, sunInfoYesterday.getSunsetStart(),
                              sunInfoToday.getSunriseEnd(),
                              sunInfoToday.getSunsetStart(),
                              sunInfoTomorrow.getSunriseEnd()))
            else:
                getLogger().warn("No SunInfo data found - Evaluating 'False'")
            return False
        except:
            LogException()

        return False
예제 #23
0
    def run(self, func, when):
        """If it has been long enough since the last time that run was called,
        execute the passed in func. Otherwise ignore the call.
        Arguments:
            - func: The lambda or function to call if allowed.
            - when: When the rate limit will expire. Can be a DateTime type
            object, a number which is treated as seconds, or a duration string
            (e.g. 5m 2.5s), or an ISO 8601 formatted date string. See time_utils
            for details
        """

        now = DateTime().now()
        if now.isAfter(self.until):
            self.until = to_datetime(when)
            func()
예제 #24
0
def to_joda_datetime(value):
    if isinstance(value, DateTime):
        return value

    calendar = to_java_calendar(value)

    return DateTime(
        calendar.get(Calendar.YEAR),
        calendar.get(Calendar.MONTH) + 1,
        calendar.get(Calendar.DAY_OF_MONTH),
        calendar.get(Calendar.HOUR_OF_DAY),
        calendar.get(Calendar.MINUTE),
        calendar.get(Calendar.SECOND),
        calendar.get(Calendar.MILLISECOND),
    )
예제 #25
0
 def tick(self):
     stream = subprocess.Popen(self.cmd,
                               shell=True,
                               bufsize=0,
                               stdout=subprocess.PIPE)
     dt = str(DateTime())
     ps = 0  #parser state
     fields = []
     state = 0
     out = {}
     nowStr = self.getCycleProperty("startdt")
     for line in stream.stdout:
         line = line.rstrip()
         matchActiveHeader = re.search(self.regexActiveHeader, line)
         if (matchActiveHeader):
             out = {}
             if (matchActiveHeader.group(1) == 'Internet'):
                 state = 5
             else:
                 state = 0
         elif (state == 5):
             matchHeader = re.search(self.regexHeader, line)
             if (matchHeader):
                 state = 10
                 out["@timestamp"] = nowStr
                 out["host"] = platform.node()
                 out["class"] = "tcpconnections"
         elif (state == 10):
             idx = 0
             values = re.split(self.regexBoundary, line)
             for value in values:
                 field = self.fields[idx]
                 if ((field == 'receive-q') or (field == 'send-q')):
                     values[idx] = float(value)
                 elif (field == 'local'):
                     pair = re.search(self.regexIpSplit, value)
                     out['localip'] = pair.group(1)
                     out['localport'] = float(pair.group(2))
                 elif (field == 'foreign'):
                     pair = re.search(self.regexIpSplit, value)
                     out['foreignip'] = pair.group(1)
                     out['foreignport'] = float(pair.group(2))
                 out[field] = values[idx]
                 idx += 1
             self.processData(out)
예제 #26
0
	def to_joda_datetime(cls, value):
		try:
			if isinstance(value, DateTime):
				return value
			
			calendar = AstroSunInfo.to_java_calendar(value)
		
			return DateTime(
				calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH) + 1,
				calendar.get(Calendar.DAY_OF_MONTH),
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE),
				calendar.get(Calendar.SECOND),
				calendar.get(Calendar.MILLISECOND),
				)
		except:
			LogException()
예제 #27
0
def ephem_tod(event):
    """Rule to recalculate the times of day for today. It triggers at system
    start, two minutes after midnight (to give Astro a chance to update the
    times for today), when ETOD_TRIGGER_ITEM (default is CalculateETOD) receives
    an ON command, or when any of the Items with etod metadata changes.
    """
    log.info("Recalculating time of day")

    # Get the start times.
    start_times = get_times()

    if not start_times:
        log.error("No start times found! Cannot run the rule!")
        return

    # If any are NULL, kick off the init rule.
    null_items = [i for i in start_times if isinstance(items[i], UnDefType)]
    if null_items and "InitItems" in items:
        log.warn("The following Items are are NULL/UNDEF, kicking off "
                 "initialization using item_init: {}".format(null_items))
        events.sendCommand("InitItems", "ON")
        from time import sleep
        sleep(5)

    # Check to see if we still have NULL/UNDEF Items.
    null_items = [i for i in start_times if isinstance(items[i], UnDefType)]
    if null_items:
        log.error("The following Items are still NULL/UNDEF, "
                  "cannot create Time of Day timers: {}".format(null_items))
        return

    # Cancel existing Items and then generate all the timers for today.
    timers.cancel_all()
    create_timers(start_times)

    # Create a timer to run this rule again a little after midnight. Work around
    # to deal with the fact that cron triggers do not appear to be workind.
    now = DateTime().now()
    reload_time = now.withTime(0, 5, 0, 0)
    if reload_time.isBefore(now):
        reload_time = reload_time.plusDays(1)
        log.info("Creating reload timer for {}".format(reload_time))
    timers.check("etod_reload", reload_time, function=lambda: ephem_tod(None))
예제 #28
0
def to_joda_datetime(value):
    """Converts any known DateTime type to a ``org.joda.time.DateTime`` type.

    Args:
        value: any known DateTime value.
    
    Returns:
        | An ``org.joda.time.DateTime`` representing ``value``.
        | If ``value`` does not have timezone information, the system default
          will be used.
    
    Raises:
        TypeError: type of ``value`` is not recognized by this package.
    """
    if isinstance(value, DateTime):
        return value

    value_zoneddatetime = to_java_zoneddatetime(value)
    return DateTime(value_zoneddatetime.toInstant(),
                    DateTimeZone.forID(value_zoneddatetime.getZone().getId()))
예제 #29
0
    def __init__(self, objRule, duration, arrSequences):
        try:

            BaseCriteria.__init__(self, "")
            #TODO:: Might want to improve this a bit. The sequence will then be controlled on when oh is started
            self._sequenceBaseTimestamp = DateTime()
            self._sequenceDuration = duration
            self._dictSequences = {}
            self._objRule = objRule

            for curSequence in arrSequences:
                if (curSequence.getName() not in self._dictSequences):
                    self._dictSequences[curSequence.getName()] = [curSequence]
                else:
                    self._dictSequences[curSequence.getName()].append(
                        curSequence)

            #TODO:: Validate if all sequences is a SequenceItem
        except:
            LogException()
예제 #30
0
def getItemValue(itemName, defVal):
    """
    Returns the Item's value if the Item exists and is initialized, otherwise
    returns the default value. ``itemRegistry.getItem`` will return an object
    for uninitialized items, but it has less methods. ``itemRegistry.getItem``
    will throw an ItemNotFoundException if the Item is not in the registry.

    Args:
        itemName: name of the Item
        defVal: the default value

    Returns:
        int, float, ON, OFF, OPEN, CLOSED, str, or DateTime: the state if the
            Item converted to the type of default value, or the default value
            if the Item's state is NULL or UNDEF
    """
    item = scope.itemRegistry.getItem(itemName)
    if type(defVal) is int:
        return item.state.intValue() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif type(defVal) is float:
        return item.state.floatValue() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif defVal in [scope.ON, scope.OFF, scope.OPEN, scope.CLOSED]:
        return item.state if item.state not in [scope.NULL, scope.UNDEF
                                                ] else defVal
    elif type(defVal) is str:
        return item.state.toFullString() if item.state not in [
            scope.NULL, scope.UNDEF
        ] else defVal
    elif type(defVal) is DateTime:
        # We return a org.joda.time.DateTime from a org.eclipse.smarthome.core.library.types.DateTimeType
        return DateTime(
            item.state.calendar.timeInMillis) if item.state not in [
                scope.NULL, scope.UNDEF
            ] else defVal
    else:
        log.warn("The type of the passed default value is not handled")
        return None