def to_java_zoneddatetime(value): """ Converts any of the supported date types to ``java.time.ZonedDateTime``. If ``value`` does not have timezone information, the system default will be used. Examples: .. code-block:: java_time = to_java_zoneddatetime(items["date_item"]) Args: value: the value to convert Returns: java.time.ZonedDateTime: the converted value Raises: TypeError: if the type of ``value`` is not supported by this module """ if isinstance(value, ZonedDateTime): return value timezone_id = ZoneId.systemDefault() # java.time.LocalDateTime if isinstance(value, LocalDateTime): return value.atZone(timezone_id) # python datetime if isinstance(value, datetime.datetime): if value.tzinfo is not None: timezone_id = ZoneId.ofOffset( "GMT", ZoneOffset.ofTotalSeconds( int(value.utcoffset().total_seconds()))) return ZonedDateTime.of(value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond * 1000, timezone_id) # java.util.Calendar if isinstance(value, Calendar): return ZonedDateTime.ofInstant(value.toInstant(), ZoneId.of(value.getTimeZone().getID())) # java.util.Date if isinstance(value, Date): return ZonedDateTime.ofInstant( value.toInstant(), ZoneId.ofOffset( "GMT", ZoneOffset.ofHours(0 - value.getTimezoneOffset() / 60))) # Joda DateTime if JodaDateTime and isinstance(value, JodaDateTime): return value.toGregorianCalendar().toZonedDateTime() # openHAB DateTimeType if DateTimeType and isinstance(value, DateTimeType): return to_java_zoneddatetime(value.getZonedDateTime()) # Eclipse Smarthome DateTimeType if EclipseDateTimeType and isinstance(value, EclipseDateTimeType): return to_java_zoneddatetime(value.calendar) # Legacy (OH1.x compat) DateTimeType if LegacyDateTimeType and isinstance(value, LegacyDateTimeType): return to_java_zoneddatetime(value.calendar) raise TypeError("Unknown type: {}".format(str(type(value))))
def confirmArriving(self): presenceState = getItemState("pOther_Presence_State").intValue() if presenceState != PresenceHelper.STATE_MAYBE_PRESENT: return newestUpdate = None for item in getItem("gSensor_Indoor").getAllMembers(): if getItemState(item) == OPEN: newestUpdate = ZonedDateTime.now() break _update = getItemLastUpdate(item) if newestUpdate == None or _update.isAfter(newestUpdate): newestUpdate = _update ref = ZonedDateTime.now().minusSeconds(7) self.isConfirmed = newestUpdate.isAfter(ref) or newestUpdate.isEqual( ref) if self.isConfirmed: self.delayedAwayCheck() else: self.setAway(False) self.confirmTimer = None
def doorbell_notification(event): global lastRing # yellow if (lastRing.isBefore(DT.now().minusSeconds(30))): # blue lastRing = DT.now() # yellow # send the doorbell notification logDebug("Demo1", "Doorbeell Alert") else: logDebug("Demo1", "Waiting ...")
def zbAvail(event): LogAction.logInfo("gTHSensorTemperatures", "== gTHSensorTemperatures Item {} received update: {}", event.itemName, event.itemState) newname = event.itemName[:event.itemName.rfind('_')+1] + "reachable" events.postUpdate(newname, "Online") # use reachable not triggering event cos its temp zbAvail.log.info("== ZB temp sensor availability marked ONLINE::") if event.itemName not in timers or timers[event.itemName].hasTerminated(): timers[event.itemName] = ScriptExecution.createTimer(DateTime.now().plusMinutes(timeoutMinutes), lambda: events.postUpdate(newname, "Offline")) else: timers[event.itemName].reschedule(DateTime.now().plusMinutes(timeoutMinutes))
def to_java_zoneddatetime(value): """Converts any known DateTime type to a ``java.time.ZonedDateTime`` type. Args: value: any known DateTime value. Returns: | A ``java.time.ZonedDateTime`` 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. """ timezone_id = ZoneId.systemDefault() if isinstance(value, ZonedDateTime): return value # java.time.LocalDateTime if isinstance(value, LocalDateTime): return value.atZone(timezone_id) # python datetime if isinstance(value, datetime.datetime): if value.tzinfo is not None: timezone_id = ZoneId.ofOffset( "GMT", ZoneOffset.ofTotalSeconds(value.utcoffset().total_seconds())) return ZonedDateTime.of(value.year, value.month, value.day, value.hour, value.minute, value.second, value.microsecond * 1000, timezone_id) # java.util.Calendar if isinstance(value, Calendar): return ZonedDateTime.ofInstant(value.toInstant(), ZoneId.of(value.getTimeZone().getID())) # java.util.Date if isinstance(value, Date): return ZonedDateTime.ofInstant( value.toInstant(), ZoneId.ofOffset( "GMT", ZoneOffset.ofTotalSeconds(value.getTimezoneOffset() * 60))) # Joda DateTime if isinstance(value, DateTime): return value.toGregorianCalendar().toZonedDateTime() # OH DateTimeType or ESH DateTimeType if isinstance(value, (LegacyDateTimeType, DateTimeType)): return to_java_zoneddatetime(value.calendar) raise TypeError("Unknown type: " + str(type(value)))
def execute(self, module, input): if getItemState( "pOther_Automatic_State_Sunprotection_Terrace").intValue( ) == SunProtectionHelper.STATE_TERRACE_MAYBE_CLOSED: pass elif getItemState( "pOther_Automatic_State_Sunprotection_Terrace").intValue( ) == SunProtectionHelper.STATE_TERRACE_CLOSED: # DOWN only if automatic is enabled and (people are present or where present changed recently or terrace door is open) if (getItemState("pOther_Manual_State_Auto_Sunprotection") == ON and (getItemState("pOther_Presence_State").intValue() not in [ PresenceHelper.STATE_AWAY, PresenceHelper.STATE_MAYBE_PRESENT ] or itemLastChangeNewerThen( "pOther_Presence_State", ZonedDateTime.now().minusMinutes(120)) or getItemState( "pGF_Livingroom_Openingcontact_Window_Terrace_State") == OPEN)): #self.log.info(u"down") sendCommand("pOutdoor_Terrace_Shading_Left_Control", DOWN) sendCommand("pOutdoor_Terrace_Shading_Right_Control", DOWN) else: #self.log.info(u"up") # UP always when sun protection time is over sendCommand("pOutdoor_Terrace_Shading_Left_Control", UP) sendCommand("pOutdoor_Terrace_Shading_Right_Control", UP)
def execute(self, module, input): #self.log.info(u"{}".format(input)) now = ZonedDateTime.now().toInstant().toEpochMilli() if self.lastUpdate != -1: currentValue = input['event'].getItemState().longValue() prevValue = input['event'].getOldItemState().longValue() # binding is uint (32) # => max value can be 4294967295 # => is also reseted on dsl reconnection if currentValue > prevValue: diffValue = (currentValue - prevValue) * 8 diffTime = (now - self.lastUpdate) / 1000.0 speed = round(diffValue / diffTime) postUpdateIfChanged("FritzboxWanDownstreamCurrRate", speed) else: self.log.info( u"wan traffic overflow - prev: {}, current: {}".format( prevValue, currentValue)) #self.log.info(u"Downstream {} MBit".format(speed)) self.lastUpdate = now
def execute(self, module, input): #self.log.info(u"{}".format(input)) global ruleTimeouts now = ZonedDateTime.now() last = ruleTimeouts.get("Light_Outdoor", now.minusHours(1)) # No Motion Detector related events if ChronoUnit.SECONDS.between(last, now) > 1: itemName = input['event'].getItemName() self.log.info( "LightOutdoorControlRule => Automatic_Switches => OFF, last: {}, now: {}" .format(last, now)) global timerMappings timer = timerMappings.get(itemName) if timer is not None: timer.cancel() for i, entry in enumerate(manualMappings): if entry[0] == itemName: #ruleTimeouts["Motiondetector_Outdoor_Individual_Switches"] = now # just an update to avoid triggering => MotiondetectorOutdoorIndividualSwitchRule if postUpdateIfChanged(entry[1], OFF): ruleTimeouts[ "Motiondetector_Outdoor_Main_Switch"] = now # must be a command to inform physical knx switch sendCommandIfChanged( "pOutdoor_Light_Automatic_Main_Switch", OFF) #self.log.info(u"{} {}".format(itemName,now-last)) break
def execute(self, module, input): moverStatus = getItemState("pOutdoor_Mower_Status").toString() if itemLastUpdateOlderThen("pOutdoor_Mower_WlanSignal", ZonedDateTime.now().minusMinutes(60)): if moverStatus != "98": postUpdate("pOutdoor_Mower_Status", 98) postUpdate( "pOutdoor_Mower_StatusFormatted", Transformation.transform("MAP", "robonect_status.map", "98")) else: seconds = getItemState("pOutdoor_Mower_Duration").intValue() hours = seconds / (60 * 60) seconds = seconds % (60 * 60) minutes = seconds / 60 #seconds = seconds % 60 msg = u"{} seit ".format( Transformation.transform("MAP", "robonect_status.map", moverStatus)) if hours < 10: msg = u"{}0".format(msg) msg = u"{}{}:".format(msg, hours) if minutes < 10: msg = u"{}0".format(msg) msg = u"{}{}:".format(msg, minutes) postUpdateIfChanged("pOutdoor_Mower_StatusFormatted", msg)
def execute(self, module, input): global ruleTimeouts now = ZonedDateTime.now() #last = ruleTimeouts.get("Motiondetector_Outdoor_Individual_Switches",0) #if now - last > 1000: ruleTimeouts["Motiondetector_Outdoor_Main_Switch"] = now ruleTimeouts["Light_Outdoor"] = now itemName = input['event'].getItemName() itemCommand = input['event'].getItemCommand() switchState = ON for i, entry in enumerate(manualMappings): if entry[1] == itemName: sendCommandIfChanged(entry[0], OFF) if itemCommand == OFF: switchState = OFF else: if getItemState(entry[1]) == OFF: switchState = OFF # must be a command to inform physical knx switch sendCommandIfChanged("pOutdoor_Light_Automatic_Main_Switch", switchState)
def Scene_Goodnight(event): # Scene_Goodnight.log.info("::Boiler_Control rule -> A Heater recieved a command - updating boiler state::") LogAction.logError("Scene_Goodnight", "goodnight going to bed") global tgoodnight global CT_HPSP_Night events.sendCommand("CT_FairyLights433Socket", "OFF") events.sendCommand("ZbColourBulb01Switch", "OFF") events.sendCommand("ZbColourBulb02Switch", "OFF") events.sendCommand("radio", "OFF") events.sendCommand("vCT_TVKodiSpeakers", "OFF") events.postUpdate("CT_Heating_PresetTempNormal", items["CT_HPSP_Night"].toString()) events.postUpdate("FR_Heating_PresetTempNormal", items["FR_HPSP_Night"].toString()) events.postUpdate("ER_Heating_PresetTempNormal", items["ER_HPSP_Night"].toString()) events.postUpdate("AT_Heating_PresetTempNormal", items["AT_HPSP_Night"].toString()) events.postUpdate("BR_Heating_PresetTempNormal", items["BR_HPSP_Night"].toString()) events.postUpdate("OF_Heating_PresetTempNormal", items["OF_HPSP_Night"].toString()) events.postUpdate("HL_Heating_PresetTempNormal", items["HL_HPSP_Night"].toString()) events.sendCommand("Heating_UpdateHeaters", "ON") events.postUpdate("Scene_Goodnight", "OFF") events.sendCommand("workLightsPowerSocket", "OFF") events.sendCommand("workLightsPowerSocket", "OFF") # events.sendCommand("Heating_UpdateHeaters", "ON") #trigger updating of heaters and boiler etc tgoodnight = ScriptExecution.createTimer( DateTime.now().plusSeconds(300), lambda: events.sendCommand("ZbWhiteBulb01Switch", "OFF"))
def execute(self, module, input): now = ZonedDateTime.now() if itemStateOlderThen("Dawn_Time", now) and itemStateNewerThen( "Dusk_Time", now): # triggers solar value update sendCommand("Solar_Total_Yield", REFRESH) sendCommand("Solar_AC_Power", REFRESH) acPower = getItemState('Solar_AC_Power').intValue() dailyConsumption = getItemState("Solar_Daily_Yield").doubleValue() msg = "{} W, {:.2f} kWh".format(acPower, dailyConsumption) if itemLastUpdateOlderThen( "Solar_Total_Yield", now.minusMinutes(15)) and itemStateOlderThen( "Dawn_Time", now.minusMinutes(60)): self.log.error("Solar values not updated") else: msg = "Inaktiv" postUpdateIfChanged("Solar_Message", msg)
def getLastUpdate(item_or_item_name): """ Returns the Item's last update datetime as an ``org.joda.time.DateTime``. If Joda is missing it will return a ``java.time.ZonedDateTime`` instead. Args: item_or_item_name (Item or str): name of the Item Returns: DateTime: Joda DateTime representing the time of the Item's last update ZonedDateTime: ZonedDateTime 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 not None: return to_joda_datetime( last_update) if JodaDateTime else to_java_zoneddatetime( last_update) LOG.warning( u"No existing lastUpdate data for item: '{}', so returning 1970-01-01T00:00:00Z" .format(item.name)) 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 JodaDateTime(0) if JodaDateTime else ZonedDateTime(0)
def execute(self, module, input): itemName = input['event'].getItemName() itemState = input['event'].getItemState() # sometimes, phones are losing wifi connections because of their sleep mode if itemState == OFF: if itemLastChangeOlderThen( "pGF_Corridor_Openingcontact_Door_State", ZonedDateTime.now().minusMinutes(30)): self.skippedTimer[itemName] = startTimer( self.log, 7200, self.process, args=[itemName, itemState]) # 1 hour sendNotification( u"System", u"Delayed presence processing {} for {}".format( itemState, itemName), recipients=['bot_holger']) return else: if itemName in self.skippedTimer: self.skippedTimer[itemName].cancel() del self.skippedTimer[itemName] sendNotification( u"System", u"Cancel presence processing {} for {}".format( itemState, itemName), recipients=['bot_holger']) return self.process(itemName, itemState)
def test_datetime_with_time_zone(self): oldDefaultTimeZone = TimeZone.getDefault() try: TimeZone.setDefault(TimeZone.getTimeZone("GMT+4")) c = tWithDateTimeZCursor(self.context) zoneId = ZoneId.of("GMT+2") #This is the datetime we will insert localDateTime = LocalDateTime.of(2017, Month.DECEMBER, 31, 22, 0, 0) zonedDateTime = ZonedDateTime.of(localDateTime, zoneId) #This is the datetime we expect the database to receive utcDateTime = LocalDateTime.of(2018, Month.JANUARY, 1, 0, 0, 0) c.eventDate = zonedDateTime c.insert() c.clear() c.first() zoneIdAfterSelect = ZoneId.of("GMT+4") self.assertEquals(utcDateTime, c.eventDate.toLocalDateTime()) self.assertEquals(zoneIdAfterSelect, c.eventDate.getZone()) finally: TimeZone.setDefault(oldDefaultTimeZone)
def execute(self, module, input): global ruleTimeouts now = ZonedDateTime.now() last = ruleTimeouts.get("Motiondetector_Outdoor_Main_Switch", now.minusHours(1)) if ChronoUnit.SECONDS.between(last, now) > 1: itemState = input["event"].getItemState() self.log.info( "MotiondetectorOutdoorSwitchRule => last: {}, now: {}, state: {}" .format(last, now, itemState)) if itemState == ON: ruleTimeouts["Light_Outdoor"] = now sendCommandIfChanged( "pOutdoor_Streedside_Garage_Light_Powered", OFF) sendCommandIfChanged( "pOutdoor_Streedside_Frontdoor_Light_Powered", OFF) sendCommandIfChanged("pOutdoor_Carport_Light_Powered", OFF) sendCommandIfChanged("pOutdoor_Terrace_Light_Brightness", 0) sendCommandIfChanged("pOutdoor_Garden_Garage_Light_Powered", OFF) #ruleTimeouts["Motiondetector_Outdoor_Individual_Switches"] = now postUpdateIfChanged("pOutdoor_Streedside_Garage_Automatic_Switch", itemState) postUpdateIfChanged( "pOutdoor_Streedside_Frontdoor_Automatic_Switch", itemState) postUpdateIfChanged("pOutdoor_Carport_Automatic_Switch", itemState) postUpdateIfChanged("pOutdoor_Terrace_Automatic_Switch", itemState) postUpdateIfChanged("pOutdoor_Garden_Garage_Automatic_Switch", itemState)
def boiler_alert(event): global events, lastNotification # yellow logDebug("Demo4", "States: {}".format(events)) eventStr = str(items.BoilerAlarm) # yellow currCount = events[eventStr] # yellow events[eventStr] = currCount + 1 # yellow # //now.plusHours(1) - We don't ever need to cancel the Timer so we don't need to keep a handle on it # ScriptExecution.createTimer(DateTime.now().plusSeconds(5), lambda e=eventStr: update_counter(e)) Timer(5, lambda e=eventStr: update_counter(e)).start() # blue if events["FHS_FAILURE"] >= 3 and events["IS_FAILURE"] >= 1: # green if lastNotification.isBefore(ZDateTime.now().minusSeconds(5)): # blue lastNotification = ZDateTime.now() # yellow logDebug("Demo4", "Sending Boiler Alert Notification") else: logDebug("Demo4", "Waiting ...")
def conservatory_tv_on(event): global t_CTtvPowerOff conservatory_tv_on.log.info("conservatory_tv_on") Voice.say("Turning on conservatory TV", "voicerss:enGB", "chromecast:chromecast:GHM_Conservatory", PercentType(50)) # events.postUpdate("shutdownKodiConservatoryProxy", "ON") events.sendCommand("CT_TV433PowerSocket", "ON") events.sendCommand("amplifier_power", "ON") events.sendCommand("CT_pi_kodi_bg_wifisocket_1_power", "ON") if t_CTtvPowerOff is not None: t_CTtvPowerOff = None t_ampStandbyON = ScriptExecution.createTimer(DateTime.now().plusSeconds(45), lambda: events.sendCommand("amplifierStandby", "ON")) t_ampVideo01 = ScriptExecution.createTimer(DateTime.now().plusSeconds(50), lambda: events.sendCommand("amplifiervideo1", "ON"))
def parse_zoned_date_time(self,t, z): ''' Return ZonedDateTime Input is a java.lang.String parsed to LocalDateTime and ZoneId applied. ''' ldt = self.parse_local_date_time(t) return ZonedDateTime.of(ldt, z)
def zone3lightson(event): zone3lightson.log.warn("zone3 lights o") NotificationAction.sendNotification("*****@*****.**", "Zone 3 light on") global t1, t2, t3 if items["gColourBulbs"] == ON: cycle_len = 5 #secs for x in range(0, 360, 15): events.sendCommand("gZbColourBulbsColour", str(x) + ",100,100") # time.sleep((cycle_len/360)*100) time.sleep(0.1) events.sendCommand("gZbColourBulbsColour", "0,100,100") # events.sendCommand("gColourBulbs", "ON") # ScriptExecution.createTimer(DateTime.now().plusSeconds(2), lambda: events.sendCommand("gZbColourBulbsColour", "120,100,100")) # ScriptExecution.createTimer(DateTime.now().plusSeconds(4), lambda: events.sendCommand("gZbColourBulbsColour", "240,100,100")) # ScriptExecution.createTimer(DateTime.now().plusSeconds(6), lambda: events.sendCommand("gZbColourBulbsColour", "0,100,100")) else: #0=red, 120=green, 240=blue, 360=red #https://community.openhab.org/t/ikea-tradfri-rgb-lights/35551/16 # var DecimalType hue = new DecimalType(hsb.hue.intValue % 360 + 10) // 0-360; 0=red, 120=green, 240=blue, 360=red(again) # var PercentType sat = new PercentType(hsb.saturation.intValue) // 0-100 # var PercentType bright = new PercentType(hsb.brightness.intValue) // 0-100 # var HSBType newHsb = new HSBType(hue,sat,bright) events.sendCommand("gZbColourBulbsColour", "0,100,100") events.sendCommand("gColourBulbs", "ON") ScriptExecution.createTimer( DateTime.now().plusSeconds(2), lambda: events.sendCommand("gZbColourBulbsColour", "120,100,100")) ScriptExecution.createTimer( DateTime.now().plusSeconds(4), lambda: events.sendCommand("gZbColourBulbsColour", "240,100,100")) t3 = ScriptExecution.createTimer( DateTime.now().plusSeconds(6), lambda: events.sendCommand("gColourBulbs", "OFF")) ScriptExecution.createTimer( DateTime.now().plusSeconds(6), lambda: events.sendCommand("gZbColourBulbsColour", "0,100,100"))
def getItemLastUpdate(itemOrName): item = _getItem(itemOrName) lastUpdate = PersistenceExtensions.lastUpdate(item) if lastUpdate is None: return ZonedDateTime.ofInstant(Instant.ofEpochMilli(0), ZoneId.systemDefault()) #raise NotInitialisedException("Item lastUpdate for '" + item.getName() + "' not found") return lastUpdate
def execute(self, module, input): global ruleTimeouts now = ZonedDateTime.now() last = ruleTimeouts.get("Livingroom_Hue_Color_Backward", now) if ChronoUnit.SECONDS.between(last, now) > 1: postUpdate("pGF_Livingroom_Light_Hue_Scene", "") sendCommand("pOther_Manual_State_Lightprogram", 0)
def execute(self, module, input): if getItemState("pOther_Presence_State").intValue() == PresenceHelper.STATE_AWAY and itemLastChangeOlderThen("pOther_Presence_State", ZonedDateTime.now().minusMinutes(60)) \ and getItemState("pIndoor_Roomba_auto") == ON \ and getItemState("pIndoor_Roomba_status").toString() == "Charging" \ and getItemState("pIndoor_Roomba_batPct").intValue() >= 100 \ and getItemState("pIndoor_Roomba_error") == OFF \ and getItemState("pIndoor_Roomba_full") == OFF \ and itemLastChangeOlderThen("pIndoor_Roomba_cleaning_state", ZonedDateTime.now().minusMinutes(360)): sendCommand("pIndoor_Roomba_command", "start")
def execute(self, module, input): if itemStateOlderThen( "pOutdoor_Streedside_Gardendoor_Bell_Last_Change", ZonedDateTime.now().minusSeconds(30)): sendNotification("Klingel", "Es klingelt", "https://smartmarvin.de/cameraStrasseImage") postUpdate("pOutdoor_Streedside_Gardendoor_Bell_Last_Change", DateTimeType())
def scene_Goodnight_init(event): LogAction.logInfo("StartUp - set up Item Scene_Goodnight", "StartUp - set up Item Scene_Goodnight") # events.postUpdate("BridgeLightSensorState", "OFF") global tsceneStartup if tsceneStartup is None: tsceneStartup = ScriptExecution.createTimer( DateTime.now().plusSeconds(45), lambda: events.postUpdate("Scene_Goodnight", "OFF"))
def execute(self, module, input): now = ZonedDateTime.now() currentErtrag = getItemState("Solar_Annual_Yield").doubleValue() currentEinspeisung = getItemState( "Electric_VZ_Jahreseinspeisung").doubleValue() postUpdateIfChanged("Solar_Annual_Consumption", currentErtrag - currentEinspeisung)
def __init__(self): self.triggers = [ ItemStateChangeTrigger( "pGF_Utilityroom_Electricity_Current_Consumption"), CronTrigger("0 */5 * * * ?") ] self.stack = [] self.lastLimitationIncrease = ZonedDateTime.now()
def conservatory_fan(event): conservatory_fan.log.debug("conservatory_fan rulel now") fanOnSecs = 240 sp = items["CT_TemperatureSetpoint"] currentTemp = items["CT_Temperature"] if ((sp >= 20) and (currentTemp < (sp)) and (items["RecircFanEnable"] == ON)): conservatory_fan.log.debug("conservatory fan circulate heat rulel turn FAN ON NOW ZZZZZ") events.sendCommand("CT_Fan433PowerSocket", "ON") ScriptExecution.createTimer(DateTime.now().plusSeconds(fanOnSecs), lambda: ct_fan_body())
def bedroom_tv_off(event): bedroom_tv_off.log.info("bedroom_tv_off") global t_brtvPowerOff Voice.say("Turning off Bedroom TV", "voicerss:enGB", "chromecast:chromecast:GHM_Conservatory", PercentType(50)) events.postUpdate("shutdownKodiBedroomProxy", "OFF") if t_brtvPowerOff is None: t_brtvPowerOff = ScriptExecution.createTimer(DateTime.now().plusSeconds(30), lambda: brtvoffbody())
def bgAvail(event): LogAction.logDebug( "gBG_socket_maxworktime_updates", "!!!! gBG_socket_maxworktime_updates Item {} received update: {}", event.itemName, event.itemState) # create the 'reachable' item name e.g bg_wifisocket_4_maxworktime to bg_wifisocket_4_reachable newname = event.itemName[:event.itemName.rfind('_') + 1] + "reachable" events.postUpdate( newname, "Online") # use reachable not triggering event cos its temp bgAvail.log.debug("== BG sockets Online/Offline status marked ONLINE::") if event.itemName not in timers or timers[event.itemName].hasTerminated(): timers[event.itemName] = ScriptExecution.createTimer( DateTime.now().plusSeconds(timeoutSeconds), lambda: events.postUpdate(newname, "Offline")) else: timers[event.itemName].reschedule( DateTime.now().plusSeconds(timeoutSeconds))
def __init__(self, method="authenticate"): self.username = '' self.app = '' self.issuer = '' self.state = '' self.method = method self.licensed = False self.created = DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now().withNano(0)) self.req_ip = '' self.req_loc = ''