def defer(target, value, when, log, is_command=True): """ Use this function to schedule a command to be sent to an Item at the specified time or after the speficied delay. If the passed in time or delay ends up in the past, the command is sent immediately. Arguments: - target: Item name to send the command to - value: the command to send the Item - when: at what time to delay to action until, see to_datetime in the timer_utils library - is_command: whether to send value to target as an update or command, defaults to True - log: logger passed in from the Rule """ trigger_time = to_datetime(when, log) if not trigger_time: log.error( "Cannot schedule a deferred action, {} is not a valid date time or duration" .format(when)) # If trigger_time is in the past, schedule for now if trigger_time.isBefore(DateTime.now()): trigger_time = DateTime.now() # Schedule the timer func = lambda: timer_body(target, value, is_command, when, log) flap = lambda: log.debug( "there is already a timer set for {}, rescheduling".format(target)) timers.check(target, trigger_time, function=func, flapping_function=flap, reschedule=True)
def gasUsage(event): global contractStart if event.oldItemState is None: return # Calculate consumption last hour used = float( str( PersistenceExtensions.deltaSince(ir.getItem(event.itemName), DateTime.now().minusHours(1)))) events.postUpdate("Gas_Use_Hour", "{0:.3f}".format(used)) gasUsage.log.info("Last Hour Gas Usage [{0:.3f} m3]".format(used / 1000)) cost = used * GAS_PRICE_PER_DM3 events.postUpdate("Gas_Use_Hour_Cost", "{0:.2f}".format(cost)) summary = u"{0:.2f} m3, € {1:.2f}".format(used / 1000, cost) events.postUpdate("Gas_Use_Hour_Summary", summary) gasUsage.log.info(u"Gas Use Hour Summary [{}]".format(summary)) # Calculate consumption today used = float( str( PersistenceExtensions.deltaSince( ir.getItem(event.itemName), DateTime.now().withTimeAtStartOfDay()))) events.postUpdate("Gas_Use_Day", "{0:.3f}".format(used)) gasUsage.log.info("Today's Gas Ussage [{0:.3f}]".format(used / 1000)) cost = used * GAS_PRICE_PER_DM3 events.postUpdate("Gas_Use_Day_Cost", "{0:.2f}".format(cost)) events.postUpdate("Gas_Use_Day_Summary", u"{0:.1f} m3, € {1:.2f}".format(used / 1000, cost)) # Calculate consumption this month used = float( str( PersistenceExtensions.deltaSince( ir.getItem(event.itemName), DateTime.now().withTimeAtStartOfDay().withDayOfMonth(1)))) events.postUpdate("Gas_Use_Month", "{0:.3f}".format(used)) gasUsage.log.info("This Month's Gas Usage [{0:.3f}]".format(used / 1000)) cost = used * GAS_PRICE_PER_DM3 events.postUpdate("Gas_Use_Month_Cost", "{0:.2f}".format(cost)) events.postUpdate("Gas_Use_Month_Summary", u"{0:.0f} m3, € {1:.2f}".format(used / 1000, cost)) # Calculate consumption this year used = float( str( PersistenceExtensions.deltaSince(ir.getItem(event.itemName), contractStart))) if used is None: used = float(str(event.itemState)) - 7374000 gasUsage.log.info( "Fix for missing year data, pre-fill [{}]".format(used)) events.postUpdate("Gas_Use_Year", str(used)) gasUsage.log.info("This Contract Year's Gas Usage [{0:.3f}]".format(used / 1000)) cost = used * GAS_PRICE_PER_DM3 events.postUpdate("Gas_Use_Year_Cost", str(cost)) events.postUpdate("Gas_Use_Year_Summary", u"{0:.0f} m3, € {1:.2f}".format(used / 1000, cost))
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 not event 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]["hour"], mode_dict.items()[i + 1][1]["minute"], mode_dict.items()[i + 1][1]["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))
def __proc_command(self): """ Called when it is time to execute another command. This function simply returns if the queue is empty. Otherwise it pops the next command, executes that command, and then sets a Timer to go off the given number of milliseconds and call __proc_command again to process the next command. """ # No more commands if self.commands.empty(): self.timer = None return # Pop the next command and run it cmd = self.commands.get() funct = cmd[1] before = DateTime.now().millis funct() after = DateTime.now().millis # Calculate how long to sleep delta = after - before pause = to_datetime(cmd[0]) trigger_time = to_datetime(cmd[0]).minusMillis(delta) # Create/reschedule the Timer if not self.timer: self.timer = ScriptExecution.createTimer(trigger_time, self.__proc_command) else: self.timer.reschedule(trigger_time)
def update_mode(event): last_mode_of_day = time_of_day.items()[-1][0] new_mode = last_mode_of_day for i, (mode, value) in enumerate(time_of_day.iteritems()): if i < len(time_of_day) - 1: mode_interval = Interval( DateTime.now().withTime(value['hour'], value['minute'], value['second'], 0), DateTime.now().withTime( time_of_day.items()[i + 1][1]['hour'], time_of_day.items()[i + 1][1]['minute'], time_of_day.items()[i + 1][1]['second'], 0)) if mode_interval.contains(DateTime.now()): new_mode = mode break if items["Mode"] != StringType(new_mode) and ( str(items["Mode"]) in time_of_day.keys() + [last_mode_of_day] 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))
def dimmer(event): global iteration interval = 250 Loops = 0 Befehl = str(event.getItemCommand()).split(",") try: #Fehlerbehebung bei fehlenden FadeStep FadeStepMS = int(Befehl[4]) except (IndexError, ValueError): FadeStepMS = interval TargetValue = int(Befehl[1]) FadePeriodMs = int(Befehl[2]) Item = Befehl[3] try: StartValue = items[Item] except (KeyError): return if items[Item] == NULL: LogAction.logInfo("Timer Test", u"Abbruch") return LogAction.logInfo("Timer Test", u"Item = " + Item) if Item in dimmertimers: LogAction.logInfo("Timer Test", u"Item existiert") dimmertimers[Item]['timer'].cancel() dimmertimers[Item]['timer'] = None del dimmertimers[Item] PercentPerStep = ((float(str(StartValue))) - float(str(TargetValue))) / (FadePeriodMs / FadeStepMS) if PercentPerStep == 0: LogAction.logInfo("Dimmer Routine", u"Nichts zu tun!") return Loops = FadePeriodMs / FadeStepMS dimmertimers[Item] = { 'item': Item, 'timer': ScriptExecution.createTimer(DateTime.now().plusMillis(interval), lambda: DimNow(Item)), 'loops': Loops, 'TargetValue': TargetValue, 'FadePeriod': FadePeriodMs, 'PercentPerStep': PercentPerStep, 'FadeStepMS': FadeStepMS } dimmertimers[Item]['timer'].reschedule(DateTime.now().plusMillis(interval))
def nefitGasHistory(event): httpHeader = {'Content-Type': 'application/json'} # Get the number of gas usage pages from Nefit server response = requests.get(NEFIT_BRIDGE_URL + "/ecus/rrc/recordings/gasusagePointer", headers=httpHeader) if response.status_code != 200: nefitGasHistory.log.warn( "NefitEasy - Invalid API status response [{}]".format(response)) events.sendCommand("CV_Retry_GasUsage", "ON") #Set retry switch else: nefitGasHistory.log.debug("Received Pages JSON data [{}]".format( response.json())) page = int(math.ceil((float(response.json()["value"]) - 1) / 32)) # Get the last web page for yesterdays data response = requests.get(NEFIT_BRIDGE_URL + "/ecus/rrc/recordings/gasusage?page=" + str(page), headers=httpHeader) if response.status_code != 200: nefitGasHistory.log.warn( "NefitEasy - Invalid API status response [{}]".format( response)) events.sendCommand("CV_Retry_GasUsage", "ON") #Set retry switch else: # Walk through JSON Array and find yesterday's entry. yesterday = DateTime.now().minusDays(1).toString("dd-MM-yyyy") for g in response.json()['value']: if g['d'] == yesterday: hotWater = "{0:.3f}".format( float(g['hw']) * GAS_CONVERSION) centralHeating = "{0:.3f}".format( float(g['ch']) * GAS_CONVERSION) influxTimestamp = DateTime.now().withTimeAtStartOfDay( ).minusSeconds(1).millis nefitGasHistory.log.info( "Yesterdays Hot Water [{}], Central Heating [{}]". format(hotWater, centralHeating)) cmd = "/bin/sh@@-c@@/usr/bin/curl -s -X POST " + INFLUXDB_URL + "write?db=" + INFLUXDB + "\\&precision=ms --data-binary '" + NEFIT_HW_SERIES + " value=" + hotWater + " " + str( influxTimestamp) + "'" response = Exec.executeCommandLine(cmd, 4000) if response != "": nefitGasHistory.log.warn( "Error writing " + NEFIT_HW_SERIES + " value to InfluxDB [{}]".format(response)) cmd = "/bin/sh@@-c@@/usr/bin/curl -s -X POST " + INFLUXDB_URL + "write?db=" + INFLUXDB + "\\&precision=ms --data-binary '" + NEFIT_CH_SERIES + " value=" + centralHeating + " " + str( influxTimestamp) + "'" Exec.executeCommandLine(cmd, 4000) if response != "": nefitGasHistory.log.warn( "Error writing " + NEFIT_HW_SERIES + " value to InfluxDB [{}]".format(response)) return nefitGasHistory.log.warn( "No historic gas usage entry found for [{}]".format(yesterday))
def setDayMode(event): # setDayMode.log = logging.getLogger("{}.setDayMode".format(LOG_PREFIX)) setDayMode.log.info( "Enter Day_Mode with Day_Mode [{}], Clouds [{}], Astro_Day_Phase [{}]".format( ir.getItem("Day_Mode").state, ir.getItem("Weather_Cloudy").state, ir.getItem("Astro_Day_Phase").state ) ) cloudy = str(ir.getItem("Weather_Cloudy").state) or "OFF" keyItem = DAY_PHASES_DICT.get(str(ir.getItem("Astro_Day_Phase").state) ) setDayMode.log.info("Day Phase entry is [{}]".format(keyItem.get("mode"))) if keyItem.get("mode") == "time": if DateTime.now().getHourOfDay() < keyItem.get("mode_time"): newState = keyItem.get("before_state") else: newState = keyItem.get("after_state") # TODO: Fix this hack: if str(ir.getItem("Astro_Day_Phase").state) in ["NIGHT", "NAUTIC_DAWN", "CIVIL_DAWN", "ASTRO_DAWN"] and DateTime.now().getHourOfDay() < 6: newState = "NIGHT" else: newState = keyItem.get("clear_state") if cloudy == "OFF" else keyItem.get("cloudy_state") setDayMode.log.info("Set Day_Mode to [{}], if different from [{}]".format(newState, ir.getItem("Day_Mode").state)) postUpdateCheckFirst("Day_Mode", str(newState))
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)))
def exampleTimeOfDay(event): # Get the time period start times for today now = DateTime.now() morningStart = now.withTime(timeOfDay['morningStart']['Hour'], timeOfDay['morningStart']['Minute'], 0, 0).toInstant() dayStart = now.withTime(timeOfDay['dayStart']['Hour'], timeOfDay['dayStart']['Minute'], 0, 0).toInstant() eveningStart = now.withTime(timeOfDay['eveningStart']['Hour'], timeOfDay['eveningStart']['Minute'], 0, 0).toInstant() nightStart = now.withTime(timeOfDay['nightStart']['Hour'], timeOfDay['nightStart']['Minute'], 0, 0).toInstant() timeOfDay = TIMEOFDAY['NIGHT'] if (now.isAfter(morningStart) and now.isBefore(dayStart)): timeOfDay = TIMEOFDAY['MORNING'] elif (now.isAfter(dayStart) and now.isBefore(eveningStart)): timeOfDay = TIMEOFDAY['DAY'] elif (now.isAfter(eveningStart) and now.isBefore(nightStart)): timeOfDay = TIMEOFDAY['EVENING'] if postUpdateCheckFirst('V_TimeOfDay', timeOfDay): exampleTimeOfDay.log.debug("Time of day now: [{}]".format( kw(TIMEOFDAY, timeOfDay)))
def solarSummary(event): if isinstance(items[event.itemName], UnDefType) or event.oldItemState is None: return else: solarSummary.log.info( "Calculate Solar Summary, triggered by [{}]".format( event.itemName)) price = powerPriceDict.get("T" + str(items["Power_Tariff"])).get("return_price") cost = float(event.itemState.toString()) * float(price) summary = "{:.1f} kWh, EUR {:.2f}".format( float(str(event.itemState)) / 1000, cost) costItem = ir.getItem(event.itemName + "_Cost") events.postUpdate(costItem, str(cost)) summaryItem = ir.getItem(event.itemName + "_Summary") events.postUpdate(summaryItem.name, summary) if (str(event.itemName) == "Solar_Prod_Day"): solarDelta = float( str( PersistenceExtensions.deltaSince( ir.getItem("Solar_Prod_Day"), DateTime.now().minusHours(1)))) solarSummary.log.info( "Calculate last hours solar production: [{}]".format(solarDelta)) events.postUpdate("Solar_Prod_Hour", str(solarDelta)) cost = float(solarDelta) * float(price) summary = "{:.1f} kWh, EUR {:.2f}".format(solarDelta / 1000, cost) events.postUpdate("Solar_Prod_Hour_Summary", summary)
def DimNow(Item): try: global iteration interval = dimmertimers[Item]['FadeStepMS'] if iteration >= (int(dimmertimers[Item]['loops'])): events.sendCommand(Item, str(dimmertimers[Item]['TargetValue'])) dimmertimers[Item]['timer'].cancel() iteration = 0 dimmertimers[Item]['timer'] = None del dimmertimers[Item] return else: NewPercent = round( float(str(items[Item])) - float(dimmertimers[Item]['PercentPerStep']), 2) events.sendCommand(Item, str(NewPercent)) dimmertimers[Item]['timer'].reschedule( DateTime.now().plusMillis(interval)) iteration += 1 dimmertimers[Item]['iteration'] = iteration except: LogAction.logInfo("DimNow Routine", u"CleanUp") dimmertimers[Item]['timer'].cancel() dimmertimers[Item]['timer'] = None del dimmertimers[Item]
def __init__(self): ''' Initialise the IdeAlarm class Expects: - Nothing really... ''' self.__version__ = '4.0.0' self.__version_info__ = tuple( [int(num) for num in self.__version__.split('.')]) self.log = logging.getLogger("{}.IdeAlarm V{}".format( LOG_PREFIX, self.__version__)) self.alarmTestMode = idealarm_configuration['ALARM_TEST_MODE'] self.loggingLevel = idealarm_configuration['LOGGING_LEVEL'] self.log.setLevel(self.loggingLevel) self.nagIntervalMinutes = idealarm_configuration[ 'NAG_INTERVAL_MINUTES'] self.timeCreated = DateTime.now() self.alarmZones = [] for i in range(len(idealarm_configuration['ALARM_ZONES'])): zoneNumber = i + 1 self.alarmZones.append( IdeAlarmZone(self, zoneNumber, idealarm_configuration['ALARM_ZONES'][i])) for alarmZone in self.alarmZones: alarmZone.getNagSensors() self.log.info("ideAlarm object initialized with {} zones at {}".format( len(self.alarmZones), format_date(self.timeCreated, customDateTimeFormats['dateTime'])))
def batteryChargingMonitor2(event): #log.debug("JSR223: Power: Battery charging monitor: {}: start".format(event.itemState)) global chargerTimerAttached2 if items["Outlet9"] == OnOffType.ON and event.itemState <= DecimalType(8) and event.oldItemState <= DecimalType(8): if npt chargerTimerAttached2 or chargerTimerAttached2.hasTerminated(): chargerTimerAttached2 = creatTimer(DateTime.now().plusMinutes(5), lambda: events.sendCommand("Outlet9","OFF")) log.info("JSR223: Power: Battery charging monitor: Started battery charging turn off timer: Outlet9_Power=[{}], oldItemState=[{}]".format(event.itemState,event.oldItemState))
def grafanaRefresh(event): if ir.getItems(GRAFANA_GROUP) == []: addGrafanaItems() # Just in case for item in ir.getItem(GRAFANA_GROUP).members: lastRefresh = get_key_value(item.name, "Grafana_Graphs", "LastRefresh") grafanaRefresh.log.debug("Last refresh time for [{}] was [{}]".format( item.name, lastRefresh)) if minutes_between(lastRefresh, DateTime.now()) >= get_key_value( item.name, "Grafana_Graphs", "RefreshRate"): refreshImageItem(item.name) set_metadata(item.name, "Grafana_Graphs", {"LastRefresh": DateTime.now()}) grafanaRefresh.log.debug( "New refresh time for [{}] set to [{}]".format( item.name, get_key_value(item.name, "Grafana_Graphs", "LastRefresh")))
def getOpenSensors(self, mins=0, armingMode=None, isArming=False): ''' Gets all open sensor objects for the zone - mins Integer 0-9999 Number of minutes that the sensor must have been updated within. A 0 value will return sensor devices who are currently open. - armingMode A sensor is regarded to be open only in the context of an arming mode. Defaults to the zones current arming mode. - isArming Boolean. In an arming scenario we don't want to include sensors that are set not to warn when arming. returns a list with open sensor objects. ''' armingMode = self.getArmingMode() if armingMode is None else armingMode openSensors = [] if armingMode == ARMINGMODE['DISARMED']: return openSensors for sensor in self.sensors: if (not sensor.isEnabled()) \ or (mins == 0 and not sensor.isActive()) \ or (isArming and not sensor.armWarn) \ or (mins > 0 and sensor.getLastUpdate().isBefore(DateTime.now().minusMinutes(mins))): continue if armingMode == ARMINGMODE['ARMED_AWAY'] \ or (armingMode == ARMINGMODE['ARMED_HOME'] and sensor.sensorClass != 'B'): openSensors.append(sensor) return openSensors
def query_shelly_status(event): index = 0 for shelly in itemRegistry.getItem("gShellyGeneralCommands").members: ScriptExecution.createTimerWithArgument( DateTime.now().plusSeconds(5 * index), StringType("announce"), shelly.send) index += 1
def timer_acidflush(log): log.info("Done flushing water line") sendCommand("pool_waterfill", OFF) log.info("Backflushing acid pump") sendCommand("pool_acidpumpflush", ON) global timer_acid timer_acid = createTimer(DateTime.now().plusSeconds(10), lambda: timer_flushdone(log))
def timer_fillflush(log): log.info("Acid injection done") sendCommand("pool_acidpump", OFF) log.info("Flushing water line") sendCommand("pool_waterfill", ON) global timer_acid timer_acid = createTimer(DateTime.now().plusSeconds(10), lambda: timer_acidflush(log))
def timer_umbrlla_down(log): log.info("The umbrella is now Closing") sendCommand("pool_umbrellaup", OFF) log.info("Closeing the Umbrella") sendCommand("pool_umbrelladown", ON) global timer_umbrella timer_umbrella = createTimer(DateTime.now().plusSeconds(45), lambda: timer_umbrlla_down(log))
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)
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))
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 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))
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))
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" )
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 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
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))
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
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
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()
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()