Esempio n. 1
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  
                                                
             
Esempio n. 2
0
 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
Esempio n. 3
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)
Esempio n. 4
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()))
def battery_charging_monitor(event):
    battery_charging_monitor.log.debug("Battery charging monitor: {}: start".format(event.itemState))
    if items["Outlet9"] == ON and event.itemState <= DecimalType(8) and event.oldItemState <= DecimalType(8):
        if MY_TIMERS.get("charger_timer") is None or MY_TIMERS["charger_timer"].hasTerminated():
            MY_TIMERS["charger_timer"] = ScriptExecution.createTimer(DateTime.now().plusMinutes(5), lambda: events.sendCommand("Outlet9","OFF"))
            battery_charging_monitor.log.info("Battery charging monitor: Started battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState, event.oldItemState))
    elif MY_TIMERS.get("charger_timer") is not None and not MY_TIMERS["charger_timer"].hasTerminated():
        MY_TIMERS.get("charger_timer").cancel()
        battery_charging_monitor.log.info("Battery charging monitor: Canceled battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState, event.oldItemState))
Esempio n. 6
0
    def start_timer(self, time_out_seconds):
        time_started = DateTime.now()

        def timeout_callback():
            log.warn(
                "Occupancy timer for area {} expired, timer was started at {}".
                format(self.name, time_started))
            self.set_area_vacant('Timer Expired')
            self.occupancy_timer = None
            self.occupancy_timeout = None

        self.cancel_timer()

        self.occupancy_timer = ScriptExecution.createTimer(
            DateTime.now().plusSeconds(time_out_seconds), timeout_callback)
        self.occupancy_timeout = DateTime.now().plusSeconds(time_out_seconds)
        log.warn("Occupancy Timer for area {} expires at {}".format(
            self.name, self.occupancy_timeout))
def nuix_worker_item_callback(worker_item):
    source_item = worker_item.getSourceItem()
    if source_item.getName() == 'test.txt':
        comm = SimpleCommunication(
            DateTime.now(),
            [SimpleAddress("David Skysits", "*****@*****.**")],
            [SimpleAddress("Stephen Artstew", "*****@*****.**")],
            [], [])
        worker_item.setItemCommunication(comm)
Esempio n. 8
0
def batteryChargingMonitor2(event):
    #log.debug("Battery charging monitor: {}: start".format(event.itemState))
    global chargerTimer2
    if items["Outlet9"] == OnOffType.ON and event.itemState <= DecimalType(8) and event.oldItemState <= DecimalType(8):
        if chargerTimer2 is None or chargerTimer2.hasTerminated():
            chargerTimer2 = creatTimer(DateTime.now().plusMinutes(5), lambda: events.sendCommand("Outlet9","OFF"))
            log.info("Battery charging monitor: Started battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState,event.oldItemState))
    elif chargerTimer2 is not None and not chargerTimer2.hasTerminated():
        chargerTimer2.cancel()
        log.info("Battery charging monitor: Cancelled battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState,event.oldItemState))
Esempio n. 9
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))
Esempio n. 10
0
def mainsEnergyMonitor(event):
    lastThreeWeeksUsage = float(
        str(
            PersistenceExtensions.sumSince(
                ir.getItem("HEM1_Total_Energy_Delta"),
                DateTime.now().minusDays(21))))  # blue yellow
    if lastThreeWeeksUsage > 200:  # green
        logDebug(
            "Demo8", "Send alert - {} => {}".format(event.itemName,
                                                    str(event.itemState)))
def update_mode(event):
    day_of_week = datetime.today().strftime('%A')
    last_mode_of_day = MODE_CONFIGURATION[day_of_week].items()[-1][0]
    new_mode = last_mode_of_day
    for i, (mode,
            value) in enumerate(MODE_CONFIGURATION[day_of_week].iteritems()):
        if mode != last_mode_of_day:
            if event is None and MODE_CONFIGURATION[day_of_week][mode].get(
                    "hour"
            ) is not None and Interval(
                    DateTime.now().withTime(value["hour"], value["minute"],
                                            value["second"], 0),
                    DateTime.now().withTime(
                        MODE_CONFIGURATION[day_of_week].items()[i + 1][1].get(
                            "hour", value["hour"]),
                        MODE_CONFIGURATION[day_of_week].items()[i + 1][1].get(
                            "minute", value["minute"] + 1),
                        MODE_CONFIGURATION[day_of_week].items()[i + 1][1].get(
                            "second", value["second"]), 0)).contains(
                                DateTime.now()):
                new_mode = mode
                break
            elif hasattr(
                    event, "channel"
            ) and MODE_CONFIGURATION[day_of_week][mode].get(
                    "channel") is not None and event.channel == ChannelUID(
                        MODE_CONFIGURATION[day_of_week][mode].get(
                            "channel")) and event.event == MODE_CONFIGURATION[
                                day_of_week][mode].get("event"):
                new_mode = mode
                break

    if items["Mode"] != StringType(new_mode) and (
            str(items["Mode"]) in MODE_CONFIGURATION[day_of_week].keys()
            or isinstance(items["Mode"], UnDefType)):
        update_mode.log.debug(u"Mode changed from '{}' to '{}'".format(
            items["Mode"], new_mode))
        events.sendCommand("Mode", new_mode)
    else:
        update_mode.log.debug(
            u"Job ran but current Mode '{}' did not need to be changed: '{}'".
            format(items["Mode"], new_mode))
Esempio n. 12
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)
Esempio n. 13
0
def rule_acidinject(event):
    global timer_acid
    if timer_acid is None:
        rule_acidinject.log.info("Injecting 250ml of acid")
        sendCommand("pool_acidpump", ON)
        timer_acid = createTimer(DateTime.now().plusSeconds(45),
                                 lambda: timer_fillflush(rule_acidinject.log))
    else:
        rule_acidinject.log.warn(
            "Failed to start acid flush, an acid flush sequence is already running"
        )
Esempio n. 14
0
 def isSensorAlive(sName):
     if getLastUpdate(ir.getItem(sName)).isAfter(
             DateTime.now().minusMinutes(sensor_dead_after_mins)):
         return True
     else:
         weatherStationUploader.log.warn(
             "Sensor device {} has not reported since: {}".format(
                 sName,
                 format_date(getLastUpdate(ir.getItem(sName)),
                             customDateTimeFormats['dateTime'])))
         return False
Esempio n. 15
0
def calcNextSunTimes():
    calcNextSunTimes.log = logging.getLogger(
        "{}.calcNextSunTimes".format(LOG_PREFIX))
    if str(items["Astro_Day_Phase"]) in ["DAYLIGHT", "NOON"]:
        calcNextSunTimes.log.info(
            "Daylight - next sunrise is tomorrow, next sunset is today")
        events.postUpdate("Astro_Sun_RiseNext",
                          str(ir.getItem("Astro_Sun_RiseTomorrow").state))
        events.postUpdate("Astro_Sun_SetNext",
                          str(ir.getItem("Astro_Sun_SetTime").state))
    elif str(ir.getItem("Astro_Day_Phase").state) == "SUN_RISE":
        calcNextSunTimes.log.info("Sunrise - next sunrise and sunset is today")
        events.postUpdate("Astro_Sun_RiseNext",
                          str(ir.getItem("Astro_Sun_RiseTime").state))
        events.postUpdate("Astro_Sun_SetNext",
                          str(ir.getItem("Astro_Sun_SetTime").state))
    elif str(ir.getItem("Astro_Day_Phase").state) == "SUN_SET":
        calcNextSunTimes.log.info(
            "Sunset - next sunrise is tomorrow and sunset is today")
        events.postUpdate("Astro_Sun_RiseNext",
                          str(ir.getItem("Astro_Sun_RiseTomorrow").state))
        events.postUpdate("Astro_Sun_SetNext",
                          str(ir.getItem("Astro_Sun_SetTime").state))
    elif str(ir.getItem("Astro_Day_Phase").state) in [
            "ASTRO_DAWN", "NAUTIC_DAWN", "CIVIL_DAWN"
    ]:
        calcNextSunTimes.log.info("Dawn - next sunrise and sunset is today")
        events.postUpdate("Astro_Sun_RiseNext",
                          str(ir.getItem("Astro_Sun_RiseTime").state))
        events.postUpdate("Astro_Sun_SetNext",
                          str(ir.getItem("Astro_Sun_SetTime").state))
    elif str(ir.getItem("Astro_Day_Phase").state) in [
            "ASTRO_DUSK", "NAUTIC_DUSK", "CIVIL_DUSK"
    ]:
        calcNextSunTimes.log.info("Dusk - next sunrise and sunset is tomorrow")
        events.postUpdate("Astro_Sun_RiseNext",
                          str(ir.getItem("Astro_Sun_RiseTomorrow").state))
        events.postUpdate("Astro_Sun_SetNext",
                          str(ir.getItem("Astro_Sun_SetTomorrow").state))
    else:
        if DateTime.now().getHourOfDay() > 12:
            calcNextSunTimes.log.info(
                "Before midnight - next sunrise and sunset is tomorrow")
            events.postUpdate("Astro_Sun_RiseNext",
                              str(ir.getItem("Astro_Sun_RiseTomorrow").state))
            events.postUpdate("Astro_Sun_SetNext",
                              str(ir.getItem("Astro_Sun_SetTomorrow").state))
        else:
            calcNextSunTimes.log.info(
                "After midnight - next sunrise and sunset is today")
            events.postUpdate("Astro_Sun_RiseNext",
                              str(ir.getItem("Astro_Sun_RiseTime").state))
            events.postUpdate("Astro_Sun_SetNext",
                              str(ir.getItem("Astro_Sun_SetTime").state))
    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)
