def check_update_conditions(self, connection_only=False): ''' Checks the users update conditions are met. Checks for: - active player - idle time - internet connectivity connection_only, limits the check to just the internet connection ''' if not connection_only: result_raw = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1 }') result = json.loads(result_raw) log(result, 'result of Player.GetActivePlayers') players = result.get('result', False) if players: log('Update CONDITION : player playing') return False, 'Update CONDITION : player playing' idle = xbmc.getGlobalIdleTime() if self.s['update_on_idle'] and idle < 60: msg = 'Update CONDITION : idle time = %s' % idle return False, 'Update CONDITION : idle time = %s' % idle return True, ''
def run(self): dbus_utils.LOOP_THREAD.start() oe.load_modules() oe.start_service() service_thread = Service_Thread() service_thread.start() while not self.abortRequested(): if self.waitForAbort(60): break if not oe.read_setting('bluetooth', 'standby'): continue timeout = oe.read_setting('bluetooth', 'idle_timeout') if not timeout: continue try: timeout = int(timeout) except: continue if timeout < 1: continue if xbmc.getGlobalIdleTime() / 60 >= timeout: log.log(f'Idle timeout reached', log.DEBUG) oe.standby_devices() if hasattr(oe, 'winOeMain') and hasattr(oe.winOeMain, 'visible'): if oe.winOeMain.visible == True: oe.winOeMain.close() oe.stop_service() service_thread.stop() dbus_utils.LOOP_THREAD.stop()
def main(): # xbmc.log('3D> main()', xbmc.LOGNOTICE) global dialog, dialogprogress, responseMap, settings, monitor dialog = xbmcgui.Dialog() dialogprogress = xbmcgui.DialogProgress() settings = Settings() monitor = MyMonitor() # xbmc.log('3D> opening serial port', xbmc.LOGNOTICE) # def get_port_ensured(self): # ser = None # while ser == None: # try: # ser = self.get_port() # except serial.serialutil.SerialException: # time.sleep(0.07) # return ser #settings.TVport = serial.Serial(0, 9600, timeout=1) # open first serial port settings.TVport = serial.Serial(settings.TVserialport, 9600, timeout=1) # open first serial port # xbmc.log('3D> ' + settings.TVport.portstr, xbmc.LOGNOTICE) # check which port was really used while not xbmc.abortRequested: if not settings.inScreensaver: settings.pollCount += 1 if xbmc.getGlobalIdleTime() <= settings.idlesec: if settings.pollCount > settings.pollsec: mainTrigger() settings.pollCount = 0 continue xbmc.sleep(1000) onAbort() # xbmc.log('3D> closing serial port', xbmc.LOGNOTICE) settings.TVport.close() # close port
def check_update_conditions(self, media_only=False): ''' Checks the users update conditions are met. The media-only flag restricts the condition check to only the media playing condition. ''' result_raw = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1 }') result = json.loads(result_raw) log(result, 'result of Player.GetActivePlayers') players = result.get('result', False) if players: log('Update CONDITION : player playing') return False, 'Update CONDITION : player playing' idle = xbmc.getGlobalIdleTime() if self.s['update_on_idle'] and idle < 60 and not media_only: msg = 'Update CONDITION : idle time = %s' % idle return False, 'Update CONDITION : idle time = %s' % idle return True, ''
def check_conditions(self): curr_time = datetime.datetime.now() current_idle = divmod(int(xbmc.getGlobalIdleTime()), 60)[0] threshold = self.threshold # Have we been idle long enough? if current_idle < threshold: xbmc.log('BGMusic: check_conditions:F {} < {}'.format( current_idle, threshold)) return False # Are we already playing something? if self.isPlaying(): xbmc.log('BGMusic: check_conditions:F isPlaying') return False # Has it been long enough since something stopped playing? time_since_stop = curr_time - self.last_stopped if time_since_stop < datetime.timedelta(minutes=threshold): xbmc.log( 'BGMusic: check_conditions:F time_since_stop {} < minutes={} threshold' .format(time_since_stop, threshold)) return False # Are we supposed to be playing at this time return self.should_play
def process(self): if not self.use_idle_timer: # skip all, go to sleep pass elif xbmc.Player().isPlaying(): # while playing media we reset the check_time to prevent that we're being # logged out immediately after playing stops self.check_time = time.time() elif xbmc.getGlobalIdleTime() == 0: # user activity so we reset the check_time to 'now' self.check_time = time.time() elif (time.time() - self.check_time) > self.max_idle_time and xbmc.getInfoLabel('System.ProfileName') != self.autologin_profile: idle_time = time.time() - self.check_time # set check_time to 1/1/2030 so we only swap profiles / perform logout once # until the user comes back self.check_time = CHECK_TIME_DISABLED # Activate window to disable the screensaver if self.screensaverActivated: xbmc.executebuiltin("XBMC.ActivateWindow(home)") active_profile = xbmc.getInfoLabel('System.ProfileName') if self.use_login_screen: log("System idle for %d seconds; logging %s out." % (idle_time, active_profile)) xbmc.executebuiltin('System.LogOff') elif xbmc.getInfoLabel('System.ProfileName') != self.autologin_profile: log("System idle for %d seconds; switching from %s to auto login profile %s" % (idle_time, active_profile, self.autologin_profile)) xbmc.executebuiltin("XBMC.LoadProfile(" + self.autologin_profile + ", prompt)")
def _checkIdle(self): if self.doidle is False: return XBMCit = xbmc.getGlobalIdleTime() if self.player.isPlaying(): self._playeridle = False self._startidle = XBMCit else: # player is not playing if self._playeridle is False: # if the first pass with player idle, start timing here self._playeridle = True self._startidle = XBMCit myit = XBMCit - self._startidle # amount of time idle and not playing for it in self.idleTs: if myit > it[0]: # if time exceeded idle timer if it[2] is False: # idle task has NOT been executed msg = Message(Topic('onIdle', it[1])) self.publish(msg) it[2] = True else: # if time has not exceeded timer it[2] = False # reset task executed flag for it in self.afterIdles: if myit > it[0]: # time has exceeded timer it[2] = True # set flag that task needs to be executed when exiting idle else: # time has not exceeded idle timer if it[2] is True: # if flag to execute has been set msg = Message(Topic('afterIdle', it[1])) self.publish(msg) it[2] = False # reset flag to execute
def isIdle(self, since=1): try: if xbmc.getGlobalIdleTime() >= since: return True return False except: return False
def conditions_met(self): curr_time = datetime.datetime.now() current_idle = divmod(int(xbmc.getGlobalIdleTime()), 60)[0] threshold = int(float(__addon__.getSetting('threshold'))) # Have we been idle long enough? if current_idle < threshold: return False # Are we already playing something? if self.isPlaying(): return False # Has it been long enough since something stopped playing? time_since_stop = curr_time - self.last_stopped if time_since_stop < datetime.timedelta(minutes=threshold): return False # Are we supposed to always play? if __addon__.getSetting('always_active') == 'true': return True # Are we supposed to play at this time of day? start_hr = int(__addon__.getSetting('start_hr')) start_min = int(__addon__.getSetting('start_min')) if curr_time.time() > datetime.time(start_hr, start_min): stop_hr = int(__addon__.getSetting('stop_hr')) stop_min = int(__addon__.getSetting('stop_min')) if curr_time.time() < datetime.time(stop_hr, stop_min): return True return False
def check_run_conditions(self): # Update in case things have changed since last check self.gamerTag = ADDON.getSetting("gamertag") self.idle_timeout = ADDON.getSetting("idle_timeout") # Is monitoring enabled? if ADDON.getSetting("enable") == "false": xbmc.log("XBLFriends: Monitoring disabled") return False # Do we have a gamerTag set? if not self.gamerTag: xbmc.log("XBLFriends: No gamerTag set") return False # Are we still under the rate limit? if int(self.current_rate) > int(self.rate_limit): xbmc.log("XBLFriends: Rate limit exceeded. Limit: %s Current: %s" % (self.rate_limit, self.current_rate)) return False if xbmc.getGlobalIdleTime() > self.idle_timeout: xbmc.log( "XBLFriends: XBMC is idle. Not fetching data. idle_timeout: %s" % self.idle_timeout, level=xbmc.LOGDEBUG ) return False return True
def CheckIdle(maxIdle): if maxIdle == 0: return idle = xbmc.getGlobalIdleTime() if idle < maxIdle: return delay = 60 count = delay dp.create("TV Portal", "Streaming will automatically quit in %d seconds" % count, "Press Cancel to contine viewing") dp.update(0) while xbmc.Player().isPlaying() and count > 0 and not dp.iscanceled(): xbmc.sleep(1000) count -= 1 perc = int(((delay - count) / float(delay)) * 100) if count > 1: dp.update( perc, "Streaming will automatically quit in %d seconds" % count, "Press Cancel to contine viewing") else: dp.update(perc, "Streaming will automatically quit in %d second" % count, "Press Cancel to contine viewing") if not dp.iscanceled(): xbmc.Player().stop()
def main(): global dialog, dialogprogress, blackScreen, settings, monitor, ser xbmc.log("3DIR", xbmc.LOGDEBUG) dialog = xbmcgui.Dialog() dialogprogress = xbmcgui.DialogProgress() blackScreen = xbmcgui.Window(-1) settings = Settings() monitor = MyMonitor() ser = serialBegin() while not xbmc.abortRequested: # xbmc.log("3DIR1", xbmc.LOGDEBUG) if settings.detectmode != 1: # xbmc.log("3DIR2", xbmc.LOGDEBUG) if not settings.inScreensaver: # xbmc.log("3DIR3", xbmc.LOGDEBUG) settings.pollCount += 1 if xbmc.getGlobalIdleTime() <= settings.idlesec: # xbmc.log("3DIR4", xbmc.LOGDEBUG) if settings.pollCount > settings.pollsec: # xbmc.log("3DIR5", xbmc.LOGDEBUG) mainTrigger() settings.pollCount = 0 continue xbmc.sleep(1000) onAbort()
def _checkIdle(self): if self.doidle is False: return XBMCit = xbmc.getGlobalIdleTime() if self.player.isPlaying(): self._playeridle = False self._startidle = XBMCit else: # player is not playing if self._playeridle is False: # if the first pass with player idle, start timing here self._playeridle = True self._startidle = XBMCit myit = XBMCit - self._startidle # amount of time idle and not playing for it in self.idleTs: if myit > it[0]: # if time exceeded idle timer if it[2] is False: # idle task has NOT been executed msg = Message(Topic("onIdle", it[1])) self.publish(msg) it[2] = True else: # if time has not exceeded timer it[2] = False # reset task executed flag for it in self.afterIdles: if myit > it[0]: # time has exceeded timer it[2] = True # set flag that task needs to be executed when exiting idle else: # time has not exceeded idle timer if it[2] is True: # if flag to execute has been set msg = Message(Topic("afterIdle", it[1])) self.publish(msg) it[2] = False # reset flag to execute
def CheckIdle(maxIdle): if maxIdle == 0: return idle = xbmc.getGlobalIdleTime() if idle < maxIdle: return delay = 60 count = delay dp = xbmcgui.DialogProgress() dp.create("OnTappTV","Streaming will automatically quit in %d seconds" % count, "Press Cancel to contine viewing") dp.update(0) while xbmc.Player().isPlaying() and count > 0 and not dp.iscanceled(): xbmc.sleep(1000) count -= 1 perc = int(((delay - count) / float(delay)) * 100) if count > 1: dp.update(perc,"Streaming will automatically quit in %d seconds" % count, "Press Cancel to contine viewing") else: dp.update(perc,"Streaming will automatically quit in %d second" % count, "Press Cancel to contine viewing") if not dp.iscanceled(): xbmc.Player().stop()
def check_update_conditions(self, media_only=False): ''' Checks the users update conditions are met. The media-only flag restricts the condition check to only the media playing condition. ''' if self.s['ban_update_media']: result_raw = xbmc.executeJSONRPC( '{ "jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1 }' ) result = json.loads(result_raw) log(result, 'result of Player.GetActivePlayers') players = result.get('result', False) if players: log('Update CONDITION : player playing') return False, 'Update CONDITION : player playing' idle = xbmc.getGlobalIdleTime() if self.s['update_on_idle'] and idle < 60 and not media_only: msg = 'Update CONDITION : idle time = %s' % idle return False, 'Update CONDITION : idle time = %s' % idle return True, ''
def __init__(self): idleTime = 0 isIdle = False while (not xbmc.abortRequested): timeout = int(addon.getSetting('on__idle_time_min')) * 60 # check for user activity and reset timer if xbmc.getGlobalIdleTime() <= 5: # returns the elapsed idle time in seconds as an integer idleTime = 0 IdleActions.OneAfterTimeout = False if isIdle: # reset random/repeat for onidle if addon.getSetting('on__action') == 'PlayMedia': if addon.getSetting('on__random_playmedia') == 'true': xbmc.executebuiltin('PlayerControl(RandomOff)') if addon.getSetting('on__repeatall_playmedia') == 'true': xbmc.executebuiltin('PlayerControl(RepeatOff)') if addon.getSetting('after__after_idle_action_enabled') == 'true': self.afterIdle() isIdle = False if idleTime > timeout: if addon.getSetting('on__service_enabled') == 'true': if not xbmc.Player().isPlaying(): isIdle = True actiontype = addon.getSetting('on__action_type') if actiontype == 'one per startup': if not IdleActions.OnePerStartup: IdleActions.OnePerStartup = True self.onIdle() if actiontype == 'one after timeout': if not IdleActions.OneAfterTimeout: IdleActions.OneAfterTimeout = True self.onIdle() if actiontype == 'repeat with timeout': idleTime = 0 self.onIdle() if actiontype == 'one per second after timeout': self.onIdle() # reset idleTime if something is played by the user if xbmc.Player().isPlaying(): idleTime = 0 else: idleTime = idleTime + 1 xbmc.sleep(1000)
def run(self): _idle_last = 0 while not self._stop_event.isSet(): self._stop_event.wait(0.01) # sleep 10 ms # User activity detected (=idle timer reset)? _idle = xbmc.getGlobalIdleTime() if _idle < _idle_last: self._user_activity = True _idle_last = _idle
def countDown(cls, counter=5): __bar = 0 __percent = 0 __counter = counter __idleTime = xbmc.getGlobalIdleTime() # deactivate screensaver (send key select) if xbmc.getCondVisibility('System.ScreenSaverActive'): query = {"method": "Input.Select"} tools.jsonrpc(query) if xbmc.getCondVisibility('VideoPlayer.isFullscreen'): tools.writeLog('Countdown possibly invisible (fullscreen mode)') tools.writeLog('Showing additional notification') tools.Notify().notify(__LS__(30010), __LS__(30011) % (__counter)) # show countdown tools.writeLog('Display countdown dialog for %s secs' % __counter) pb = xbmcgui.DialogProgressBG() pb.create(__LS__(30010), __LS__(30011) % __counter) pb.update(__percent) # actualize progressbar while __bar <= __counter: __percent = int(__bar * 100 / __counter) pb.update(__percent, __LS__(30010), __LS__(30011) % (__counter - __bar)) if __idleTime > xbmc.getGlobalIdleTime(): tools.writeLog('Countdown aborted by user', level=xbmc.LOGNOTICE) pb.close() return True xbmc.sleep(1000) __idleTime += 1 __bar += 1 pb.close() return False
def _is_idle(self): if self.nx_common.get_setting('wait_idle') != 'true': return True lastidle = xbmc.getGlobalIdleTime() if xbmc.Player().isPlaying(): self.startidle = lastidle if lastidle < self.startidle: self.startidle = 0 idletime = lastidle - self.startidle return idletime >= 300
def _is_idle(self): if self.kodi_helper.get_setting('wait_idle') != 'true': return True lastidle = xbmc.getGlobalIdleTime() if xbmc.Player().isPlaying(): self.startidle = lastidle if lastidle < self.startidle: self.startidle = 0 idletime = lastidle - self.startidle return idletime >= 300
def isTimout(): screensaverTime = Settings.loadScreensaverSettings() if screensaverTime == -1: return False # It is a timeout if the idle time is larger that the time stored # for when the screensaver is due to kick in if (xbmc.getGlobalIdleTime() > screensaverTime): log("Settings: Stopping due to screensaver") return True else: return False
def postAddVideo(self, values=''): # prevent go Kodi to suspend if xbmc.getGlobalIdleTime() > 120: xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Input.ExecuteAction", "params": { "action": "noop" }, "id": 1 }') url = self.setXBMC['RootURL'] + 'sync/movies' debug.debug('[REQUEST]: ' + url) debug.debug('[REQUEST]: ' + str(values)) # try send data data = urllib.urlencode(values, True) data_len = len(data) debug.debug('[REQUEST DATA SIZE]: ' + str(data_len) + ' bytes') for l in range(1, 4): try: request = urllib2.Request(url, data, headers = { 'token' : self.setXBMC['Token']}) result = urllib2.urlopen(request) output = result.read() except Exception as Error: conn = False debug.debug('Can\'t connect to: ' + url) debug.debug('[REQUEST ERROR]: ' + str(Error)) if l < 3: debug.debug('[REQUEST]: Wait 5 secs and retring ' + str(l)) time.sleep(15) else: conn = True break; if conn != True: debug.notify(__lang__(32100).encode('utf-8')) return False debug.debug('[RESPONSE]: ' + str(output)) # if no values return json if values == '': try: output = unicode(output, 'utf-8', errors='ignore') output = json.loads(output) except Exception as Error: debug.debug('[GET JSON ERROR]: ' + str(Error)) return False else: #get errors if len(output) > 0 and 'ERROR:' in output: debug.notify(__lang__(32102).encode('utf-8')) return False return output
def countDown(self, counter): # deactivate screensaver (if running), check screenmode, set progressbar and notify __bar = 0 __percent = 0 __counter = counter __idleTime = xbmc.getGlobalIdleTime() writeLog('Display countdown dialog for %s secs' % __counter) if self.__ScreensaverActive and self.__windowID: xbmc.executebuiltin('ActivateWindow(%s)') % self.__windowID if xbmc.getCondVisibility('VideoPlayer.isFullscreen'): writeLog('Countdown possibly invisible (fullscreen mode)', level=xbmc.LOGDEBUG) writeLog('Showing additional notification', level=xbmc.LOGDEBUG) self.notifyOSD(__LS__(30010), __LS__(30011) % __counter) xbmc.sleep(5000) pb = xbmcgui.DialogProgressBG() pb.create(__LS__(30010), __LS__(30011) % __counter) pb.update(__percent) # actualize progressbar while __bar <= __counter: __percent = int(__bar * 100 / __counter) pb.update(__percent, __LS__(30010), __LS__(30011) % (__counter - __bar)) if __idleTime > xbmc.getGlobalIdleTime(): writeLog('Countdown aborted by user', level=xbmc.LOGNOTICE) pb.close() return True xbmc.sleep(1000) __idleTime += 1 __bar += 1 pb.close() return False
def __init__(self): global ONE_PER_STARTUP_DONE global ONE_AFTER_TIMEOUT_DONE IDLE_TIME = 0 IS_IDLE = False while (not xbmc.abortRequested): TIMEOUT = int(addon.getSetting('on__idle_time_min'))*60 if xbmc.getGlobalIdleTime() <= 5: IDLE_TIME = 0 ONE_AFTER_TIMEOUT_DONE = False if IS_IDLE: if addon.getSetting('after__after_idle_action_enabled') == 'true': self.afterIDLE() IS_IDLE = False if IDLE_TIME > TIMEOUT: if addon.getSetting('on__service_enabled') == 'true': if not xbmc.Player().isPlaying(): IS_IDLE = True actiontype = addon.getSetting('on__action_type') if actiontype == 'one per startup': if not ONE_PER_STARTUP_DONE: ONE_PER_STARTUP_DONE = True self.onIDLE() if actiontype == 'one after timeout': if not ONE_AFTER_TIMEOUT_DONE: ONE_AFTER_TIMEOUT_DONE = True self.onIDLE() if actiontype == 'repeat with timeout': IDLE_TIME = 0 self.onIDLE() if actiontype == 'one per second after timeout': self.onIDLE() if xbmc.Player().isPlaying(): IDLE_TIME = 0 else: IDLE_TIME = IDLE_TIME + 1 xbmc.sleep(1000)
def __init__(self): global ONE_PER_STARTUP_DONE global ONE_AFTER_TIMEOUT_DONE IDLE_TIME = 0 IS_IDLE = False while (not xbmc.abortRequested): TIMEOUT = int(addon.getSetting('on__idle_time_min')) * 60 if xbmc.getGlobalIdleTime() <= 5: IDLE_TIME = 0 ONE_AFTER_TIMEOUT_DONE = False if IS_IDLE: if addon.getSetting( 'after__after_idle_action_enabled') == 'true': self.afterIDLE() IS_IDLE = False if IDLE_TIME > TIMEOUT: if addon.getSetting('on__service_enabled') == 'true': if not xbmc.Player().isPlaying(): IS_IDLE = True actiontype = addon.getSetting('on__action_type') if actiontype == 'one per startup': if not ONE_PER_STARTUP_DONE: ONE_PER_STARTUP_DONE = True self.onIDLE() if actiontype == 'one after timeout': if not ONE_AFTER_TIMEOUT_DONE: ONE_AFTER_TIMEOUT_DONE = True self.onIDLE() if actiontype == 'repeat with timeout': IDLE_TIME = 0 self.onIDLE() if actiontype == 'one per second after timeout': self.onIDLE() if xbmc.Player().isPlaying(): IDLE_TIME = 0 else: IDLE_TIME = IDLE_TIME + 1 xbmc.sleep(1000)
def is_idle(self): """ Check if Kodi has been idle for 5 minutes """ if not g.ADDON.getSettingBool('wait_idle'): return True lastidle = xbmc.getGlobalIdleTime() if xbmc.Player().isPlaying(): self.startidle = lastidle if lastidle < self.startidle: self.startidle = 0 idletime = lastidle - self.startidle return idletime >= 300
def _daemon(self): while (not xbmc.abortRequested): # Do nothing global script_idle if script_idle: if xbmc.getGlobalIdleTime() > 60 * __addon__.getSetting("idle_time"): log('XBMC is idle') log('Going to execute script = "' + script_idle + '"') try: subprocess.call([script_idle, 'KODI_IDLE']) except: log('ERROR executing script when xbmc goes idle') xbmc.sleep(4000) log('abort requested')
def countDown(self, counter): # deactivate screensaver (if running), check screenmode, set progressbar and notify __bar = 0 __percent = 0 __counter = counter __idleTime = xbmc.getGlobalIdleTime() writeLog('Display countdown dialog for %s secs' % __counter) if self.__ScreensaverActive and self.__windowID: xbmc.executebuiltin('ActivateWindow(%s)') % self.__windowID if xbmc.getCondVisibility('VideoPlayer.isFullscreen'): writeLog('Countdown possibly invisible (fullscreen mode)', level=xbmc.LOGDEBUG) writeLog('Showing additional notification', level=xbmc.LOGDEBUG) self.notifyOSD(__LS__(30010), __LS__(30011) % __counter) xbmc.sleep(5000) pb = xbmcgui.DialogProgressBG() pb.create(__LS__(30010), __LS__(30011) % __counter) pb.update(__percent) # actualize progressbar while __bar <= __counter: __percent = int(__bar * 100 / __counter) pb.update(__percent, __LS__(30010), __LS__(30011) % (__counter - __bar)) if __idleTime > xbmc.getGlobalIdleTime(): writeLog('Countdown aborted by user', level=xbmc.LOGNOTICE) pb.close() return True xbmc.sleep(1000) __idleTime += 1 __bar +=1 pb.close() return False
def _daemon(self): while (not xbmc.abortRequested): # Do nothing global script_idle if script_idle: if xbmc.getGlobalIdleTime( ) > 60 * __addon__.getSetting("idle_time"): log('XBMC is idle') log('Going to execute script = "' + script_idle + '"') try: subprocess.call(script_idle) except: log('ERROR executing script when xbmc goes idle') xbmc.sleep(4000) log('abort requested')
def check_update_conditions(self): ''' Checks the users update conditions are met. ''' if self.s['ban_update_media']: result = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1 }') log(result, 'result of Player.GetActivePlayers') players = result.get('result', False) if players: return False if self.s['update_on_idle'] and xbmc.getGlobalIdleTime() < 60: return False return True
def attractMode(): VIDEOS = addon.getSetting('videos').decode('utf-8') BUMPERS = addon.getSetting('bumpers').decode('utf-8') BSTART = addon.getSetting('bstart') BFREQ = int(addon.getSetting('bfreq')) BCROP = int(addon.getSetting('bcrop')) xbmc.log('Loading bumper items') bumperItems = list(getVideos(BUMPERS)) xbmc.log('Loading video items') attractItems = list(getVideos(VIDEOS)) playlist = xbmc.PlayList( xbmc.PLAYLIST_VIDEO ) playlist.clear() random.shuffle(bumperItems) random.shuffle(attractItems) if BSTART == 'true': C = 0 while C < BCROP: I = bumperItems.pop(0) bumperItems.append(I) xbmc.log('Adding bumper %s to playlist' % I) playlist.add(url=I) C += 1 A = 0 for item in attractItems: if A == BFREQ: A = 0 C = 0 while C < BCROP: I = bumperItems.pop(0) bumperItems.append(I) xbmc.log('Adding bumper %s to playlist' % I) playlist.add(url=I) C += 1 xbmc.log('Adding video %s to playlist' % item) playlist.add(item) A += 1 xbmc.executebuiltin("xbmc.PlayerControl(RepeatAll)") xbmc.Player().play(playlist) while(not xbmc.abortRequested): if xbmc.Player().isPlayingVideo: TIMEOUT = int(addon.getSetting('idle_timeout'))*60 IDLE_TIME = xbmc.getGlobalIdleTime() if IDLE_TIME < TIMEOUT: xbmc.log('Exiting attract mode') xbmc.executebuiltin('xbmc.PlayerControl(Stop)') xbmc.executebuiltin("xbmc.PlayerControl(RepeatOff)") break xbmc.sleep(1000)
def attractMode(): VIDEOS = addon.getSetting('videos').decode('utf-8') BUMPERS = addon.getSetting('bumpers').decode('utf-8') BSTART = addon.getSetting('bstart') BFREQ = int(addon.getSetting('bfreq')) BCROP = int(addon.getSetting('bcrop')) xbmc.log('Loading bumper items') bumperItems = list(getVideos(BUMPERS)) xbmc.log('Loading video items') attractItems = list(getVideos(VIDEOS)) playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO) playlist.clear() random.shuffle(bumperItems) random.shuffle(attractItems) if BSTART == 'true': C = 0 while C < BCROP: I = bumperItems.pop(0) bumperItems.append(I) xbmc.log('Adding bumper %s to playlist' % I) playlist.add(url=I) C += 1 A = 0 for item in attractItems: if A == BFREQ: A = 0 C = 0 while C < BCROP: I = bumperItems.pop(0) bumperItems.append(I) xbmc.log('Adding bumper %s to playlist' % I) playlist.add(url=I) C += 1 xbmc.log('Adding video %s to playlist' % item) playlist.add(item) A += 1 xbmc.executebuiltin("xbmc.PlayerControl(RepeatAll)") xbmc.Player().play(playlist) while (not xbmc.abortRequested): if xbmc.Player().isPlayingVideo: TIMEOUT = int(addon.getSetting('idle_timeout')) * 60 IDLE_TIME = xbmc.getGlobalIdleTime() if IDLE_TIME < TIMEOUT: xbmc.log('Exiting attract mode') xbmc.executebuiltin('xbmc.PlayerControl(Stop)') xbmc.executebuiltin("xbmc.PlayerControl(RepeatOff)") break xbmc.sleep(1000)
def is_idle(self): """ Check if Kodi has been idle for 5 minutes """ try: if not G.ADDON.getSettingBool('lib_auto_upd_wait_idle'): return True except TypeError: # Could happen when the service tick is executed at the same time when the settings are written return False lastidle = xbmc.getGlobalIdleTime() if xbmc.Player().isPlaying(): self.startidle = lastidle if lastidle < self.startidle: self.startidle = 0 idletime = lastidle - self.startidle return idletime >= 300
def maintain_caches(interruptable, manual=False): _log(u'Maintenance started') hasFilesLen = HAS_FILES_TAG.__len__() for filename in os.listdir(pathCaches): # Only perform maintenance when idle for more than 60 seconds if (interruptable and xbmc.getGlobalIdleTime() < IDLE_DELAY_SECONDS): _log(u'Maintenance interrupted') return False if not filename.endswith(CACHE_FILE_EXT): continue file = os.path.join(pathCaches, filename) _log(u'Found list cache file: ' + filename) if (expireEnable or manual): # Use modified time, creation time is windows specific # and has tunneling issue age = time.time() - os.path.getmtime(file) # Make sure file is big enough if os.path.getsize(file) <= hasFilesLen: _log(u'File is too small.') delete_cache_file(file) else: # Determine if cache list includes files # (tag previously appended to end of file) with open(file, 'r') as openedfile: # Seek from end of file openedfile.seek(-hasFilesLen, 2) hasFiles = openedfile.read(hasFilesLen) == HAS_FILES_TAG _log(u'List contains files: ' + str(bool(hasFiles))) if ((hasFiles and (age > expireFilesSeconds)) or (not hasFiles and (age > expireFoldersSeconds))): _log(u'File is expired: ' + str(age // 3600) + ' hours old') delete_cache_file(file) else: change_readonly(file, True) _log(u'Maintenance complete') return True
def main(): global dialog, dialogprogress, blackScreen, responseMap, settings, monitor dialog = xbmcgui.Dialog() dialogprogress = xbmcgui.DialogProgress() blackScreen = xbmcgui.Window(-1) responseMap = responsePayloadMapping() settings = Settings() checkAndDiscover() monitor = MyMonitor() while not xbmc.abortRequested: if settings.detectmode != 1: if not settings.inScreensaver: settings.pollCount += 1 if xbmc.getGlobalIdleTime() <= settings.idlesec: if settings.pollCount > settings.pollsec: mainTrigger() settings.pollCount = 0 continue xbmc.sleep(1000) onAbort()
def check_update_conditions(self, connection_only=False): ''' Checks the users update conditions are met. Checks for: - /platform_no_longer_updates file - active player - idle time - internet connectivity connection_only, limits the check to just the internet connection ''' if not connection_only: check_platform, _ = self.check_platform_conditions() if not check_platform: log('Update CONDITION : platform no longer maintained') return False, 'Update CONDITION : platform no longer maintained' result_raw = xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Player.GetActivePlayers", "id": 1 }') result = json.loads(result_raw) log(result, 'result of Player.GetActivePlayers') players = result.get('result', False) if players: log('Update CONDITION : player playing') return False, 'Update CONDITION : player playing' idle = xbmc.getGlobalIdleTime() if self.s['update_on_idle'] and idle < 60: msg = 'Update CONDITION : idle time = %s' % idle return False, 'Update CONDITION : idle time = %s' % idle return True, ''
def runProgram(self): #run until XBMC quits while(not xbmc.abortRequested): structTime = time.localtime() now = time.time() #only do all this if we are in a new minute if(structTime[4] != self.last_check): self.last_check = structTime[4] if xbmc.getGlobalIdleTime() < min_idle_seconds: xbmcgui.Dialog().notification('Idle time is less than ' + min_idle_seconds + ' seconds') if not xbmc.getCondVisibility(System.ScreenSaverActive): xbmcgui.Dialog().notification('Screensaver is not active') if xbmc.isPlaying(): xbmcgui.Dialog().notification('Something is playing') #Switch off screen here xbmcgui.Dialog().notification('Would have switched off screen here!') xbmc.sleep(self.sleep_time)
def run(): # global __options__ try: __options__['tester'] = False info('Starting %s version %s' % (__scriptname__, __version__)) Main.load() if 'onStartup' in Main.dispatcher.ddict: Main.dispatcher.dispatch('onStartup', []) sleep_int = __options__['interval'] executed_idle = False doidle = (('onIdle' in Main.dispatcher.ddict) is True) if doidle: idletime = 60 * __options__['idle_time'] while not abortloop(sleep_int, Main.mm): if doidle: if xbmc.getGlobalIdleTime() > idletime: if not executed_idle: Main.dispatcher.dispatch('onIdle', []) executed_idle = True else: executed_idle = False # xbmc.sleep(sleep_int) if 'onShutdown' in Main.dispatcher.ddict: Main.dispatcher.dispatch('onShutdown', []) if Main.mm is not None: Main.mm.StopListening() del Main.mm del Main.player del Main.dispatcher info('Stopped %s' % __scriptname__) except Exception, e: e = sys.exc_info()[0] msg = '' if hasattr(e, 'message'): msg = msg + str(e.message) msg = msg + '\n' + traceback.format_exc() info(__language__(32053) % msg) notification(__language__(32053) % msg) sys.exit()
def run(self): while (not xbmc.abortRequested): time.sleep(0.5) dialogid = int(xbmcgui.getCurrentWindowDialogId()) is_fullscreen = xbmc.getCondVisibility('VideoPlayer.IsFullscreen') is_playing_tv = xbmc.getCondVisibility('Pvr.IsPlayingTv') is_playing_video = xbmc.getCondVisibility('Player.HasVideo') osd_visible = (dialogid != 9999) idle = xbmc.getGlobalIdleTime() if idle < MAX_OSD_IDLE or is_fullscreen and not osd_visible: continue if not (is_playing_tv or is_playing_video): continue xbmc.log('Idle warning: {0:d} seconds, going full screen'.format(idle)) #xbmc.executebuiltin('Action(FullScreen)') xbmc.executebuiltin('Action(Close)')
def start(self): _currentIdleTime = 0 _maxIdleTime = self.maxIdleTime _msgCnt = 0 while not xbmc.Monitor.abortRequested(self): self.actionCanceled = False if _msgCnt % 10 == 0 and _currentIdleTime > 60 and not self.testConfig: notifyLog( 'idle time in active time frame: %s' % (time.strftime('%H:%M:%S', time.gmtime(_currentIdleTime)))) if _currentIdleTime > xbmc.getGlobalIdleTime(): notifyLog('user activity detected, reset idle time') _msgCnt = 0 _maxIdleTime = self.maxIdleTime _currentIdleTime = 0 _msgCnt += 1 # Check if GlobalIdle longer than maxIdle and we're in a time frame if self.activeTimeFrame(debug=True): if _currentIdleTime > (_maxIdleTime - int(self.notifyUser) * self.notificationTime): notifyLog( 'max idle time reached, ready to perform some action') # Check if notification is allowed if self.notifyUser: _bar = 0 notifyLog( 'init notification countdown for action no. %s' % (self.action)) """ xbmcgui.DialogProgress().create(__LS__(32100), __LS__(32115) % (__LS__(self.action), self.notificationTime)) xbmcgui.DialogProgress().update(_bar) # synchronize progressbar while _bar < self.notificationTime: _bar += 1 _percent = int(_bar * 100 / self.notificationTime) xbmcgui.DialogProgress().update(_percent, __LS__(32115) % (__LS__(self.action), self.notificationTime - _bar)) if xbmcgui.DialogProgress().iscanceled(): self.actionCanceled = True break xbmc.sleep(1000) xbmcgui.DialogProgress().close() xbmc.sleep(500) # """ count = 0 while (self.notificationTime - count > 0): notifyUser( __LS__(32115) % (__LS__(self.action), self.notificationTime - count)) xbmc.sleep(9000) count += 9 if _currentIdleTime > xbmc.getGlobalIdleTime(): self.actionCanceled = True break if not self.actionCanceled: self.sendCecCommand() { 32130: self.stopVideoAudioTV, 32131: self.systemReboot, 32132: self.systemShutdown, 32133: self.systemHibernate, 32134: self.systemSuspend, 32135: self.runAddon, 32136: self.quit }.get(self.action)() # # ToDo: implement more user defined actions here # Action numbers are defined in settings.xml/strings.xml # also see LANGOFFSET # if self.testConfig: notifyLog( 'watchdog was running in test mode, keep it alive' ) else: if self.keepAlive: notifyLog( 'keep watchdog alive, update idletime for next cycle' ) _maxIdleTime += self.maxIdleTime else: break else: notifyLog('Countdown canceled by user action') notifyUser(__LS__(32118), icon=__iconError__) # Reset test status if self.testConfig: __addon__.setSetting('testConfig', 'false') else: notifyLog('no active timeframe yet') # _loop = 1 while not xbmc.Monitor.abortRequested(self): xbmc.sleep(1000) _loop += 1 if self.activeTimeFrame(): _currentIdleTime += 1 if self.SettingsChanged: notifyLog('settings changed') self.getWDSettings() _maxIdleTime = self.maxIdleTime break if self.testConfig or _currentIdleTime > xbmc.getGlobalIdleTime( ) or _loop > 60: break
break; unlockAttempts += 1; xbmc.log(msg='XBMCIdleMythLock: unlock required (status %d), attempt %d'%(status,unlockAttempts+1), level=xbmc.LOGINFO); os.system(unlockCmd); def disallowShutdown(): xbmc.log(msg='XBMCIdleMythLock: disallowing shutdown by locking', level=xbmc.LOGINFO); os.system(statusCmd); status = int(open(tmpFile).read()); if status < 0: xbmc.log(msg='XBMCIdleMythLock: bad status %d; giving up'%status, level=xbmc.LOGINFO); elif status & 16 == 0: xbmc.log(msg='XBMCIdleMythLock: unlocked (status %d); locking'%(status), level=xbmc.LOGINFO); os.system(lockCmd); else: xbmc.log(msg='XBMCIdleMythLock: already locked (status %d); nothing was done'%status, level=xbmc.LOGINFO); try: while 1: currentIdleTime = xbmc.getGlobalIdleTime(); xbmc.log(msg='XBMCIdleMythLock: Idle for %d sec (threshold %d)'%(currentIdleTime,idleThreshold), level=xbmc.LOGINFO); if currentIdleTime < idleThreshold: disallowShutdown(); else: allowShutdown(); time.sleep(60); except: xbmc.log(msg='XBMCIdleMythLock: Exception: %s: %s %s'%(sys.exc_info()[0],sys.exc_info()[1],sys.exc_info()[2]), level=xbmc.LOGINFO); allowShutdown();
while not xbmcm.abortRequested(): if xbmcm.waitForAbort(60): break if not oe.__oe__.read_setting('bluetooth', 'standby'): continue timeout = oe.__oe__.read_setting('bluetooth', 'idle_timeout') if not timeout: continue try: timeout = int(timeout) except: continue if timeout < 1: continue if xbmc.getGlobalIdleTime() / 60 >= timeout: oe.__oe__.dbg_log('service', 'idle timeout reached', 0) oe.__oe__.standby_devices() if hasattr(oe, 'winOeMain') and hasattr(oe.winOeMain, 'visible'): if oe.winOeMain.visible == True: oe.winOeMain.close() oe.stop_service() monitor.stop()
attract_wait_time = int(addon.getSetting("attract_wait_time")) relaunch_previous_view = addon.getSetting("relaunch_previous_view") RESTART_FILE = os.path.join(HLaddonDataPath, 'restart_file.txt') if relaunch_previous_view == 'true': if os.path.exists(RESTART_FILE): f = open(RESTART_FILE, 'r') plugin_path = f.readline() xbmc.executebuiltin('xbmc.ActivateWindow(Videos,%s)' % plugin_path) f.close() os.remove(RESTART_FILE) while not xbmc.abortRequested: addon_path = xbmc.getInfoLabel('Container.FolderPath') if 'plugin.hyper.launcher' in addon_path: idle_time = xbmc.getGlobalIdleTime() if bg_video_wait_time != 0: if idle_time > bg_video_wait_time: if not xbmc.Player().isPlayingVideo(): xbmc.Player().play( item=xbmc.getInfoLabel('ListItem.Trailer'), windowed=1) else: if xbmc.Player().isPlayingVideo(): xbmc.Player().stop() if attract_wait_time != 0: if idle_time > attract_wait_time: total_list_items = int( xbmc.getInfoLabel('Container(id).NumItems')) current_selection = int( xbmc.getInfoLabel('Container(id).CurrentItem')) win = xbmcgui.Window(xbmcgui.getCurrentWindowId())
def __init__(self): FirstCycle = True next_check = False monitor = xbmc.Monitor() while not monitor.abortRequested(): kodi_time = get_kodi_time() try: supervise_start_time = int( selfAddon.getSetting('hour_start_sup').split(':')[0] + selfAddon.getSetting('hour_start_sup').split(':')[1]) except: supervise_start_time = 0 try: supervise_end_time = int( selfAddon.getSetting('hour_end_sup').split(':')[0] + selfAddon.getSetting('hour_end_sup').split(':')[1]) except: supervise_end_time = 0 proceed = should_i_supervise(kodi_time, supervise_start_time, supervise_end_time) if proceed: if FirstCycle: # Variables: enable_audio = audio_enable enable_video = video_enable maxaudio_time_in_minutes = max_time_audio maxvideo_time_in_minutes = max_time_video iCheckTime = check_time _log("started ... (" + str(__version__) + ")") if debug == 'true': _log( "DEBUG: ################################################################" ) _log("DEBUG: Settings in Kodi:") _log('DEBUG: enable_audio: ' + enable_audio) _log("DEBUG: maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes)) _log("DEBUG: enable_video: " + str(enable_video)) _log("DEBUG: maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes)) _log("DEBUG: check_time: " + str(iCheckTime)) _log("DEBUG: Supervision mode: Always") _log( "DEBUG: ################################################################" ) # Set this low values for easier debugging! _log("DEBUG: debug is enabled! Override Settings:") enable_audio = 'true' _log("DEBUG: -> enable_audio: " + str(enable_audio)) maxaudio_time_in_minutes = 1 _log("DEBUG: -> maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes)) enable_video = 'true' _log("DEBUG: -> enable_video: " + str(enable_audio)) maxvideo_time_in_minutes = 1 _log("DEBUG: -> maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes)) iCheckTime = 1 _log("DEBUG: -> check_time: " + str(iCheckTime)) _log( "DEBUG: ----------------------------------------------------------------" ) # wait 15s before start to let Kodi finish the intro-movie if monitor.waitForAbort(15): break max_time_in_minutes = -1 FirstCycle = False idle_time = xbmc.getGlobalIdleTime() idle_time_in_minutes = int(idle_time) / 60 if xbmc.Player().isPlaying(): if debug == 'true' and max_time_in_minutes == -1: _log( "DEBUG: max_time_in_minutes before calculation: " + str(max_time_in_minutes)) if next_check == 'true': # add "diff_between_idle_and_check_time" to "idle_time_in_minutes" idle_time_in_minutes += int( diff_between_idle_and_check_time) if debug == 'true' and max_time_in_minutes == -1: _log("DEBUG: max_time_in_minutes after calculation: " + str(max_time_in_minutes)) if xbmc.Player().isPlayingAudio(): if enable_audio == 'true': if debug == 'true': _log("DEBUG: enable_audio is true") print_act_playing_file() what_is_playing = "audio" max_time_in_minutes = maxaudio_time_in_minutes else: if debug == 'true': _log( "DEBUG: Player is playing Audio, but check is disabled" ) do_next_check(iCheckTime) continue elif xbmc.Player().isPlayingVideo(): if enable_video == 'true': if debug == 'true': _log("DEBUG: enable_video is true") print_act_playing_file() what_is_playing = "video" max_time_in_minutes = maxvideo_time_in_minutes else: if debug == 'true': _log( "DEBUG: Player is playing Video, but check is disabled" ) do_next_check(iCheckTime) continue ### ToDo: # expand it with RetroPlayer for playing Games!!! else: if debug == 'true': _log( "DEBUG: Player is playing, but no Audio or Video" ) print_act_playing_file() what_is_playing = "other" do_next_check(iCheckTime) continue if debug == 'true': _log("DEBUG: what_is_playing: " + str(what_is_playing)) if debug == 'true': _log("DEBUG: idle_time: '" + str(idle_time) + "s'; idle_time_in_minutes: '" + str(idle_time_in_minutes) + "'") _log("DEBUG: max_time_in_minutes: " + str(max_time_in_minutes)) # only display the Progressdialog, if audio or video is enabled AND idle limit is reached # Check if what_is_playing is not "other" and idle time exceeds limit if (what_is_playing != "other" and idle_time_in_minutes >= max_time_in_minutes): if debug == 'true': _log( "DEBUG: idle_time exceeds max allowed. Display Progressdialog" ) ret = msgdialogprogress.create(translate(30000), translate(30001)) secs = 0 percent = 0 # use the multiplier 100 to get better %/calculation increment = 100 * 100 / time_to_wait cancelled = False while secs < time_to_wait: secs = secs + 1 # divide with 100, to get the right value percent = increment * secs / 100 secs_left = str((time_to_wait - secs)) remaining_display = str( secs_left) + " seconds left." msgdialogprogress.update(int(percent), translate(30001)) xbmc.sleep(1000) if (msgdialogprogress.iscanceled()): cancelled = True if debug == 'true': _log("DEBUG: Progressdialog cancelled") break if cancelled == True: iCheckTime = check_time_next _log("Progressdialog cancelled, next check in " + str(iCheckTime) + " min") # set next_check, so that it opens the dialog after "iCheckTime" next_check = True msgdialogprogress.close() else: _log( "Progressdialog not cancelled: stopping Player" ) msgdialogprogress.close() # softmute audio before stop playing # get actual volume if audiochange == 'true': resp = xbmc.executeJSONRPC( '{"jsonrpc": "2.0", "method": "Application.GetProperties", "params": { "properties": [ "volume"] }, "id": 1}' ) dct = json.loads(resp) muteVol = 10 if ("result" in dct) and ("volume" in dct["result"]): curVol = dct["result"]["volume"] for i in range(curVol - 1, muteVol - 1, -1): xbmc.executebuiltin( 'SetVolume(%d,showVolumeBar)' % (i)) # move down slowly xbmc.sleep(audiochangerate) # stop player anyway monitor.waitForAbort(5) # wait 5s before stopping xbmc.executebuiltin('PlayerControl(Stop)') if audiochange == 'true': monitor.waitForAbort( 2 ) # wait 2s before changing the volume back if ("result" in dct) and ("volume" in dct["result"]): curVol = dct["result"]["volume"] # we can move upwards fast, because there is nothing playing xbmc.executebuiltin( 'SetVolume(%d,showVolumeBar)' % (curVol)) if enable_screensaver == 'true': if debug == 'true': _log("DEBUG: Activating screensaver") xbmc.executebuiltin('ActivateScreensaver') # Run a custom cmd after playback is stopped if custom_cmd == 'true': if debug == 'true': _log("DEBUG: Running custom script") os.system(cmd) else: if debug == 'true': _log( "DEBUG: Playing the stream, time does not exceed max limit" ) else: if debug == 'true': _log("DEBUG: Not playing any media file") # reset max_time_in_minutes max_time_in_minutes = -1 diff_between_idle_and_check_time = idle_time_in_minutes - int( iCheckTime) if debug == 'true' and next_check == 'true': _log("DEBUG: diff_between_idle_and_check_time: " + str(diff_between_idle_and_check_time)) do_next_check(iCheckTime) monitor.waitForAbort(1)
def start(self): _currentIdleTime = 0 _maxIdleTime = self.maxIdleTime while not xbmc.Monitor.abortRequested(self): self.actionCanceled = False _status = False if not self.timeframe or self.mode == 'USER': _status = True else: _currframe = (datetime.datetime.now() - datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)).seconds if self.act_start < self.act_stop: if self.act_start <= _currframe < self.act_stop: _status = True else: if self.act_start <= _currframe < 86400 or 0 <= _currframe < self.act_stop: _status = True if self.wd_status ^ _status: notifyLog('Watchdog status changed: %s' % ('active' if _status else 'inactive')) self.wd_status = _status if self.wd_status and _currentIdleTime > 60 and not self.testConfig: notifyLog('idle time: %s' % (str(datetime.timedelta(seconds=_currentIdleTime)))) if _currentIdleTime > xbmc.getGlobalIdleTime(): notifyLog('user activity detected, reset idle time') _maxIdleTime = self.maxIdleTime if self.mode == 'SERVICE' else self.userIdleTime _currentIdleTime = 0 # Check if GlobalIdle longer than maxIdle and we're in a time frame if self.wd_status or self.testConfig: if _currentIdleTime > (_maxIdleTime - int(self.notifyUser)*self.notificationTime): notifyLog('max idle time reached, ready to perform some action') # Check if notification is allowed if self.notifyUser: count = 0 notifyLog('init notification countdown for action no. %s' % (self.action)) while (self.notificationTime - count > 0): notifyUser(LOC(32115) % (LOC(self.action), self.notificationTime - count), time=7000) if xbmc.Monitor.waitForAbort(self, 10): break count += 10 if _currentIdleTime > xbmc.getGlobalIdleTime(): self.actionCanceled = True break if not self.actionCanceled: self.sendCecCommand() { 32130: self.stopVideoAudioTV, 32131: self.systemReboot, 32132: self.systemShutdown, 32133: self.systemHibernate, 32134: self.systemSuspend, 32135: self.runAddon, 32136: self.quit }.get(self.action)() # # ToDo: implement more user defined actions here # Action numbers are defined in settings.xml/strings.xml # also see LANGOFFSET # if self.testConfig: notifyLog('watchdog was running in test mode, keep it alive') else: if self.keepAlive: notifyLog('keep watchdog alive, update idletime for next cycle') _maxIdleTime += self.maxIdleTime else: break else: notifyLog('Countdown canceled by user action') notifyUser(LOC(32118), icon=ICON_ERROR) # Reset test status if self.testConfig: ADDON.setSetting('testConfig', 'false') _loop = 0 while not xbmc.Monitor.waitForAbort(self, 15): _loop += 15 _currentIdleTime += 15 if self.SettingsChanged: notifyLog('settings changed') self.getWDSettings() _maxIdleTime = self.maxIdleTime break if self.testConfig or _currentIdleTime > xbmc.getGlobalIdleTime() or _loop >= 60: break
def autoStop(self, hrs=2): # get auto stop to prevent 24/7 running :D # http://forum.xbmc.org/showthread.php?tid=129473&pid=1082117#pid1082117 return xbmc.getGlobalIdleTime() > (hrs * 60**2)
def __init__(self): FirstCycle = True next_check = False while True: kodi_time = get_kodi_time() try: supervise_start_time = int(selfAddon.getSetting('hour_start_sup').split(':')[0]+selfAddon.getSetting('hour_start_sup').split(':')[1]) except: supervise_start_time = 0 try: supervise_end_time = int(selfAddon.getSetting('hour_end_sup').split(':')[0]+selfAddon.getSetting('hour_end_sup').split(':')[1]) except: supervise_end_time = 0 proceed = should_i_supervise(kodi_time,supervise_start_time,supervise_end_time) if proceed: if FirstCycle: # Variables: enable_audio = audio_enable enable_video = video_enable maxaudio_time_in_minutes = max_time_audio maxvideo_time_in_minutes = max_time_video iCheckTime = check_time _log ( "started ... (" + str(__version__) + ")" ) if debug == 'true': _log ( "DEBUG: ################################################################" ) _log ( "DEBUG: Settings in Kodi:" ) _log ( 'DEBUG: enable_audio: ' + enable_audio ) _log ( "DEBUG: maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes) ) _log ( "DEBUG: enable_video: " + str(enable_video) ) _log ( "DEBUG: maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes) ) _log ( "DEBUG: check_time: " + str(iCheckTime) ) _log ( "DEBUG: Supervision mode: Always") _log ( "DEBUG: ################################################################" ) # Set this low values for easier debugging! _log ( "DEBUG: debug is enabled! Override Settings:" ) enable_audio = 'true' _log ( "DEBUG: -> enable_audio: " + str(enable_audio) ) maxaudio_time_in_minutes = 1 _log ( "DEBUG: -> maxaudio_time_in_minutes: " + str(maxaudio_time_in_minutes) ) enable_video = 'true' _log ( "DEBUG: -> enable_video: " + str(enable_audio) ) maxvideo_time_in_minutes = 1 _log ( "DEBUG: -> maxvideo_time_in_minutes: " + str(maxvideo_time_in_minutes) ) iCheckTime = 1 _log ( "DEBUG: -> check_time: " + str(iCheckTime) ) _log ( "DEBUG: ----------------------------------------------------------------" ) # wait 15s before start to let Kodi finish the intro-movie if xbmc.Monitor().waitForAbort(15): break max_time_in_minutes = -1 FirstCycle = False idle_time = xbmc.getGlobalIdleTime() idle_time_in_minutes = int(idle_time)/60 if xbmc.Player().isPlaying(): if debug == 'true' and max_time_in_minutes == -1: _log ( "DEBUG: max_time_in_minutes before calculation: " + str(max_time_in_minutes) ) if next_check == 'true': # add "diff_betwenn_idle_and_check_time" to "idle_time_in_minutes" idle_time_in_minutes += int(diff_betwenn_idle_and_check_time) if debug == 'true' and max_time_in_minutes == -1: _log ( "DEBUG: max_time_in_minutes after calculation: " + str(max_time_in_minutes) ) if xbmc.Player().isPlayingAudio(): if enable_audio == 'true': if debug == 'true': _log ( "DEBUG: enable_audio is true" ) print_act_playing_file() what_is_playing = "audio" max_time_in_minutes = maxaudio_time_in_minutes else: if debug == 'true': _log ( "DEBUG: Player is playing Audio, but check is disabled" ) do_next_check(iCheckTime) continue elif xbmc.Player().isPlayingVideo(): if enable_video == 'true': if debug == 'true': _log ( "DEBUG: enable_video is true" ) print_act_playing_file() what_is_playing = "video" max_time_in_minutes = maxvideo_time_in_minutes else: if debug == 'true': _log ( "DEBUG: Player is playing Video, but check is disabled" ) do_next_check(iCheckTime) continue ### ToDo: # expand it with RetroPlayer for playing Games!!! else: if debug == 'true': _log ( "DEBUG: Player is playing, but no Audio or Video" ) print_act_playing_file() what_is_playing = "other" do_next_check(iCheckTime) continue if debug == 'true': _log ( "DEBUG: what_is_playing: " + str(what_is_playing) ) if debug == 'true': _log ( "DEBUG: idle_time: '" + str(idle_time) + "s'; idle_time_in_minutes: '" + str(idle_time_in_minutes) + "'" ) _log ( "DEBUG: max_time_in_minutes: " + str(max_time_in_minutes) ) # only display the Progressdialog, if audio or video is enabled AND idle limit is reached # Check if what_is_playing is not "other" and idle time exceeds limit if ( what_is_playing != "other" and idle_time_in_minutes >= max_time_in_minutes ): if debug == 'true': _log ( "DEBUG: idle_time exceeds max allowed. Display Progressdialog" ) ret = msgdialogprogress.create(translate(30000),translate(30001)) secs=0 percent=0 # use the multiplier 100 to get better %/calculation increment = 100*100 / time_to_wait cancelled = False while secs < time_to_wait: secs = secs + 1 # divide with 100, to get the right value percent = increment*secs/100 secs_left = str((time_to_wait - secs)) remaining_display = str(secs_left) + " seconds left." msgdialogprogress.update(percent,translate(30001),remaining_display) xbmc.sleep(1000) if (msgdialogprogress.iscanceled()): cancelled = True if debug == 'true': _log ( "DEBUG: Progressdialog cancelled" ) break if cancelled == True: iCheckTime = check_time_next _log ( "Progressdialog cancelled, next check in " + str(iCheckTime) + " min" ) # set next_check, so that it opens the dialog after "iCheckTime" next_check = True msgdialogprogress.close() else: _log ( "Progressdialog not cancelled: stopping Player" ) msgdialogprogress.close() # softmute audio before stop playing # get actual volume if audiochange == 'true': resp = xbmc.executeJSONRPC('{"jsonrpc": "2.0", "method": "Application.GetProperties", "params": { "properties": [ "volume"] }, "id": 1}') dct = json.loads(resp) muteVol = 10 if (dct.has_key("result")) and (dct["result"].has_key("volume")): curVol = dct["result"]["volume"] for i in range(curVol - 1, muteVol - 1, -1): xbmc.executebuiltin('SetVolume(%d,showVolumeBar)' % (i)) # move down slowly xbmc.sleep(audiochangerate) # stop player anyway xbmc.sleep(5000) # wait 5s before stopping xbmc.executebuiltin('PlayerControl(Stop)') if audiochange == 'true': xbmc.sleep(2000) # wait 2s before changing the volume back if (dct.has_key("result")) and (dct["result"].has_key("volume")): curVol = dct["result"]["volume"] # we can move upwards fast, because there is nothing playing xbmc.executebuiltin('SetVolume(%d,showVolumeBar)' % (curVol)) if enable_screensaver == 'true': if debug == 'true': _log ( "DEBUG: Activating screensaver" ) xbmc.executebuiltin('ActivateScreensaver') #Run a custom cmd after playback is stopped if custom_cmd == 'true': if debug == 'true': _log ( "DEBUG: Running custom script" ) os.system(cmd) else: if debug == 'true': _log ( "DEBUG: Playing the stream, time does not exceed max limit" ) else: if debug == 'true': _log ( "DEBUG: Not playing any media file" ) # reset max_time_in_minutes max_time_in_minutes = -1 diff_between_idle_and_check_time = idle_time_in_minutes - int(iCheckTime) if debug == 'true' and next_check == 'true': _log ( "DEBUG: diff_between_idle_and_check_time: " + str(diff_between_idle_and_check_time) ) do_next_check(iCheckTime)
def getIdle(min=True): idleTime = xbmc.getGlobalIdleTime() if min: return int(idleTime) / 60 return idleTime
def autoStop( self, hrs=2 ): # get auto stop to prevent 24/7 running :D # http://forum.xbmc.org/showthread.php?tid=129473&pid=1082117#pid1082117 return xbmc.getGlobalIdleTime() > ( hrs*60**2 )
def start(self): _currentIdleTime = 0 _maxIdleTime = self.maxIdleTime _msgCnt = 0 while not xbmc.Monitor.abortRequested(self): self.actionCanceled = False if _msgCnt % 10 == 0 and _currentIdleTime > 60 and not self.testConfig: notifyLog('idle time in active time frame: %s' % (time.strftime('%H:%M:%S', time.gmtime(_currentIdleTime)))) if _currentIdleTime > xbmc.getGlobalIdleTime(): notifyLog('user activity detected, reset idle time', level=xbmc.LOGDEBUG) _msgCnt = 0 _maxIdleTime = self.maxIdleTime _currentIdleTime = 0 _msgCnt += 1 # Check if GlobalIdle longer than maxIdle and we're in a time frame if self.activeTimeFrame(debug=True): if _currentIdleTime > (_maxIdleTime - int(self.notifyUser)*self.notificationTime): notifyLog('max idle time reached, ready to perform some action', level=xbmc.LOGDEBUG) # Check if notification is allowed if self.notifyUser: _bar = 0 notifyLog('init notification countdown for action no. %s' % (self.action), level=xbmc.LOGDEBUG) self.PopUp.create(__LS__(32100), __LS__(32115) % (__LS__(self.action), self.notificationTime)) self.PopUp.update(_bar) # synchronize progressbar while _bar < self.notificationTime: _bar += 1 _percent = int(_bar * 100 / self.notificationTime) self.PopUp.update(_percent, __LS__(32100), __LS__(32115) % (__LS__(self.action), self.notificationTime - _bar)) if self.PopUp.iscanceled(): self.actionCanceled = True break xbmc.sleep(1000) self.PopUp.close() xbmc.sleep(500) # if not self.actionCanceled: self.sendCecCommand() { 32130: self.stopVideoAudioTV, 32131: self.systemReboot, 32132: self.systemShutdown, 32133: self.systemHibernate, 32134: self.systemSuspend, 32135: self.runAddon, 32136: self.quit }.get(self.action)() # # ToDo: implement more user defined actions here # Action numbers are defined in settings.xml/strings.xml # also see LANGOFFSET # if self.testConfig: notifyLog('watchdog was running in test mode, keep it alive', level=xbmc.LOGDEBUG) else: if self.keepAlive: notifyLog('keep watchdog alive, update idletime for next cycle', level=xbmc.LOGDEBUG) _maxIdleTime += self.maxIdleTime else: break # Reset test status if self.testConfig: __addon__.setSetting('testConfig', 'false') else: notifyLog('no active timeframe yet', level=xbmc.LOGDEBUG) # _loop = 1 while not xbmc.Monitor.abortRequested(self): xbmc.sleep(1000) _loop += 1 if self.activeTimeFrame(): _currentIdleTime += 1 if self.SettingsChanged: notifyLog('settings changed') self.getWDSettings() _maxIdleTime = self.maxIdleTime break if self.testConfig or _currentIdleTime > xbmc.getGlobalIdleTime() or _loop > 60: break
def _get(self, key): if key == 'lang': return xbmc.getLanguage() elif key == 'langname': langname = xbmc.getLanguage() if langname.find('Oromo') != -1: langname = 'Oromo' else: for tag in (' (', ';', ','): i = langname.find(tag) if i != -1: langname = langname[0:i] break try: LANGCODE[langname] except KeyError: return 'English' else: return langname elif key == 'langcode': return LANGCODE[self._get('langname')] elif key == 'dvd': state = {0: 'open', 1: 'notready', 2: 'ready', 3: 'empty', 4: 'present', 5: None} return state[xbmc.getDVDState()] elif key == 'mem': return xbmc.getFreeMem() # MB elif key == 'time': return xbmc.getGlobalIdleTime() elif key == 'skin': return xbmc.getSkinDir() elif key == 'ip': return xbmc.getIPAddress() elif key == 'platform': if self._platform == -1: for platform in ('linux', 'windows', 'android', 'atv2', 'ios', 'osx'): if xbmc.getCondVisibility('system.platform.' + platform): self._platform = platform break else: self._platform = None return self._platform elif key == 'is_64bits': return sys.maxsize > 2**32 elif key == 'support': if not self._support['all']: for src, dst in (('video', 'video'), ('music', 'audio'), ('picture', 'picture')): self._support[dst] = [x[1:] for x in xbmc.getSupportedMedia(src).split('|')] self._support['all'].extend(self._support[dst]) return self._support elif key == 'region': if not self._region: for tag in ('dateshort', 'datelong', 'time', 'meridiem', 'tempunit', 'speedunit'): self._region[tag] = xbmc.getRegion(tag) return self._region else: raise AttributeError, key
if freq: while not monitor.abortRequested(): from datetime import datetime, timedelta today = datetime.today() freq = var.addon.getSetting('auto_update') time = var.addon.getSetting('update_time') time = '00:00' if time == '' else time last = getConfig('last_update', '1970-01-01') update_run = updateRunning() if freq == '0': break dt = last + ' ' + time[0:5] dtlast = strp(dt, '%Y-%m-%d %H:%M') freqdays = [0, 1, 2, 5, 7][int(freq)] lastidle = xbmc.getGlobalIdleTime() if xbmc.Player().isPlaying(): startidle = lastidle if lastidle < startidle: startidle = 0 idletime = lastidle - startidle if var.addon.getSetting('wait_idle') != 'true': idletime = idleupdate if dtlast + timedelta(days=freqdays) <= today and idletime >= idleupdate: if not update_run: Log('Starting DBUpdate ({} / {})'.format(dtlast, today)) xbmc.executebuiltin('XBMC.RunPlugin(plugin://{}/?mode=appfeed&sitemode=updateAll)'.format(var.addon.getAddonInfo('id'))) if monitor.waitForAbort(checkfreq): break
xbmc.log('Exiting attract mode') xbmc.executebuiltin('xbmc.PlayerControl(Stop)') xbmc.executebuiltin("xbmc.PlayerControl(RepeatOff)") break xbmc.sleep(1000) class blankScreen(xbmcgui.Window): def __init__(self): pass bs = blankScreen() IDLE_TIME = 0 while (not xbmc.abortRequested): if xbmc.getGlobalIdleTime() <= 5: IDLE_TIME = 0 TIMEOUT = int(addon.getSetting('idle_timeout')) * 60 if IDLE_TIME < TIMEOUT: PLAYED_TRAILERS = False del bs bs = blankScreen() if IDLE_TIME > TIMEOUT: if not xbmc.Player().isPlaying(): if not PLAYED_TRAILERS: PLAYED_TRAILERS = True bs.show() attractMode() if xbmc.Player().isPlaying(): IDLE_TIME = 0 else:
def __init__(self): # all options within this dict will be synced to VDR # important: id within settings.xml must match variable name in vdr's setup.conf # Be sure to send the datatypes needed by the dbus2vdr plugin for each setting # each dict entry needs this sytax: '<Variable Name>':'<dbus data types ('si'=string, integer; 'ss'=string, string>')>' self.Options = { 'MinUserInactivity':'si', 'MinEventTimeout':'si', 'MarginStart':'si', 'MarginStop':'si', 'DefaultPriority':'si', 'MaxVideoFileSize':'si', 'DefaultLifetime':'si', #'DumpNaluFill':'ss', 'EPGScanTimeout':'si', 'SetSystemTime':'si', 'DiSEqC':'si', 'EmergencyExit':'si' } self.getSettings() self.debug("Plugin started") #self.setupdbus() # get VDR setup vars self.getVDRSettings() with open('/tmp/shutdownrequest','w') as f: f.write("0") # Check if Addon called by RunScript(script[,args]*) try: if sys.argv[1] == "check": self.debug("External Shutdown Request") self.xbmcNotify(message="Shutdown requested, probing VDR") oldstatus = self.xbmcStatus if xbmc.Player().isPlaying(): xbmc.Player().stop() self.xbmcStatus(0) idle, message = self.getVDRidle() if idle: self.xbmcNotify(message="Shutdown initiated") xbmc.sleep(2000) self.xbmcShutdown(1) xbmc.executebuiltin('Shutdown') exit() else: self.xbmcNotify(message=message) xbmc.sleep(2000) self.xbmcNotify(title="Auto shutdown activated", message="Will shutdown ASAP") with open('/tmp/shutdownrequest','w') as f: f.write("1") exit() elif sys.argv[1] == "quit": self.debug("Quit request") if xbmc.Player().isPlaying(): xbmc.Player().stop() xbmc.sleep(1000) xbmc.executebuiltin('Quit') exit() except: self.debug("no sys.arg[1] found - Addon was started by XBMC") self.updateXBMCSettings() self._manualStart = self.ask_vdrshutdown.ManualStart() self.debug("Manual Start: %s"%( self._manualStart)) while (not xbmc.abortRequested): if (self._manualStart == False and self.settings['MinEventTimeout'] > 0) or self._exitrequested == 1: self.debug("Mode: Timer start or exit requested") self._idleTime = 0 while not (self._isPlaying): self.debug("trying to shutdown XBMC") self.xbmcShutdown(1) self.xbmcStatus(0) self._lastIdleTime = self._idleTime self._idleTime = xbmc.getGlobalIdleTime() if self._idleTime <= self._lastIdleTime: break self.idleCheck(0) interval = self._sleep_interval self.debug(interval) xbmc.sleep(self._sleep_interval) self._exitrequested = 0 self.xbmcNotify(message="Autoshutdown aborted") with open('/tmp/shutdownrequest','w') as f: f.write("0") self.xbmcShutdown(0) self.xbmcStatus(1) # main loop+ while self._exitrequested == 0: self.getSettings() self.updateVDRSettings() if self.settings['MinUserInactivity'] > 0: # time warp calculations demands to have our own idle timers self._lastIdleTime = self._idleTime self.debug("lastIdleTime = %s"%self._lastIdleTime) self._idleTime = xbmc.getGlobalIdleTime() if (self._idleTime > self._lastIdleTime): self._realIdleTime = self._realIdleTime + (self._idleTime - self._lastIdleTime) else: self._realIdleTime = self._idleTime # notice changes in playback self._lastPlaying = self._isPlaying self._isPlaying = xbmc.Player().isPlaying() #print self._isPlaying #print self.settings['livetv_on'] if self._isPlaying and xbmc.Player().getPlayingFile().startswith("pvr://channels/") and self.settings['livetv_on']=="true": self.debug("ignoring Player activity for LiveTV") self._isPlaying = False #try: #if xbmc.Player().isPlaying(): # self.debug("Playing %s"%(xbmc.Player().getPlayingFile())) #except: # pass # now this one is tricky: a playback ended, idle would suggest to powersave, but we set the clock back for overrun. # Otherwise xbmc could sleep instantly at the end of a movie if (self._lastPlaying == True) & (self._isPlaying == False) & (self._realIdleTime >= self.settings['MinUserInactivity']): self._realIdleTime = self.settings['MinUserInactivity'] - self.settings['overrun'] self.debug("vdr.powersave: playback stopped!") # powersave checks ... if (self._realIdleTime + 60 >= self.settings['MinUserInactivity']) and self._isPlaying == False: self.xbmcStatus(0) idle, message = self.getVDRidle() if idle and int(self.settings['MinUserInactivity']) - int(self._realIdleTime) >= 0: self.xbmcNotify('Inactivity timeout in %s seconds'%(int(self.settings['MinUserInactivity']) - int(self._realIdleTime)),'press key to abort') if (self._realIdleTime >= self.settings['MinUserInactivity']): self.idleCheck(self.settings['MinUserInactivity']) xbmc.sleep(self._sleep_interval/2) else: xbmc.sleep(self._sleep_interval) with open('/tmp/shutdownrequest','r') as f: #print "EXITREQUESTED = %s"%(bool(f.read())) self._exitrequested = int(f.read()) else: xbmc.sleep(self._sleep_interval) self.debug("vdr.yavdrtools: Plugin exit on request") exit()
if shouldKeepAwake: sabIsActive = False req = urllib2.Request(sabNzbdQueue) try: handle = urllib2.urlopen(req) except IOError, e: xbmc.log('SABnzbd-Suite: could not determine SABnzbds status', level=xbmc.LOGERROR) else: queue = handle.read() handle.close() sabIsActive = (queue.find('<status>Downloading</status>') >= 0) # reset idle timer when we're close to idle sleep/shutdown if sabIsActive: response = xbmc.executehttpapi("GetGUISetting(0;powermanagement.shutdowntime)").replace('<li>','') shutdownTime = int(response) * 60 idleTime = xbmc.getGlobalIdleTime() timeToShutdown = shutdownTime - idleTime if (timeToShutdown <= checkInterval - timeout): xbmc.log('SABnzbd-Suite: still downloading. Resetting XBMC idle timer.') xbmc.executehttpapi("SendKey(0xF000)") # calculate and set the time to wake up at (if any) if wakePeriodically: wakeHour = wakeHourIdx * 2 + 1 timeOfDay = datetime.time(hour=wakeHour) now = datetime.datetime.now() wakeTime = now.combine(now.date(),timeOfDay) if now.time() > timeOfDay: wakeTime += datetime.timedelta(days=1) secondsSinceEpoch = time.mktime(wakeTime.timetuple())
def onScreensaverDeactivated(self): call_script({'event': EventNames.SCREENSAVER_DEACTIVATED}) def onDatabaseUpdated(self, db): call_script({'event': EventNames.DATABASE_UPDATED}) if __name__ == "__main__": Logger.notice('Script version {} started', __addonversion__) # make a player that will get called when media-related things happen playerEventReceiver = PlayerEventReceiver() monitor = MyMonitor() sent_idle = False # block here so the script stays active until XBMC shuts down while not xbmc.abortRequested: # watch for the idle time to cross the threshold and send the idle event when it does if xbmc.getGlobalIdleTime() > 60 * int(__addon__.getSetting("idle_time")): if not sent_idle: call_script({'event': EventNames.IDLE}) sent_idle = True else: if sent_idle: call_script({'event': EventNames.NOT_IDLE}) sent_idle = False xbmc.sleep(1000) Logger.notice('Script version {} stopped', __addonversion__)