Author: duncan
Date: Fri Nov  2 15:58:15 2007
New Revision: 10058

Log:
Implementation of kaa.rpc using callback functions
This looks like a clean implementation


Modified:
   branches/rel-1/freevo/src/tv/plugins/upsoon.py
   branches/rel-1/freevo/src/tv/record_client.py

Modified: branches/rel-1/freevo/src/tv/plugins/upsoon.py
==============================================================================
--- branches/rel-1/freevo/src/tv/plugins/upsoon.py      (original)
+++ branches/rel-1/freevo/src/tv/plugins/upsoon.py      Fri Nov  2 15:58:15 2007
@@ -72,7 +72,7 @@
         """
         init the upsoon plugin
         """
-        _debug_('__init__(self)', 2)
+        _debug_('PluginInterface.__init__()', 1)
         plugin.DaemonPlugin.__init__(self)
         plugin.register(self, 'upsoon')
         self.lock = thread.allocate_lock()
@@ -81,59 +81,40 @@
         self.event.register(('VIDEO_START', 'VIDEO_END'))
 
         self.recordclient = RecordClient()
-        #server_string = 'http://%s:%s/' % (config.RECORDSERVER_IP, 
config.RECORDSERVER_PORT)
-        #_debug_('%s' % server_string)
-        #self.server = xmlrpclib.Server(server_string, allow_none=1)
-        #_debug_('%s' % self.server)
-
-        #self.serverup = None
-        #self.next_program = self.findNextProgram()
-        #_debug_('%s' % (self.next_program))
-        self.next_program = None
 
         self.fc = FreevoChannels()
         self.rdev = config.RADIO_DEVICE
 
+        self.next_program = None
         self.seconds_before_announce = 120
         self.seconds_before_start = 60
         self.pending_lockfile = config.FREEVO_CACHEDIR + '/record.soon'
         self.tv_lockfile = None # lockfile of recordserver
-        self.stopped = False    # flag that tells upsoon stopped the tv, not 
the user
+        self.stopped = None     # flag that tells upsoon what stopped
 
 
     def findNextProgramHandler(self, result):
         """ Handles the result from the findNextProgram call """
+        _debug_('findNextProgramHandler(result=%r)' % (result), 1)
         self.next_program = result
 
-        now = time.time()
-
-        _debug_('now=%s next=%s ' % (time.strftime('%T', time.localtime(now)), 
self.next_program), 2)
-
         if self.next_program == None:
             return
 
-        self.vdev = self.getVideoForChannel(self.next_program.channel_id)
-
-        self.tv_lockfile = os.path.join(config.FREEVO_CACHEDIR, 
'record.'+vdev.split('/')[-1])
+        now = time.time()
+        _debug_('now=%s next=%s ' % (time.strftime('%T', time.localtime(now)), 
self.next_program), 2)
 
-        # Remove the pending record lock file when a record lock file is 
written
-        if os.path.exists(self.pending_lockfile):
-            if os.path.exists(self.tv_lockfile):
-                os.remove(self.pending_lockfile)
-                _debug_("record.soon lockfile removed")
-            return
+        self.vdev = self.getVideoForChannel(self.next_program.channel_id)
 
-        # Check if a recording is in progress
-        if os.path.exists(self.tv_lockfile):
-            return
+        self.tv_lockfile = os.path.join(config.FREEVO_CACHEDIR, 
'record.'+self.vdev.split('/')[-1])
 
-        secs_to_next = self.next_program.start - config.TV_RECORD_PADDING_PRE 
- int(now + 0.5)
-        _debug_('next recording in %s secs' % (secs_to_next), 2)
+        self.seconds_to_next = self.next_program.start - 
config.TV_RECORD_PADDING_PRE - int(now + 0.5)
+        _debug_('next recording in %s secs' % (self.seconds_to_next), 1)
 
         # announce 120 seconds before recording is due to start
         # stop the player 60 seconds before recording is due to start
 
-        if (secs_to_next > self.seconds_before_announce):
+        if (self.seconds_to_next > self.seconds_before_announce):
             return
 
         _debug_('stopping video or radio player')