Esempio n. 17
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 isSensorAlive(sName):
     if getLastUpdate(PersistenceExtensions,
                      ir.getItem(sName)).isAfter(
                          DateTime.now().minusMinutes(
                              sensor_dead_after_mins)):
         return True
     else:
         self.log.warning('Sensor device ' + unicode(sName) +
                          ' has not reported since: ' + str(
                              getLastUpdate(PersistenceExtensions,
                                            ir.getItem(sName))))
         return False
Esempio n. 19
0
    def start_lock_timer(self, time_out_seconds):
        def timeout_callback():
            log.warn("Occupancy LOCK timer for area {} expired".format(
                self.name))
            self.unlock()

        self.lock_timer = ScriptExecution.createTimer(
            DateTime.now().plusSeconds(time_out_seconds), timeout_callback)
        self.lock_timer = Timer(time_out_seconds, timeout_callback)
        log.warn(
            "Occupancy LOCK timer for area {} started for {} seconds".format(
                self.name, time_out_seconds))
Esempio n. 20
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
Esempio n. 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
Esempio n. 22
0
def getLastUpdate(itemName):
    '''
    Returns the Item's last update datetime as a 'org.joda.time.DateTime',
    http://joda-time.sourceforge.net/apidocs/org/joda/time/DateTime.html
    '''
    try:
        item = scope.itemRegistry.getItem(itemName) if isinstance(
            itemName, basestring) else itemName
        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)
def update_mode(event):
    last_mode_of_day = mode_dict.items()[-1][0]
    new_mode = last_mode_of_day
    for i, (mode, value) in enumerate(mode_dict.iteritems()):
        if mode != last_mode_of_day:
            if event is None and mode_dict[mode].get(
                    "hour") is not None and Interval(
                        DateTime.now().withTime(value["hour"], value["minute"],
                                                value["second"], 0),
                        DateTime.now().withTime(
                            mode_dict.items()[i + 1][1].get(
                                "hour", value["hour"]),
                            mode_dict.items()[i + 1][1].get(
                                "minute", value["minute"] + 1),
                            mode_dict.items()[i + 1][1].get(
                                "second", value["second"]), 0)).contains(
                                    DateTime.now()):
                new_mode = mode
                break
            elif hasattr(event, "channel") and mode_dict[mode].get(
                    "channel") is not None and event.channel == ChannelUID(
                        mode_dict[mode].get("channel")
                    ) and event.event == mode_dict[mode].get("event"):
                new_mode = mode
                break

    if items["Mode"] != StringType(new_mode) and (
            str(items["Mode"]) in mode_dict.keys()
            or isinstance(items["Mode"], UnDefType)):
        update_mode.log.debug("Mode changed from [{}] to [{}]".format(
            items["Mode"], new_mode))
        events.sendCommand("Mode", new_mode)
    else:
        update_mode.log.debug(
            "Job ran but current Mode [{}] did not need to be changed: [{}]".
            format(items["Mode"], new_mode))