@@ -144,74 +125,83 @@
 
     def getVideoForChannel(self, channel_id):
         """ get the video device given a channel id """
+        _debug_('getVideoForChannel(channel_id=%r)' % (channel_id), 1)
         return self.fc.getVideoGroup(channel_id, False).vdev
 
 
     def stopVideoInUse(self, vdev):
         """ stop the video device if being used """
+        _debug_('stopVideoInUse(vdev=%r)' % (vdev), 1)
         if vdev:
             try:
                 dev_fh = os.open(vdev, os.O_TRUNC)
                 try:
                     os.read(dev_fh, 1)
                 except:
-                    if (secs_to_next > self.seconds_before_start):
+                    if (self.seconds_to_next > self.seconds_before_start):
                         # just announce
                         rc.post_event(Event(OSD_MESSAGE, arg=_('A recording 
will start in a few minutes')))
                     else:
                         # stop the tv
                         rc.post_event(STOP)
-                        self.stopped = True
+                        self.stopped = _('Radio')
                         open(self.pending_lockfile, 'w').close()
                 os.close(dev_fh)
-            except:
+            except Exception, e:
+                print '%r: %s' % (vdev, e)
                 _debug_('cannot check video device \"%s\"' % (vdev), 0)
 
 
     def stopRadioInUse(self, rdev):
         """ stop the radio device if being used """
+        _debug_('stopRadioInUse(rdev=%r)' % (rdev), 1)
         if rdev:
             try:
                 dev_fh = os.open(rdev, os.O_TRUNC)
                 try:
                     os.read(dev_fh, 1)
                 except:
-                    if (secs_to_next > self.seconds_before_start):
+                    if (self.seconds_to_next > self.seconds_before_start):
                         rc.post_event(Event(OSD_MESSAGE, arg=_('A recording 
will start in a few minutes')))
                     else:
                         # stop the radio
                         rc.post_event(STOP)
-                        self.stopped = True
-                        # write lockfile, not sure if this is needed
+                        self.stopped = _('TV')
                         open(self.pending_lockfile, 'w').close()
                 os.close(dev_fh)
             except:
                 _debug_('cannot check radio device \"%s\"' % (rdev), 0)
 
-    def getPlayerRunning(self):
-        """
-        Return is a player is running
-        """
-        _debug_('getPlayerRunning(self)', 2)
-        return self.is_player_running
-
 
     def close(self):
         """
         to be called before the plugin exists.
         It terminates the connection with the server
         """
-        _debug_('close(self)')
+        _debug_('close()', 1)
 
 
     def timer_handler(self):
         """
         Sends a poll message to the record server
         """
-        _debug_('timer_handler()', 2)
+        _debug_('timer_handler()', 1)
 
-        self.recordclient.findNextProgram(self.findNextProgramHandler)
+        # Remove the pending record lock file when a record lock file is 
written
+        if self.tv_lockfile:
+            if os.path.exists(self.tv_lockfile):
+                if os.path.exists(self.pending_lockfile):
+                    os.remove(self.pending_lockfile)
+                    _debug_("record.soon lockfile removed")
+                return True
+            else:
+                self.tv_lockfile = None
 
+        # Check if a recording is about to start
+        if os.path.exists(self.pending_lockfile):
+            return True
+
+        self.recordclient.findNextProgram(self.findNextProgramHandler)
         return True
 
 
@@ -220,19 +210,20 @@
         Processes events, detect the video start and stop events so that the
         alert box will work correctly
         """
-        self.lock.acquire()
+        _debug_('event_handler(event=%r)' % (event), 1)
         try:
             _debug_('event_handler(%s) name=%s arg=%s context=%s handler=%s' % 
\
                 (event, event.name, event.arg, event.context, event.handler), 
2)
         finally:
-            self.lock.release()
+            pass
 
         if (event.name == 'VIDEO_START'):
-            self.stopped = False
+            self.stopped = None
         if (event.name == 'VIDEO_END'):
             if self.stopped:
                 # upsoon stopped the tv, now display a msgbox
-                AlertBox(text=_('TV stopped, a recording is about to start!'), 
height=200).show()
+                AlertBox(text=_('%s stopped, a recording is about to start!') 
% self.stopped, height=200).show()
+                self.stopped = None
         return 0
 
 
@@ -246,7 +237,6 @@
 
     if function == "run":
         pi = PluginInterface()
-        Timer(pi.timer_handler).start(15)
         kaa.main()
 
     elif function == "findnextprogram":

Modified: branches/rel-1/freevo/src/tv/record_client.py
==============================================================================
--- branches/rel-1/freevo/src/tv/record_client.py       (original)
+++ branches/rel-1/freevo/src/tv/record_client.py       Fri Nov  2 15:58:15 2007
@@ -52,55 +52,83 @@
     recordserver access class using kaa.rpc
     """
     def __init__(self):
+        """
+        """
+        _debug_('__init__()', 1)
         self.socket = (config.RECORDSERVER_IP, config.RECORDSERVER_PORT2)
         self.secret = config.RECORDSERVER_SECRET
-        try:
-            self.server = kaa.rpc.Client(self.socket, self.secret)
-        except kaa.rpc.ConnectError, e:
-            print e
-            raise
+        self.server = None
+
 
-    [EMAIL PROTECTED]()
     def recordserver_rpc(self, cmd, *args, **kwargs):
-        print 'RecordClient.recordserver_rpc(cmd=%r, args=%r, kwargs=%r)' % 
(cmd, args, kwargs)
+        """ call the record server command using kaa rpc """
+        _debug_('recordserver_rpc(cmd=%r, args=%r, kwargs=%r)' % (cmd, args, 
kwargs), 1)
         return self.server.rpc(cmd, *args, **kwargs)
 
     def getScheduledRecordings(self):
         """ get the scheduled recordings, returning an in process object """
-        print 'RecordClient.getScheduledRecordings()'
+        _debug_('getScheduledRecordings()', 1)
         inprogress = self.recordserver_rpc('getScheduledRecordings')
         print 'RecordClient.getScheduledRecordings.inprogress = %r' % 
(inprogress)
         return inprogress
 
-    # this redefined getScheduledRecordings
+
+    def server_rpc(self, cmd, callback, *args, **kwargs):
+        """
+        Call the server with the command the results will be put in the 
callback
+        Try to reconnect if the connection is down
+        """
+        _debug_('server_rpc(cmd=%r, callback=%r, args=%r, kwargs=%r)' % (cmd, 
callback, args, kwargs), 1)
+        try:
+            if self.server is None:
+                try:
+                    self.server = kaa.rpc.Client(self.socket, self.secret)
+                    _debug_('%r is up' % (self.socket,))
+                except kaa.rpc.ConnectError, e:
+                    _debug_('%r is down' % (self.socket,))
+                    self.server = None
+                    return False
+            self.server.rpc(cmd, *args, **kwargs).connect(callback)
+            return True
+        except kaa.rpc.ConnectError, e:
+            _debug_('%r is down' % (self.socket,))
+            self.server = None
+            return False
+
+
     def getScheduledRecordings(self, callback):
-        """ get the scheduled recordings, using a callback function """
-        print 'RecordClient.getScheduledRecordings(callback=%r)' % (callback)
-        res = self.server.rpc('getScheduledRecordings').connect(callback)
-        print 'RecordClient.getScheduledRecordings().res = %r' % (res)
-        return res
+        """ Get the scheduled recordings, using a callback function """
+        _debug_('getScheduledRecordings(callback=%r)' % (callback), 1)
+        return self.server_rpc('getScheduledRecordings', callback)
 
 
     def findNextProgram(self, callback):
-        """ find the next program using a callback function """
-        print 'RecordClient.findNextProgram(callback=%r)' % (callback)
-        self.server.rpc('findNextProgram').connect(callback)
+        """ Find the next program using a callback function """
+        _debug_('findNextProgram(callback=%r)' % (callback), 1)
+        return self.server_rpc('findNextProgram', callback)
 
 
     def isPlayerRunning(self, callback):
-        """ is a player running, using a callback function """
-        print 'RecordClient.isPlayerRunning(callback=%r)' % (callback)
-        self.server.rpc('isPlayerRunning').connect(callback)
+        """ Find out if a player is running, using a callback function """
+        _debug_('isPlayerRunning(callback=%r)' % (callback), 1)
+        return self.server_rpc('isPlayerRunning', callback)
         
 
 
+#
+# Deprecated Twisted calls
+#
 def returnFromJelly(status, response):
+    """ Unjelly the xml from the response """
+    _debug_('returnFromJelly(status=%r, response=%r)' % (status, response), 1)
     if status:
         return (status, unjellyFromXML(response))
     return (status, response)
 
 
 def getScheduledRecordings():
+    """ Using Twisted get the scheduled recordings """
+    _debug_('getScheduledRecordings()', 1)
     try:
         (status, message) = server.getScheduledRecordings()
     except Exception, e:
@@ -110,6 +138,8 @@
 
 
 def saveScheduledRecordings(scheduledRecordings):
+    """ Using Twisted save the scheduled recordings """
+    _debug_('saveScheduledRecordings(scheduledRecordings)', 1)
     try:
         (status, message) = server.saveScheduledRecordings(scheduledRecordings)
     except:
@@ -118,6 +148,8 @@
 
 
 def connectionTest(teststr='testing'):
+    """ Using Twisted check if the record server is running """
+    _debug_('connectionTest(teststr=%r)' % (teststr), 1)
     try:
         (status, message) = server.echotest(teststr)
     except Exception, e:
@@ -128,6 +160,8 @@
 
 
 def scheduleRecording(prog=None):
+    """ Using Twisted add a programme to recording schedule  """
+    _debug_('scheduleRecording(prog=%r)' % (prog), 1)
     if not prog:
         return (FALSE, _('no program'))
 
@@ -144,6 +178,8 @@
 
 
 def removeScheduledRecording(prog=None):
+    """ Using Twisted remove a programme from the recording schedule """
+    _debug_('removeScheduledRecording(prog=%r)' % (prog), 1)
     if not prog:
         return (FLASE, _('no program'))
 
@@ -155,6 +191,8 @@
 
 
 def cleanScheduledRecordings():
+    """ Using Twisted clean the recordings schedule """
+    _debug_('cleanScheduledRecordings()', 1)
     try:
         (status, message) = server.cleanScheduledRecordings()
     except:
@@ -163,6 +201,8 @@
 
 
 def isProgScheduled(prog, schedule=None):
+    """ Using Twisted find out if a programme is scheduled to record """
+    _debug_('isProgScheduled(prog=%r, schedule=%r)' % (prog, schedule), 1)
     if schedule or schedule == {}:
         if schedule == {}:
             return (FALSE, _('program not scheduled'))
@@ -182,6 +222,8 @@
 
 
 def findProg(chan, start):
+    """ Using Twisted find a program using the channel and the start time """
+    _debug_('findProg(chan=%r, start=%r)' % (chan, start), 1)
     try:
         (status, response) = server.findProg(chan, start)
     except:
@@ -190,6 +232,8 @@
 
 
 def findMatches(find='', movies_only=0):
+    """ Using Twisted find matching programmes """
+    _debug_('findMatches(find=%r, movies_only=%r)' % (find, movies_only), 1)
     try:
         (status, response) = server.findMatches(find, movies_only)
     except Exception, e:
@@ -199,6 +243,9 @@
 
 
 def addFavorite(name, prog, exactchan, exactdow, exacttod):
+    """ Using Twisted add a favourite programme """
+    _debug_('addFavorite(name=%r, prog=%r, exactchan=%r, exactdow=%r, 
exacttod=%r)' % \
+        (name, prog, exactchan, exactdow, exacttod), 1)
     try:
         (status, message) = server.addFavorite(name, prog, exactchan, 
exactdow, exacttod)
     except:
@@ -207,6 +254,9 @@
 
 
 def addEditedFavorite(name, title, chan, dow, mod, priority, allowDuplicates, 
onlyNew):
+    """ Using Twisted add an edited favourite programme """
+    _debug_('addEditedFavorite(name=%r, title=%r, chan=%r, dow=%r, mod=%r, 
priority=%r, allowDuplicates=%r, onlyNew=%r)' % \
+        (name, title, chan, dow, mod, priority, allowDuplicates, onlyNew), 1)
     try:
         (status, message) = \
             server.addEditedFavorite(jellyToXML(name), \
@@ -219,6 +269,8 @@
 
 
 def removeFavorite(name):
+    """ Using Twisted remove a favourite programme """
+    _debug_('removeFavorite(name=%r)' % (name), 1)
     try:
         (status, message) = server.removeFavorite(name)
     except:
@@ -227,6 +279,8 @@
 
 
 def clearFavorites():
+    """ Using Twisted clear favourites """
+    _debug_('clearFavorites()', 1)
     try:
         (status, message) = server.clearFavorites()
     except:
@@ -235,6 +289,8 @@
 
 
 def getFavorites():
+    """ Using Twisted get favourites """
+    _debug_('getFavorites()', 1)
     try:
         (status, response) = server.getFavorites()
     except:
@@ -243,6 +299,8 @@
 
 
 def getFavorite(name):
+    """ Using Twisted get a favourite """
+    _debug_('getFavorite(name=%r)' % (name), 1)
     try:
         (status, response) = server.getFavorite(name)
     except:
@@ -251,6 +309,8 @@
 
 
 def getFavoriteObject(prog, favs=None):
+    """ Using Twisted get a favourite object """
+    _debug_('getFavoriteObject(prog=%r, favs=%r)' % (prog, favs), 1)
     try:
         (status, response) = server.getFavoriteObject(jellyToXML(prog), 
jellyToXML(favs))
     except:
@@ -259,6 +319,8 @@
 
 
 def adjustPriority(favname, mod):
+    """ Using Twisted adjust the priority of a favourite programme """
+    _debug_('adjustPriority(favname=%r, mod=%r)' % (favname, mod), 1)
     try:
         (status, message) = server.adjustPriority(favname, mod)
     except:
@@ -267,6 +329,8 @@
 
 
 def isProgAFavorite(prog, favs=None):
+    """ Using Twisted find out if a programme is a favourite """
+    _debug_('isProgAFavorite(prog=%r, favs=%r)' % (prog, favs), 1)
     try:
         (status, message) = server.isProgAFavorite(jellyToXML(prog), 
jellyToXML(favs))
     except:
@@ -275,6 +339,8 @@
 
 
 def removeFavoriteFromSchedule(fav):
+    """ Using Twisted remove a favourite from the schedule """
+    _debug_('removeFavoriteFromSchedule(fav=%r)' % (fav), 1)
     try:
         (status, message) = server.removeFavoriteFromSchedule(fav)
     except:
@@ -283,6 +349,8 @@
 
 
 def addFavoriteToSchedule(fav):
+    """ Using Twisted add a favourite to the schedule """
+    _debug_('addFavoriteToSchedule(fav=%r)' % (fav), 1)
     try:
         (status, message) = server.addFavoriteToSchedule(fav)
     except:
@@ -291,6 +359,8 @@
 
 
 def updateFavoritesSchedule():
+    """ Using Twisted update the recoding schedule with the favourites """
+    _debug_('updateFavoritesSchedule()', 1)
     try:
         (status, message) = server.updateFavoritesSchedule()
     except:
@@ -301,6 +371,8 @@
 if __name__ == '__main__':
 
     def handler(result):
+        """ A callback handler for test functions """
+        _debug_('handler(result)=%r' % (result), 1)
         print 'result = %r' % (result)
         raise SystemExit
 
@@ -309,13 +381,13 @@
     kaa.main()
 
     if len(sys.argv) >= 2:
-        function = sys.argv[1]
+        function = sys.argv[1].lower()
     else:
         function = 'none'
 
     print 'xml_rpc_server at %r' % (xml_rpc_server)
 
-    if function == "updateFavoritesSchedule":
+    if function == "updatefavoritesschedule":
         (result, response) = updateFavoritesSchedule()
         print '%r' % response
 

-------------------------------------------------------------------------
This SF.net email is sponsored by: Splunk Inc.
Still grepping through log files to find problems?  Stop.
Now Search log events and configuration files using AJAX and a browser.
Download your FREE copy of Splunk now >> http://get.splunk.com/
_______________________________________________
Freevo-cvslog mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/freevo-cvslog

Reply via email to