Esempio n. 24
0
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
    """
    LOG.warn("The 'core.utils.getLastUpdate' function is pending deprecation.")
    try:
        from core.actions import PersistenceExtensions
        item = itemRegistry.getItem(item_or_item_name) if isinstance(item_or_item_name, basestring) else item_or_item_name
        last_update = PersistenceExtensions.lastUpdate(item)
        if last_update is None:
            LOG.warning(u"No existing lastUpdate data for item: '{}', so returning 1970-01-01T00:00:00Z".format(item.name))
            return DateTime(0)
        return last_update.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(u"Exception when getting lastUpdate data for item: '{}', so returning 1970-01-01T00:00:00Z".format(item.name))
        return DateTime(0)
Esempio n. 25
0
    def __iterate__(self):
        """Implements the main loop for the Timer. This function is called every
        second until the Timer expires, updating the Item with the amount of
        time left on the Timer each time. When the time is up it sets the Item
        to 0 and calls the function.
        """
        self.log.debug("There is {} left on the timer"
                       .format(self.time_left))

        # Subtract a second from the time left.
        self.time_left = self.time_left - ONE_SEC

        # We have more time left, reschedule for a second into the future and
        # update the time_left Item.
        if self.time_left > ZERO_SEC:
            self.log.debug("Rescheduling the timer!")
            # Update the count Item.
            self.__update_item__()

            # Reschedule the Timer. If there is more than a second left,
            # reschedule for a second from now. If there is less than a second
            # this is the last iteration and schedule the Timer for the number
            # of milliseconds left.
            next_time = DateTime.now().plusSeconds(1)
            if self.time_left < ONE_SEC:
                next_time = DateTime.now().plusMillis(
                    int(round(self.time_left.total_seconds() * 1000)))
            self.log.debug("Next timer will go off at {}".format(next_time))
            self.timer = ScriptExecution.createTimer(next_time, self.__iterate__)

        # Time's up, call the passed in function.
        else:
            self.log.debug("Time's up!")
            self.time_left = ZERO_SEC
            self.__update_item__()
            self.func()
Esempio n. 26
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),
    )
Esempio n. 27
0
    def lock(self):
        self.locking_level = self.locking_level + 1
        if self.locking_level == 1:  # went from unlocked to locked, manage area timer
            if self.occupancy_timer:  # timer is running, store time remaining
                self.seconds_left_when_locked = seconds_between(
                    DateTime.now(),
                    self.occupancy_timeout)  # save seconds left
                log.warn(
                    "Occupancy Locking turned on, time left in minutes {}".
                    format(int(self.seconds_left_when_locked / 60)))
                # cancel running timer
                self.cancel_timer()

        # update locking state
        events.postUpdate(self.occupancy_locking_item, 'ON')
Esempio n. 28
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)
Esempio n. 29
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)
Esempio n. 30
0
def getgris(match=None,active=True):

    gris={}
    start = DateTime.now()
    end = start.plusHours(2)

    reservations = OSCARSReservations(esnet).retrieveScheduledCircuits()
    for res in reservations:
        if active and (not res.isActive(start,end)):
            continue
        gri = res.getName()
        desc = res.getDescription()
        if match != None:
            if match in desc:
                gris[gri] =res
        else:
            gris[gri] = res
    return gris
Esempio n. 31
0
def getgris(match=None,active=True):

    gris={}
    start = DateTime.now()
    end = start.plusHours(2)

    reservations = OSCARSReservations(esnet).retrieveScheduledCircuits()
    for res in reservations:
        if active and (not res.isActive(start,end)):
            continue
        gri = res.getName()
        desc = res.getDescription()
        if match != None:
            if match in desc:
                gris[gri] =res
        else:
            gris[gri] = res
    return gris
Esempio n. 32
0
	def run(self):
		i = 0
		rCount = 0
		outfile = open(self._outputFile, 'w')
		outfile.write("TIMESTAMP,SIZE,THROUGHPUT\n")
		while True:
			if self._exit:
				break
			start = System.currentTimeMillis()
			self.sleep(self._freq)
			total = 0
			for t in self._pool:
				total = total + t._counter.get()
				t._counter.set(0)
			end = System.currentTimeMillis()
			timestamp = DateTime.now()
			elap = float(end - start)
			elap = elap / 1000.0
			#size = self._counter.get()
			throughput = float(total) / elap
			print "Result Update: Size=" + str(total) + ", Throughput=" + str(throughput)
			outfile.write('"'+self.formatter.print(timestamp) + '","'+str(total)+'","'+str(throughput)+'"')
			outfile.flush()
			i = i + 1
Esempio n. 33
0
                	print port
                	elems = port.split(":")
                	if elems[5] != None:
                        	elems[5] = elems[5].split(".")[0]
                	p =  ":".join(elems)
                	link = links.get(p)
                	if link != None:
                        	routerPort = portsByLink.get(link)[0]
                        	if routerPort.getId() in reserved:
                                	reserved[routerPort.getId()] += long(routerPort.getMaximumReservableCapacity())
                        	else:
                                	reserved[routerPort.getId()] = long(routerPort.getMaximumReservableCapacity())
                	else:   
                        	print "####### NO LINK"

now = DateTime.now()

for circuit in circuits:
	start = circuit.getStartDateTime()
	end = circuit.getEndDateTime()
	if (start >  now):
		print "end= " + end.toString()


for linkid in links.keySet():
	link = links.get(linkid)
	# print linkid + " : " + link.getId() + "   " + link.getRemoteLinkId()



Esempio n. 34
0
from net.es.netshell.api import ModifiedDijkstra
from net.es.netshell.api import TopologyFactory
from net.es.enos.esnet import OSCARSReservations
from net.es.netshell.api import TopologyProvider
from org.joda.time import DateTime

# Create graph with bandwidth weights rather than network metrics
topology = TopologyFactory.instance()
topo = topology.retrieveTopologyProvider("localLayer2")

src = raw_input("src: ")
dst = raw_input("dst: ")
srcNode = topo.getNode(src+"@es.net");
dstNode = topo.getNode(dst+"@es.net");

start = DateTime.now()
end = start.plusHours(2)
reserved = OSCARSReservations(topo).getReserved(start,end)

maxReservable = -1

# Calculate max bandwidth possible from source to destination

tgraph = topo.getGraph(start, end, TopologyProvider.WeightType.MaxBandwidth)

md = ModifiedDijkstra(tgraph, srcNode, dstNode)
maxBandwidth = md.getBandwidth()

# iterate through path to calculate what is the max bandwidth available and the path corresponding
for link in maxBandwidth:
    print "link: " , link.getId()
Esempio n. 35
0
import sys
# Ensure jar is in path.
sys.path.append('./joda-time-2.4/joda-time-2.4.jar')

from org.joda.time import DateTime
from org.joda.time import DateTimeZone
from org.joda.time.chrono import CopticChronology

zone = DateTimeZone.forID("America/Los_Angeles")
coptic = CopticChronology.getInstance(zone)
coptic_today = DateTime(coptic)
print coptic_today.getYear()
print coptic_today.getMonthOfYear()
print coptic_today.toGregorianCalendar()
Esempio n. 36
0
 def test_java_stuff_external_java_library(self):
     from org.joda.time import DateTime
     dt = DateTime(2014, 2, 1, 0, 0)
     self.assertEqual(u"February", dt.monthOfYear().getAsText())