Esempio n. 1
0
class ResourceReader:
    config=None

    def __init__(self):
        self.mon=Monitor()
        self.mon.on()
        
    def read(self,pp_dir,pp_home):
        if ResourceReader.config==None:
            tryfile=pp_home+os.sep+"resources.cfg"
            if os.path.exists(tryfile):
                 filename=tryfile
            else:
                self.mon.log(self,"Resources not found at "+ tryfile)
                tryfile=pp_dir+os.sep+'pp_home'+os.sep+"resources.cfg"
                if os.path.exists(tryfile):
                    filename=tryfile
                else:
                    self.mon.log(self,"Resources not found at "+ tryfile)
                    self.mon.err(self,"resources.cfg not found")
                    return False   
            ResourceReader.config = ConfigParser.ConfigParser()
            ResourceReader.config.read(filename)
            self.mon.log(self,"Read resources from "+ filename)
            return True

    def get(self,section,item):
        if ResourceReader.config.has_option(section,item)==False:
            return False
        else:
            return ResourceReader.config.get(section,item)
Esempio n. 2
0
    def __init__(self,widget,pp_dir):


        self.widget=widget
        self.pp_dir=pp_dir
        
        self.mon=Monitor()

        self.start_play_signal=False
        self.end_play_signal=False
        self.end_play_reason='nothing'
        self.duration=0
        self.video_position=0
        
        self.pause_at_end_required=False
        self.paused_at_end=False
        self.pause_at_end_time=0
        
        # self.pause_before_play_required='before-first-frame'  #no,before-first-frame, after-first-frame
        # self.pause_before_play_required='no'
        self.paused_at_start='False'

        self.paused=False      

        self.terminate_reason=''

        #  dbus and subprocess
        self._process=None
        self.__iface_root=None
        self.__iface_props = None
        self.__iface_player = None
Esempio n. 3
0
 def __init__(self,
                     canvas, 
                     cd,
                     track_params ):
     """       
         canvas - the canvas onto which the video is to be drawn (not!!)
         cd - configuration dictionary
         track_params - config dictionary for this track overides cd
     """
     self.mon=Monitor()
     self.mon.on()
     
     #instantiate arguments
     self.cd=cd       #configuration dictionary for the videoplayer
     self.canvas = canvas  #canvas onto which video should be played but isn't! Use as widget for alarm
     self.track_params=track_params
     
     # get config from medialist if there.
     if 'omx-audio' in self.track_params and self.track_params['omx-audio']<>"":
         self.omx_audio= self.track_params['omx-audio']
     else:
         self.omx_audio= self.cd['omx-audio']
     if self.omx_audio<>"": self.omx_audio= "-o "+ self.omx_audio
         
     # could put instance generation in play, not sure which is better.
     self.omx=OMXDriver()
     self._tick_timer=None
     self.error=False
     self.terminate_required=False
     self._init_play_state_machine()
Esempio n. 4
0
    def __init__(self,
                            show_params,
                            canvas,
                            showlist,
                            pp_home,
                            pp_profile):
        """ canvas - the canvas that the menu is to be written on
            show - the name of the configuration dictionary section for the menu
            showlist  - the showlist
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory"""
        
        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show_params=show_params
        self.showlist=showlist
        self.canvas=canvas
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()
        
        # init variables
        self.drawn  = None
        self.player=None
        self.shower=None
        self.menu_timeout_running=None
        self.error=False
Esempio n. 5
0
    def __init__(self,
                            show,
                            canvas,
                            showlist,
                            pp_home,
                            pp_profile):
        """ canvas - the canvas that the show is to be written on
            showlist - used jus to check the issue of medialist against showlist
            show - the dictionary for the show to be played
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory
        """

        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show =show
        self.showlist=showlist
        self.canvas=canvas
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()

        # Init variables
        self.player=None
        self.shower=None
        self._end_liveshow_signal=False
        self._play_child_signal = False
        self.error=False
        
        self._livelist=None
        self._new_livelist= None
Esempio n. 6
0
    def __init__(self,widget,pp_dir):

        self.widget=widget
        self.pp_dir=pp_dir
        
        self.mon=Monitor()

        self.start_play_signal=False
        self.end_play_signal=False
        self.end_play_reason='nothing'
        self.duration=0
        self.video_position=0
        
        self.pause_at_end_required=False
        self.paused_at_end=False
        
        self.pause_before_play_required=True
        self.paused_at_start=False

        self.paused=False      

        self.terminate_reason=''

        #  dbus and subprocess
        self._process=None
        self.__iface_root=None
        self.__iface_props = None
        self.__iface_player = None

        # legacy
        self.xbefore=''
        self.xafter=''
Esempio n. 7
0
    def __init__(self,canvas,cd,track_params):
        """
                canvas - the canvas onto which the image is to be drawn
                cd - configuration dictionary for the show from which player was called
        """

        self.mon=Monitor()
        self.mon.on()

        self.canvas=canvas
        self.cd=cd
        self.track_params=track_params
        
       # get config from medialist if there.
       
        if 'duration' in self.track_params and self.track_params['duration']<>"":
            self.duration= int(self.track_params['duration'])
        else:
            self.duration= int(self.cd['duration'])

        # keep dwell and porch as an integer multiple of tick          
        self.tick = 100 # tick time for image display (milliseconds)
        self.dwell = (1000*self.duration)

        self.centre_x = int(self.canvas['width'])/2
        self.centre_y = int(self.canvas['height'])/2
Esempio n. 8
0
    def __init__(self, widget):

        self.widget = widget

        self.mon = Monitor()
        self.mon.on()
        self._process = None
        self.fifo = ""
Esempio n. 9
0
    def __init__(self, widget):

        self.widget = widget

        self.mon = Monitor()
        self.mon.off()
        self._process = None
        self.paused = None
Esempio n. 10
0
    def __init__(self,widget):

        self.widget=widget
        
        self.mon=Monitor()
        self.mon.on()
        
        self.paused=None
    def __init__(self,widget,pp_dir):

        self.widget=widget
        self.pp_dir=pp_dir
        
        self.mon=Monitor()
        
        self._process=None
        self.paused=False
Esempio n. 12
0
    def  init(self,pp_profile,show_command_callback,input_event_callback,output_event_callback):

        self.pp_profile=pp_profile
        self.show_command_callback=show_command_callback
        self.input_event_callback=input_event_callback
        self.output_event_callback=output_event_callback

        self.mon=Monitor()
        config_file=self.pp_profile + os.sep +'pp_io_config'+os.sep+ 'osc.cfg'
        if not os.path.exists(config_file):
            self.mon.err(self, 'OSC Configuration file nof found: '+config_file)
            return'error','OSC Configuration file nof found: '+config_file
        
        self.mon.log(self, 'OSC Configuration file found at: '+config_file)        
        self.options=OSCConfig()
        # only reads the  data for required unit_type 
        if self.options.read(config_file) ==False:
            return 'error','failed to read osc.cfg'

        self.prefix='/pipresents'
        self.this_unit='/' + self.options.this_unit_name
        self.this_unit_type = self.options.this_unit_type

        self.reply_client=None
        self.command_client=None
        self.client=None
        self.server=None

        if self.this_unit_type not in ('master','slave','master+slave'):
            return 'error','this unit type not known: '+self.this_unit_type

        if self.this_unit_type in('slave','master+slave'):
            #start the client that sends replies to controlling unit
            self.reply_client=OSC.OSCClient()
            self.mon.log(self, 'sending replies to controller at: '+self.options.controlled_by_ip+':'+self.options.controlled_by_port)
            self.reply_client.connect((self.options.controlled_by_ip,int(self.options.controlled_by_port)))
            self.mon.log(self,'sending repiles to: '+ str(self.reply_client))
            self.client=self.reply_client
            
        if self.this_unit_type in ('master','master+slave'):
            #start the client that sends commands to the controlled unit
            self.command_client=OSC.OSCClient()
            self.command_client.connect((self.options.controlled_unit_1_ip,int(self.options.controlled_unit_1_port)))
            self.mon.log(self, 'sending commands to controled unit at: '+self.options.controlled_unit_1_ip+':'+self.options.controlled_unit_1_port)
            self.mon.log(self,'sending commands to: '+str(self.command_client))
            self.client=self.command_client

        #start the listener's server
        self.mon.log(self, 'listen to commands from controlled by unit and replies from controlled units on: ' + self.options.this_unit_ip+':'+self.options.this_unit_port)
        self.server=myOSCServer((self.options.this_unit_ip,int(self.options.this_unit_port)),self.client)
        # return_port=int(self.options.controlled_by_port)
        self.mon.log(self,'listening on: '+str(self.server))
        self.add_initial_handlers()
        return 'normal','osc.cfg read'
Esempio n. 13
0
    def __init__(self,show_id,showlist,show_params,root,canvas,pp_dir,pp_profile,pp_home):
        self.showlist=showlist
        self.show_params=show_params
        self.root=root
        self.canvas=canvas
        self.pp_dir=pp_dir
        self.pp_profile=pp_profile
        self.pp_home=pp_home
        self.show_id=show_id

        self.mon=Monitor()
        self.mon.on()
Esempio n. 14
0
    def __init__(self,
                            show_params,
                             root,
                            canvas,
                            showlist,
                            pp_dir,
                            pp_home,
                            pp_profile):
        """ canvas - the canvas that the menu is to be written on
            show - the dictionary fo the show to be played
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory
        """

        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show_params =show_params
        self.showlist=showlist
        self.root=root
        self.canvas=canvas
        self.pp_dir=pp_dir
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()

        # Init variables
        self.player=None
        self.shower=None
        self.poll_for_interval_timer=None
        self.poll_for_continue_timer=None
        self.waiting_for_interval=False
        self.interval_timer=None
        self.duration_timer=None
        self.error=False
        
        self.interval_timer_signal=False
        self.end_trigger_signal=False
        self.end_mediashow_signal=False
        self.next_track_signal=False
        self.previous_track_signal=False
        self.play_child_signal = False
        self.req_next='nil'

        #create and instance of TimeOfDay scheduler so we can add events
        self.tod=TimeOfDay()

        self.state='closed'
Esempio n. 15
0
    def __init__(self,show_id,root,canvas,show_params,track_params,pp_dir,pp_home,pp_profile):

        self.mon=Monitor()
        self.mon.on()

        self.root=root
        self.canvas=canvas
        self.show_id=show_id
        self.track_params=track_params
        self.show_params=show_params
        self.pp_dir=pp_dir
        self.pp_home=pp_home
        self.pp_profile=pp_profile

       # get config from medialist if there.
       
        if 'duration' in self.track_params and self.track_params['duration']<>"":
            self.duration= int(self.track_params['duration'])
        else:
            self.duration= int(self.show_params['duration'])

        # get background image from profile.
        self.background_file=''
        if self.track_params['background-image']<>"":
            self.background_file= self.track_params['background-image']
        else:
            if self.track_params['display-show-background']=='yes':
                self.background_file= self.show_params['background-image']
            
        # get background colour from profile.
        if self.track_params['background-colour']<>"":
            self.background_colour= self.track_params['background-colour']
        else:
            self.background_colour= self.show_params['background-colour']
            
        self.centre_x = int(self.canvas['width'])/2
        self.centre_y = int(self.canvas['height'])/2
        
        # keep tick as an integer sub-multiple of 1 second         
        self.tick = 100 # tick time for image display (milliseconds)
        self.dwell = 1000*self.duration

        #get animation instructions from profile
        self.animate_begin_text=self.track_params['animate-begin']
        self.animate_end_text=self.track_params['animate-end']

        # open the plugin Manager
        self.pim=PluginManager(self.show_id,self.root,self.canvas,self.show_params,self.track_params,self.pp_dir,self.pp_home,self.pp_profile) 

        #create an instance of PPIO so we can create gpio events
        self.ppio = PPIO() 
    def __init__(self,widget):

        self.widget=widget
        
        self.mon=Monitor()
        self.mon.on()
        
        self.paused=None
        #NIK
        # for pausing video while moving back and forth through slideshow
        self.delayed_pause = False
        #NIK

        self._process=None
Esempio n. 17
0
    def __init__(self, parent, title, tp, track_types, field_specs, show_refs):
        self.mon = Monitor()
        self.mon.on()
        # save the extra arg to instance variable
        self.tp = tp  # dictionary - the track parameters to be edited
        self.track_types = track_types
        self.field_specs = field_specs
        self.show_refs = show_refs
        self.show_refs.append("")
        # list of stringvars from which to get edited values
        self.entries = []

        # and call the base class _init_which calls body immeadiately and apply on OK pressed
        tkSimpleDialog.Dialog.__init__(self, parent, title)
Esempio n. 18
0
    def __init__(self):
    
        # get command options
        self.command_options=remote_options()

        # get directory holding the code
        self.pp_dir=sys.path[0]
            
        if not os.path.exists(self.pp_dir+os.sep+"pipresents.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()
            
          
        # Initialise logging
        Monitor.log_path=self.pp_dir
        self.mon=Monitor()
        self.mon.init()
        
        Monitor.classes  = ['OSCMonitor','OSCConfig','OSCEditor']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log (self, "Pi Presents Monitor is starting")
        self.mon.log (self," OS and separator " + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: code "+sys.path[0])

        self.root = Tk()

        # initialise OSC config class
        self.osc_config=OSCConfig()

        # read the options and allow their editing
        self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscmonitor.cfg'
        self.read_create_osc()

        if self.osc_config.slave_enabled !='yes':
            self.mon.err(self,'OSC Slave is not enabled in pp_oscmonitor.cfg')
            exit()
            
        #build gui
        self.setup_gui()

        # initialise
        self.init()

        #and start the system
        self.root.after(1000,self.run_app)
        self.root.mainloop()
Esempio n. 19
0
    def __init__(self):
    
        self.editor_issue="1.3"

        # get command options
        self.command_options=remote_options()

        # get directory holding the code
        self.pp_dir=sys.path[0]
            
        if not os.path.exists(self.pp_dir+os.sep+"pp_oscremote.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()
            
          
        # Initialise logging
        Monitor.log_path=self.pp_dir
        self.mon=Monitor()
        self.mon.init()
        
        Monitor.classes  = ['OSCRemote','OSCConfig','OSCEditor']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log (self, "Pi Presents Remote is starting")
        self.mon.log (self," OS and separator " + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: code "+sys.path[0])

        self.root = Tk()

        # OSC config class
        self.osc_config=OSCConfig()
        self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscremote.cfg'
        self.read_create_osc()

        self.setup_gui()

        if self.osc_config.this_unit_ip =='':
            self.mon.err(self,'IP of own unit must be provided in oscremote.cfg')

      
        self.init()


        #and start the system
        self.root.after(1000,self.run_app)
        self.root.mainloop()
    def __init__(self,
                         show_id,
                        canvas,
                        pp_home,
                        show_params,
                        track_params ):
        """       
            canvas - the canvas onto which the video is to be drawn (not!!)
            cd - configuration dictionary
            track_params - config dictionary for this track overides cd
        """
        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show_id=show_id
        self.show_params=show_params       #configuration dictionary for the videoplayer
        self.pp_home=pp_home
        self.canvas = canvas  #canvas onto which video should be played but isn't! Use as widget for alarm
        self.track_params=track_params
        
        # get config from medialist if there.
        if self.track_params['omx-audio']<>"":
            self.omx_audio= self.track_params['omx-audio']
        else:
            self.omx_audio= self.show_params['omx-audio']
        if self.omx_audio<>"": self.omx_audio= "-o "+ self.omx_audio
        
        if self.track_params['omx-volume']<>"":
            self.omx_volume= self.track_params['omx-volume']
        else:
            self.omx_volume= self.show_params['omx-volume']
        if self.omx_volume<>"": self.omx_volume= "--vol "+ str(int(self.omx_volume)*100) + ' '
        self.omx_volume=' '
        #get animation instructions from profile
        self.animate_begin_text=self.track_params['animate-begin']
        self.animate_end_text=self.track_params['animate-end']

        #create an instance of PPIO so we can create gpio events
        self.ppio = PPIO()        
        
        # could put instance generation in play, not sure which is better.
        self.omx=OMXDriver(self.canvas)
        self._tick_timer=None
        self.error=False
        self.terminate_required=False
        self._init_play_state_machine()
Esempio n. 21
0
    def __init__(self,widget,pp_dir):

        self.widget=widget
        self.pp_dir=pp_dir
        
        self.mon=Monitor()

        self.paused=False

        self._process=None
        
        # PRELOAD add some initilisation to cope with first iteration of preload state machine
        self.start_play_signal=False
        self.end_play_signal=True
        self.end_play_reason='nice_day'
        self.video_position=0
        self.freeze_at_end_required=False
    def __init__(self,show_id,canvas,pp_home,show_params,track_params):
        """
                canvas - the canvas onto which the image is to be drawn
                cd -  dictionary of show parameters
                track_params - disctionary of track paramters
        """

        self.mon=Monitor()
        self.mon.on()

        self.show_id=show_id
        self.canvas=canvas
        self.pp_home=pp_home
        self.show_params=show_params
        self.track_params=track_params

        # open resources
        self.rr=ResourceReader()

            
        # get config from medialist if there.
        
        self.animate_begin_text=self.track_params['animate-begin']
        self.animate_end_text=self.track_params['animate-end']
        
        if 'duration' in self.track_params and self.track_params['duration']<>"":
            self.duration= int(self.track_params['duration'])
        else:
            self.duration= int(self.show_params['duration'])
            
        if 'transition' in self.track_params and self.track_params['transition']<>"":
            self.transition= self.track_params['transition']
        else:
            self.transition= self.show_params['transition']
  
        # keep dwell and porch as an integer multiple of tick          
        self.porch = 1000 #length of pre and post porches for an image (milliseconds)
        self.tick = 100 # tick time for image display (milliseconds)
        self.dwell = (1000*self.duration)- (2*self.porch)
        if self.dwell<0: self.dwell=0

        self.centre_x = int(self.canvas['width'])/2
        self.centre_y = int(self.canvas['height'])/2

        #create an instance of PPIO so we can create gpio events
        self.ppio = PPIO()
Esempio n. 23
0
    def __init__(self, parent, title, field_content, record_specs,field_specs,show_refs,initial_media_dir,pp_home_dir,initial_tab):
        self.mon=Monitor()
        # save the extra arg to instance variable
        self.field_content = field_content   # dictionary - the track parameters to be edited
        self.record_specs= record_specs # list of field names and seps/tabs in the order that they appear
        self.field_specs=field_specs  # dictionary of specs referenced by field name
        
        self.show_refs=show_refs
        self.show_refs.append('')
        self.initial_media_dir=initial_media_dir
        self.pp_home_dir=pp_home_dir
        self.initial_tab=initial_tab
        
        # list of stringvars from which to get edited values (for optionmenu only??)
        self.entries=[]

        # and call the base class _init_which calls body immeadiately and apply on OK pressed
        tkSimpleDialog.Dialog.__init__(self, parent, title)
Esempio n. 24
0
class ResourceReader:
    config=None

    def __init__(self):
        self.mon=Monitor()
        self.mon.on()

    def read(self,pp_dir,pp_home,pp_profile):
        if ResourceReader.config==None:
            # try inside profile
            tryfile=pp_profile+os.sep+"resources.cfg"
            # self.mon.log(self,"Trying resources.cfg in profile at: "+ tryfile)
            if os.path.exists(tryfile):
                 filename=tryfile
            else:
                # try inside pp_home
                # self.mon.log(self,"resources.cfg not found at "+ tryfile+ " trying pp_home")
                tryfile=pp_home+os.sep+"resources.cfg"
                if os.path.exists(tryfile):
                    filename=tryfile
                else:
                    # try inside pipresents
                    # self.mon.log(self,"resources.cfg not found at "+ tryfile + " trying inside pipresents")
                    tryfile=pp_dir+os.sep+'pp_home'+os.sep+"resources.cfg"
                    if os.path.exists(tryfile):
                        filename=tryfile
                    else:
                        self.mon.log(self,"resources.cfg not found at "+ tryfile)
                        self.mon.err(self,"resources.cfg not found")
                        return False   
            ResourceReader.config = ConfigParser.ConfigParser()
            ResourceReader.config.read(filename)
            self.mon.log(self,"resources.cfg read from "+ filename)
            return True
        

    def get(self,section,item):
        if ResourceReader.config.has_option(section,item)==False:
            return False
        else:
            return ResourceReader.config.get(section,item)
Esempio n. 25
0
    def __init__(self,
                            show_params,
                            root,
                            canvas,
                            showlist,
                             pp_dir,
                            pp_home,
                            pp_profile):
        """ canvas - the canvas that the tracks of the event show are to be written on
            show_params - the name of the configuration dictionary section for the hyperlinkshow
            showlist  - the showlist, to enable runningnof show type tracks.
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory
        """
        
        self.mon=Monitor()
        self.mon.on()

        self.debug=False
        # remove # to enable debugging trace
        #self.debug=True
        
        #instantiate arguments
        self.show_params=show_params
        self.root=root
        self.showlist=showlist
        self.canvas=canvas
        self.pp_dir=pp_dir
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()

        #create a path stack
        self.path = PathManager()
        
        # init variables
        self.drawn  = None
        self.player=None
        self.shower=None
        self.timeout_running=None
        self.error=False
Esempio n. 26
0
    def __init__(self,
                            show,
                            canvas,
                            showlist,
                            pp_home,
                            pp_profile):
        """ canvas - the canvas that the menu is to be written on
            show - the dictionary fo the show to be played
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory
        """

        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show =show
        self.showlist=showlist
        self.canvas=canvas
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()

        # Init variables
        self.player=None
        self.shower=None
        self._poll_for_interval_timer=None
        self._poll_for_continue_timer=None
        self._waiting_for_interval=False
        self._interval_timer=None
        self.error=False
        
        self._interval_timer_signal=False
        self._end_mediashow_signal=False
        self._next_track_signal=False
        self._previous_track_signal=False
        self._play_child_signal = False
        self._req_next='nil'

        self._state='closed'
class ResourceReader(object):
    config = None

    def __init__(self):
        self.mon = Monitor()
        self.mon.on()

    def read(self, pp_dir, pp_home, pp_profile):
        """
        looks for resources.cfg in the profile, then in pp_home, then in the pi_presents directory.
        returns True if it finds the resources.cfg, otherwise returns False

        ::param pp_dir: the PiPresents directory
        ::param pp_home: the current pp_home directory
        ::param pp_profile: the current profile directory
        """
        if not ResourceReader.config:
            profile_config = os.path.join(pp_profile, "resources.cfg")
            home_config = os.path.join(pp_home, "resources.cfg")
            pp_config = os.path.join(pp_dir, 'pp_home', "resources.cfg")

            # try inside profile
            if os.path.exists(profile_config):
                config_path = profile_config

            # try inside pp_home
            elif os.path.exists(home_config):
                config_path = home_config

            # try in the pi presents directory
            elif os.path.exists(pp_config):
                config_path = pp_config

            else:
                # throw an error if we can't find any config files
                self.mon.err(self, "resources.cfg not found at {0}, {1} or {2}".format(profile_config, home_config, pp_config))
                return False

            ResourceReader.config = ConfigParser.ConfigParser()
            ResourceReader.config.read(config_path)
            self.mon.log(self, "resources.cfg read from " + config_path)
            return True

    def get(self, section, item):
        if not ResourceReader.config.has_option(section, item):
            return False
        else:
            return ResourceReader.config.get(section, item)
Esempio n. 28
0
    def __init__(self,
                            show_params,
                             root,
                            canvas,
                            showlist,
                             pp_dir,
                            pp_home,
                            pp_profile):

        self.mon=Monitor()
        self.mon.on()
        
        #instantiate arguments
        self.show_params =show_params
        self.showlist=showlist
        self.root=root
        self.canvas=canvas
        self.pp_dir=pp_dir
        self.pp_home=pp_home
        self.pp_profile=pp_profile

        # open resources
        self.rr=ResourceReader()

        #create and instance of TimeOfDay scheduler so we can add events
        self.tod=TimeOfDay()


        # Init variables
        self.player=None
        self.shower=None
        self.end_liveshow_signal=False
        self.end_trigger_signal= False
        self.play_child_signal = False
        self.error=False
        self.egg_timer=None
        self.duration_timer=None
        self.state='closed'
        self.livelist=None
        self.new_livelist= None
Esempio n. 29
0
    def __init__(self, tkparent, title, objtype, field_content, show_refs):
        self.mon = Monitor()

        if objtype == SHOW:
            self.record_specs = PPdefinitions.show_types
            self.field_specs = PPdefinitions.show_field_specs
            self.initial_tab = "show"
        elif objtype == TRACK:
            self.record_specs = PPdefinitions.track_types
            self.field_specs = PPdefinitions.track_field_specs
            self.initial_tab = "track"

        # save the extra arg to instance variable
        self.objtype = objtype
        self.field_content = field_content  # dictionary - the track parameters to be edited
        self.show_refs = show_refs
        self.show_refs.append("")
        self.initial_media_dir = pp_paths.media_dir
        self.pp_home_dir = pp_paths.pp_home

        # list of stringvars from which to get edited values (for optionmenu only??)
        self.entries = []

        # lookup for widget when all we have is the field
        self.widgets = {}

        self.validator = Validator()
        self.validator.initialize(scope=objtype)
        if objtype == SHOW:
            self.mon.log(self, "Editing show '{0} -------------------".format(Validator.get_showref))
            self.validator.set_current(show=field_content)
        elif objtype == TRACK:
            self.mon.log(self, "Editing track '{0} -------------------".format(Validator.get_trackref))
            self.validator.set_current(track=field_content)
        self.tempcontent = copy.deepcopy(self.field_content)

        # and call the base class _init_which calls body immeadiately and apply on OK pressed
        ttkSimpleDialog.Dialog.__init__(self, tkparent, title)
Esempio n. 30
0
    def __init__(self):
    
        self.editor_issue="1.3"

        # get command options
        self.command_options=remote_options()

        # get directory holding the code
        self.pp_dir=sys.path[0]
            
        if not os.path.exists(self.pp_dir+os.sep+"pipresents.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()
            
          
        # Initialise logging
        Monitor.log_path=self.pp_dir
        self.mon=Monitor()
        self.mon.init()
        
        Monitor.classes  = ['OSCMonitor','OSCConfig','OSCEditor']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log (self, "Pi Presents Monitor is starting")
        self.mon.log (self," OS and separator " + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: code "+sys.path[0])

        self.setup_gui()

        # initialise OSC config class
        self.osc_config=OSCConfig()

        self.init()

        #and start the system
        self.root.after(1000,self.run_app)
        self.root.mainloop()
Esempio n. 31
0
class OSCMonitor(object):
    def __init__(self):

        self.editor_issue = "1.3"

        # get command options
        self.command_options = remote_options()

        # get directory holding the code
        self.pp_dir = sys.path[0]

        if not os.path.exists(self.pp_dir + os.sep + "pipresents.py"):
            tkMessageBox.showwarning("Pi Presents",
                                     "Bad Application Directory")
            exit()

        # Initialise logging
        Monitor.log_path = self.pp_dir
        self.mon = Monitor()
        self.mon.init()

        Monitor.classes = ['OSCMonitor', 'OSCConfig', 'OSCEditor']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log(self, "Pi Presents Monitor is starting")
        self.mon.log(self, " OS and separator " + os.name + '  ' + os.sep)
        self.mon.log(self,
                     "sys.path[0] -  location of code: code " + sys.path[0])

        self.setup_gui()

        # initialise OSC config class
        self.osc_config = OSCConfig()

        self.init()

        #and start the system
        self.root.after(1000, self.run_app)
        self.root.mainloop()

    def init(self):
        # read the options and allow their editing
        self.osc_config_file = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_oscmonitor.cfg'
        self.read_create_osc()

    def add_status(self, text):
        self.status_display.insert(END, text + '\n')
        self.status_display.see(END)

    def run_app(self):
        self.client = None
        self.server = None
        self.st = None

        # initialise OSC variables
        self.prefix = '/pipresents'
        self.this_unit = '/' + self.osc_config.this_unit_name
        self.add_status('this unit is: ' + self.this_unit)
        self.controlled_by_unit = '/' + self.osc_config.controlled_by_name
        self.add_status('controlled by unit : ' + self.controlled_by_unit)

        #connect client for replies then start server to listen for commands
        self.client = OSC.OSCClient()
        self.add_status('connecting to controlled by unit: ' +
                        self.osc_config.controlled_by_ip + ':' +
                        self.osc_config.controlled_by_port + ' ' +
                        self.osc_config.controlled_by_name)
        self.client.connect((self.osc_config.controlled_by_ip,
                             int(self.osc_config.controlled_by_port)))
        self.add_status('listening for commands on:' +
                        self.osc_config.this_unit_ip + ':' +
                        self.osc_config.this_unit_port)
        self.init_server(self.osc_config.this_unit_ip,
                         self.osc_config.this_unit_port, self.client)
        self.add_initial_handlers()
        self.start_server()

    # ***************************************
    # OSC CLIENT TO SEND REPLIES
    # ***************************************

    def disconnect_client(self):
        if self.client != None:
            self.client.close()
        return

    # ***************************************
    # OSC SERVER TO LISTEN TO COMMANDS
    # ***************************************

    def init_server(self, ip, port_text, client):
        self.add_status('Init Server: ' + ip + ':' + port_text)
        self.server = myOSCServer((ip, int(port_text)), client)

    def start_server(self):
        self.add_status('Start Server')
        self.st = threading.Thread(target=self.server.serve_forever)
        self.st.start()

    def close_server(self):
        if self.server != None:
            self.server.close()
        self.mon.log(self, 'Waiting for Server-thread to finish')
        if self.st != None:
            self.st.join()  ##!!!
        self.mon.log(self, 'server thread closed')

    def add_initial_handlers(self):
        pass
        self.server.addMsgHandler('default', self.no_match_handler)
        self.server.addMsgHandler(
            self.prefix + self.this_unit + "/system/server-info",
            self.server_info_handler)
        self.server.addMsgHandler(
            self.prefix + self.this_unit + "/system/loopback",
            self.loopback_handler)

    def no_match_handler(self, addr, tags, stuff, source):
        text = "Message from %s" % OSC.getUrlStr(source) + '\n'
        text += "     %s" % addr + self.pretty_list(stuff)
        self.add_status(text + '\n')

    def server_info_handler(self, addr, tags, stuff, source):
        msg = OSC.OSCMessage(self.prefix + self.controlled_by_unit +
                             '/system/server-info-reply')
        msg.append('Unit: ' + self.osc_config.this_unit_name)
        self.add_status('Server Info Request from %s:' % OSC.getUrlStr(source))
        return msg

    def loopback_handler(self, addr, tags, stuff, source):
        # send a reply to the client.
        msg = OSC.OSCMessage(self.prefix + self.controlled_by_unit +
                             '/system/loopback-reply')
        self.add_status('Loopback Request from %s:' % OSC.getUrlStr(source))
        return msg

    def pretty_list(self, fields):
        text = ' '
        for field in fields:
            text += str(field) + ' '
        return text

    # ***************************************
    # INIT EXIT MISC
    # ***************************************

    def e_edit_osc(self):
        self.disconnect_client()
        self.close_server()
        self.edit_osc()
        self.init()
        self.add_status('\n\n\nRESTART')
        self.run_app()

    def app_exit(self):
        self.disconnect_client()
        self.close_server()
        if self.root is not None:
            self.root.destroy()
        self.mon.finish()
        sys.exit()

    def show_help(self):
        tkMessageBox.showinfo("Help", "Read 'manual.pdf'")

    def about(self):
        tkMessageBox.showinfo(
            "About", "Simple Remote Monitor for Pi Presents\n" +
            "Author: Ken Thompson" +
            "\nWebsite: http://pipresents.wordpress.com/")

    def setup_gui(self):
        # set up the gui

        # root is the Tkinter root widget
        self.root = Tk()
        self.root.title("Remote Monitor for Pi Presents")

        # self.root.configure(background='grey')

        self.root.resizable(False, False)

        # define response to main window closing
        self.root.protocol("WM_DELETE_WINDOW", self.app_exit)

        # bind some display fields
        self.filename = StringVar()
        self.display_show = StringVar()
        self.results = StringVar()
        self.status = StringVar()

        # define menu
        menubar = Menu(self.root)

        toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Tools', menu=toolsmenu)

        osc_configmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Options', menu=osc_configmenu)
        osc_configmenu.add_command(label='Edit', command=self.e_edit_osc)

        helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Help', menu=helpmenu)
        helpmenu.add_command(label='Help', command=self.show_help)
        helpmenu.add_command(label='About', command=self.about)

        self.root.config(menu=menubar)

        # status_frame
        status_frame = Frame(self.root, padx=5, pady=5)
        status_frame.pack(side=TOP, fill=BOTH, expand=1)
        status_label = Label(status_frame, text="Status", font="arial 12 bold")
        status_label.pack(side=LEFT)
        scrollbar = Scrollbar(status_frame, orient=VERTICAL)
        self.status_display = Text(status_frame,
                                   height=10,
                                   yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.status_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.status_display.pack(side=LEFT, fill=BOTH, expand=1)


# ***************************************
#  OSC CONFIGURATION
# ***************************************

    def read_create_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            self.osc_config.create(self.osc_config_file)
            eosc = OSCEditor(self.root, self.osc_config_file, 'slave',
                             'Create OSC Monitor Configuration')
            self.osc_config.read(self.osc_config_file)

    def edit_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            self.osc_config.create(self.osc_config_file)
        eosc = OSCEditor(self.root, self.osc_config_file, 'slave',
                         'Edit OSC Monitor Configuration')
Esempio n. 32
0
class GPIODriver(object):
    """
    GPIODriver provides GPIO facilties for Pi presents
     - configures and binds GPIO pins from data in gpio.cfg
     - reads and debounces inputs pins, provides callbacks on state changes which generate input events
    - changes the stae of output pins as required by calling programs
    """

    # constants for buttons

    # cofiguration from gpio.cfg
    PIN = 0  # pin on RPi board GPIO connector e.g. P1-11
    DIRECTION = 1  # IN/OUT/NONE (None is not used)
    NAME = 2  # symbolic name for output
    RISING_NAME = 3  # symbolic name for rising edge callback
    FALLING_NAME = 4  # symbolic name of falling edge callback
    ONE_NAME = 5  # symbolic name for one state callback
    ZERO_NAME = 6  # symbolic name for zero state callback
    REPEAT = 7  # repeat interval for state callbacks (mS)
    THRESHOLD = 8  # threshold of debounce count for state change to be considered
    PULL = 9  # pull up or down or none

    # dynamic data
    COUNT = 10  # variable - count of the number of times the input has been 0 (limited to threshold)
    PRESSED = 11  # variable - debounced state
    LAST = 12  # varible - last state - used to detect edge
    REPEAT_COUNT = 13

    TEMPLATE = [
        '',  # pin
        '',  # direction
        '',  # name
        '',
        '',
        '',
        '',  #input names
        0,  # repeat
        0,  # threshold
        '',  #pull
        0,
        False,
        False,
        0
    ]  #dynamics

    # for A and B
    #    PINLIST = ('P1-03','P1-05','P1-07','P1-08',
    #               'P1-10','P1-11','P1-12','P1-13','P1-15','P1-16','P1-18','P1-19',
    #               'P1-21','P1-22','P1-23','P1-24','P1-26')

    # for A+ and B+ seems to work for A and B
    PINLIST = ('P1-03', 'P1-05', 'P1-07', 'P1-08', 'P1-10', 'P1-11', 'P1-12',
               'P1-13', 'P1-15', 'P1-16', 'P1-18', 'P1-19', 'P1-21', 'P1-22',
               'P1-23', 'P1-24', 'P1-26', 'P1-29', 'P1-31', 'P1-32', 'P1-33',
               'P1-35', 'P1-36', 'P1-37', 'P1-38', 'P1-40')

    # CLASS VARIABLES  (GPIODriver.)
    shutdown_index = 0  #index of shutdown pin
    pins = []
    options = None
    gpio_enabled = False

    # executed by main program and by each object using gpio
    def __init__(self):
        self.mon = Monitor()

    # executed once from main program
    def init(self,
             pp_dir,
             pp_home,
             pp_profile,
             widget,
             button_tick,
             button_callback=None):

        # instantiate arguments
        self.widget = widget
        self.pp_dir = pp_dir
        self.pp_profile = pp_profile
        self.pp_home = pp_home
        self.button_tick = button_tick
        self.button_callback = button_callback

        GPIODriver.shutdown_index = 0

        # read gpio.cfg file.
        reason, message = self.read(self.pp_dir, self.pp_home, self.pp_profile)
        if reason == 'error':
            return 'error', message

        import RPi.GPIO as GPIO
        self.GPIO = GPIO

        # construct the GPIO control list from the configuration
        for index, pin_def in enumerate(GPIODriver.PINLIST):
            pin = copy.deepcopy(GPIODriver.TEMPLATE)
            pin_bits = pin_def.split('-')
            pin_num = pin_bits[1:]
            pin[GPIODriver.PIN] = int(pin_num[0])
            if self.config.has_section(pin_def) is False:
                self.mon.warn(self, "no pin definition for " + pin_def)
                pin[GPIODriver.DIRECTION] = 'None'
            else:
                # unused pin
                if self.config.get(pin_def, 'direction') == 'none':
                    pin[GPIODriver.DIRECTION] = 'none'
                else:
                    pin[GPIODriver.DIRECTION] = self.config.get(
                        pin_def, 'direction')
                    if pin[GPIODriver.DIRECTION] == 'in':
                        # input pin
                        pin[GPIODriver.RISING_NAME] = self.config.get(
                            pin_def, 'rising-name')
                        pin[GPIODriver.FALLING_NAME] = self.config.get(
                            pin_def, 'falling-name')
                        pin[GPIODriver.ONE_NAME] = self.config.get(
                            pin_def, 'one-name')
                        pin[GPIODriver.ZERO_NAME] = self.config.get(
                            pin_def, 'zero-name')
                        if pin[GPIODriver.FALLING_NAME] == 'pp-shutdown':
                            GPIODriver.shutdown_index = index
                        if self.config.get(pin_def, 'repeat') != '':
                            pin[GPIODriver.REPEAT] = int(
                                self.config.get(pin_def, 'repeat'))
                        else:
                            pin[GPIODriver.REPEAT] = -1
                        pin[GPIODriver.THRESHOLD] = int(
                            self.config.get(pin_def, 'threshold'))
                        if self.config.get(pin_def, 'pull-up-down') == 'up':
                            pin[GPIODriver.PULL] = GPIO.PUD_UP
                        elif self.config.get(pin_def,
                                             'pull-up-down') == 'down':
                            pin[GPIODriver.PULL] = GPIO.PUD_DOWN
                        else:
                            pin[GPIODriver.PULL] = GPIO.PUD_OFF
                    else:
                        # output pin
                        pin[GPIODriver.NAME] = self.config.get(pin_def, 'name')

            # print pin
            GPIODriver.pins.append(copy.deepcopy(pin))

        # setup GPIO
        self.GPIO.setwarnings(True)
        self.GPIO.setmode(self.GPIO.BOARD)

        # set up the GPIO inputs and outputs
        for index, pin in enumerate(GPIODriver.pins):
            num = pin[GPIODriver.PIN]
            if pin[GPIODriver.DIRECTION] == 'in':
                self.GPIO.setup(num,
                                self.GPIO.IN,
                                pull_up_down=pin[GPIODriver.PULL])
            elif pin[GPIODriver.DIRECTION] == 'out':
                self.GPIO.setup(num, self.GPIO.OUT)
                self.GPIO.setup(num, False)
        self.reset_input_state()

        GPIODriver.gpio_enabled = True

        # init timer
        self.button_tick_timer = None
        return 'normal', 'GPIO initialised'

    # called by main program only
    def poll(self):
        # loop to look at the buttons
        self.do_buttons()
        self.button_tick_timer = self.widget.after(self.button_tick, self.poll)

    # called by main program only
    def terminate(self):
        if GPIODriver.gpio_enabled is True:
            if self.button_tick_timer is not None:
                self.widget.after_cancel(self.button_tick_timer)
            self.reset_outputs()
            self.GPIO.cleanup()

# ************************************************
# gpio input functions
# called by main program only
# ************************************************

    def reset_input_state(self):
        for pin in GPIODriver.pins:
            pin[GPIODriver.COUNT] = 0
            pin[GPIODriver.PRESSED] = False
            pin[GPIODriver.LAST] = False
            pin[GPIODriver.REPEAT_COUNT] = pin[GPIODriver.REPEAT]

    # index is of the pins array, provided by the callback ***** needs to be name
    def shutdown_pressed(self):
        if GPIODriver.shutdown_index != 0:
            return GPIODriver.pins[GPIODriver.shutdown_index][
                GPIODriver.PRESSED]
        else:
            return False

    def do_buttons(self):
        for index, pin in enumerate(GPIODriver.pins):
            if pin[GPIODriver.DIRECTION] == 'in':
                # debounce
                if self.GPIO.input(pin[GPIODriver.PIN]) == 0:
                    if pin[GPIODriver.COUNT] < pin[GPIODriver.THRESHOLD]:
                        pin[GPIODriver.COUNT] += 1
                        if pin[GPIODriver.COUNT] == pin[GPIODriver.THRESHOLD]:
                            pin[GPIODriver.PRESSED] = True
                else:  # input us 1
                    if pin[GPIODriver.COUNT] > 0:
                        pin[GPIODriver.COUNT] -= 1
                        if pin[GPIODriver.COUNT] == 0:
                            pin[GPIODriver.PRESSED] = False

                # detect edges
                # falling edge
                if pin[GPIODriver.PRESSED] is True and pin[
                        GPIODriver.LAST] is False:
                    pin[GPIODriver.LAST] = pin[GPIODriver.PRESSED]
                    pin[GPIODriver.REPEAT_COUNT] = pin[GPIODriver.REPEAT]
                    if pin[GPIODriver.
                           FALLING_NAME] != '' and self.button_callback is not None:
                        self.button_callback(pin[GPIODriver.FALLING_NAME],
                                             "GPIO")
            # rising edge
                if pin[GPIODriver.PRESSED] is False and pin[
                        GPIODriver.LAST] is True:
                    pin[GPIODriver.LAST] = pin[GPIODriver.PRESSED]
                    pin[GPIODriver.REPEAT_COUNT] = pin[GPIODriver.REPEAT]
                    if pin[GPIODriver.
                           RISING_NAME] != '' and self.button_callback is not None:
                        self.button_callback(pin[GPIODriver.RISING_NAME],
                                             "GPIO")

                # do state callbacks
                if pin[GPIODriver.REPEAT_COUNT] == 0:
                    if pin[GPIODriver.ZERO_NAME] != '' and pin[
                            GPIODriver.
                            PRESSED] is True and self.button_callback is not None:
                        self.button_callback(pin[GPIODriver.ZERO_NAME], "GPIO")
                    if pin[GPIODriver.ONE_NAME] != '' and pin[
                            GPIODriver.
                            PRESSED] is False and self.button_callback is not None:
                        self.button_callback(pin[GPIODriver.ONE_NAME], "GPIO")
                    pin[GPIODriver.REPEAT_COUNT] = pin[GPIODriver.REPEAT]
                else:
                    if pin[GPIODriver.REPEAT] != -1:
                        pin[GPIODriver.REPEAT_COUNT] -= 1

    # execute an output event
    def handle_output_event(self, name, param_type, param_values, req_time):
        if GPIODriver.gpio_enabled is False:
            return 'normal', 'gpio not enabled'

        #gpio only handles state parameters
        if param_type != 'state':
            return 'error', 'gpio does not handle: ' + param_type
        to_state = param_values[0]
        if to_state == 'on':
            state = True
        else:
            state = False

        pin = self.output_pin_of(name)
        if pin == -1:
            return 'error', 'Not an output for gpio: ' + name

        self.mon.log(
            self,
            'pin P1-' + str(pin) + ' set  ' + str(state) + ' required at: ' +
            str(req_time) + ' sent at: ' + str(long(time.time())))
        # print 'pin P1-'+ str(pin)+ ' set  '+ str(state) + ' required: ' + str(req_time)+ ' actual: ' + str(long(time.time()))
        self.GPIO.output(pin, state)
        return 'normal', 'gpio handled OK'

# ************************************************
# gpio output interface methods
# these can be called from many classes so need to operate on class variables
# ************************************************

    def reset_outputs(self):
        if GPIODriver.gpio_enabled is True:
            self.mon.log(self, 'reset outputs')
            for index, pin in enumerate(GPIODriver.pins):
                num = pin[GPIODriver.PIN]
                if pin[GPIODriver.DIRECTION] == 'out':
                    self.GPIO.output(num, False)

# ************************************************
# internal functions
# these can be called from many classes so need to operate on class variables
# ************************************************

    def output_pin_of(self, name):
        for pin in GPIODriver.pins:
            # print " in list" + pin[GPIODriver.NAME] + str(pin[GPIODriver.PIN] )
            if pin[GPIODriver.NAME] == name and pin[
                    GPIODriver.DIRECTION] == 'out':
                return pin[GPIODriver.PIN]
        return -1

# ***********************************
# reading gpio.cfg
# ************************************

    def read(self, pp_dir, pp_home, pp_profile):
        # try inside profile
        filename = pp_profile + os.sep + 'pp_io_config' + os.sep + 'gpio.cfg'
        if os.path.exists(filename):
            self.config = ConfigParser.ConfigParser()
            self.config.read(filename)
            self.mon.log(self, "gpio.cfg read from " + filename)
            return 'normal', 'gpio.cfg read'
        else:
            return 'normal', 'gpio.cfg not found in profile: ' + filename
Esempio n. 33
0
 def __init__(self):
     self.mon = Monitor()
Esempio n. 34
0
    def  init(self,pp_profile,manager_unit,preferred_interface,my_ip,show_command_callback,input_event_callback,animate_callback):

        self.pp_profile=pp_profile
        self.show_command_callback=show_command_callback
        self.input_event_callback=input_event_callback
        self.animate_callback=animate_callback

        self.mon=Monitor()
        config_file=self.pp_profile + os.sep +'pp_io_config'+os.sep+ 'osc.cfg'
        if not os.path.exists(config_file):
            self.mon.err(self, 'OSC Configuration file not found: '+config_file)
            return'error','OSC Configuration file nof found: '+config_file
        
        self.mon.log(self, 'OSC Configuration file found at: '+config_file)        
        self.osc_config=OSCConfig()
        
        # reads config data 
        if self.osc_config.read(config_file) ==False:
            return 'error','failed to read osc.cfg'

        # unpack config data and initialise

        if self.osc_config.this_unit_name =='':
            return 'error','OSC Config -  This Unit has no name'
        if len(self.osc_config.this_unit_name.split())>1:
            return 'error','OSC config - This Unit Name not a single word: '+self.osc_config.this_unit_name
        self.this_unit_name=self.osc_config.this_unit_name
               
                 
        if self.osc_config.this_unit_ip=='':
            self.this_unit_ip=my_ip
        else:
            self.this_unit_ip=self.osc_config.this_unit_ip

        if self.osc_config.slave_enabled == 'yes':
            if not self.osc_config.listen_port.isdigit():
                return 'error','OSC Config - Listen port is not a positve number: '+ self.osc_config.listen_port
            self.listen_port= self.osc_config.listen_port

        if self.osc_config.master_enabled == 'yes':
            if not self.osc_config.reply_listen_port.isdigit():
                return 'error','OSC Config - Reply Listen port is not a positve number: '+ self.osc_config.reply_listen_port
            self.reply_listen_port= self.osc_config.reply_listen_port

            # prepare the list of slaves
            status,message=self.parse_slaves()
            if status=='error':
                return status,message
             

        self.prefix='/pipresents'
        self.this_unit='/' + self.this_unit_name
        
        self.input_server=None
        self.input_reply_client=None
        self.input_st=None
        
        self.output_client=None
        self.output_reply_server=None
        self.output_reply_st=None


        if self.osc_config.slave_enabled == 'yes' and self.osc_config.master_enabled == 'yes' and self.listen_port == self.reply_listen_port:
            # The two listen ports are the same so use one server for input and output

            #start the client that sends commands to the slaves
            self.output_client=OSC.OSCClient()
            self.mon.log(self, 'sending commands to slaves and replies to master on: '+self.reply_listen_port)

            #start the input+output reply server
            self.mon.log(self, 'listen to commands and replies from slave units using: ' + self.this_unit_ip+':'+self.reply_listen_port)
            self.output_reply_server=myOSCServer((self.this_unit_ip,int(self.reply_listen_port)),self.output_client)
            self.add_default_handler(self.output_reply_server)
            self.add_input_handlers(self.output_reply_server)
            self.add_output_reply_handlers(self.output_reply_server)

            self.input_server=self.output_reply_server
            
        else:

            if self.osc_config.slave_enabled == 'yes':
                # we want this to be a slave to something else

                # start the client that sends replies to controlling unit
                self.input_reply_client=OSC.OSCClient()
                
                #start the input server
                self.mon.log(self, 'listening to commands on: ' + self.this_unit_ip+':'+self.listen_port)
                self.input_server=myOSCServer((self.this_unit_ip,int(self.listen_port)),self.input_reply_client)
                self.add_default_handler(self.input_server)
                self.add_input_handlers(self.input_server)
                print self.pretty_list(self.input_server.getOSCAddressSpace(),'\n')
                
            if self.osc_config.master_enabled =='yes':
                #we want to control other units
               
                #start the client that sends commands to the slaves
                self.output_client=OSC.OSCClient()
                self.mon.log(self, 'sending commands to slaves on port: '+self.reply_listen_port)

                #start the output reply server
                self.mon.log(self, 'listen to replies from slave units using: ' + self.this_unit_ip+':'+self.reply_listen_port)
                self.output_reply_server=myOSCServer((self.this_unit_ip,int(self.reply_listen_port)),self.output_client)
                self.add_default_handler(self.output_reply_server)
                self.add_output_reply_handlers(self.output_reply_server)
        
        return 'normal','osc.cfg read'
class TimeOfDay(object):

    # CLASS VARIABLES

    # change this for another language
    DAYS_OF_WEEK = [
        'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday',
        'sunday'
    ]
    """
        TimeOfDay.events is a dictionary the keys being show-refs.
        Each dictionary entry is a list of time_elements sorted by descending time
        Each time element is a list with the fields:
        0 - command
        1 - time, seconds since midnight

    """
    events = {
    }  # list of times of day used to generate callbacks, earliest first

    # executed by main program and by each object using tod
    def __init__(self):
        self.mon = Monitor()

    # executed once from main program  only
    def init(self, pp_dir, pp_home, pp_profile, showlist, root, callback):

        # instantiate arguments
        TimeOfDay.root = root
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile
        self.showlist = showlist
        self.callback = callback

        # init variables
        self.testing = False
        self.tod_tick = 500
        self.tick_timer = None
        # set time of day for if no schedule
        TimeOfDay.now = datetime.now().replace(microsecond=0)

        #  read and error check the schedule
        reason, message, schedule_enabled = self.read_schedule()
        if reason == 'error':
            return 'error', message, False

        if schedule_enabled is False:
            return 'normal', '', False

        #create the initial events list
        if self.simulate_time is True:
            year = int(self.sim_year)
            month = int(self.sim_month)
            day = int(self.sim_day)
            hour = int(self.sim_hour)
            minute = int(self.sim_minute)
            second = int(self.sim_second)
            TimeOfDay.now = datetime(day=day,
                                     month=month,
                                     year=year,
                                     hour=hour,
                                     minute=minute,
                                     second=second)
            self.testing = True
            print '\nInitial SIMULATED time', TimeOfDay.now.ctime()
            self.mon.sched(
                self, TimeOfDay.now, 'Testing is ON, Initial SIMULATED time ' +
                str(TimeOfDay.now.ctime()))
        else:
            #get the current date/time only this once
            TimeOfDay.now = datetime.now().replace(microsecond=0)
            self.mon.sched(
                self, TimeOfDay.now, 'Testing is OFF, Initial REAL time ' +
                str(TimeOfDay.now.ctime()))
            # print '\nInitial REAL time',TimeOfDay.now.ctime()
            self.testing = False
        # print 'init',TimeOfDay.now
        TimeOfDay.last_now = TimeOfDay.now - timedelta(seconds=1)
        reason, message = self.build_schedule_for_today()
        if reason == 'error':
            return 'error', message, False
        self.mon.sched(self, TimeOfDay.now, self.pretty_todays_schedule())
        if self.testing:
            self.print_todays_schedule()
        self.build_events_lists()
        if self.testing:
            self.print_events_lists()
        # and do exitpipresents or start any show that should be running at start up time
        self.do_catchup()
        return 'normal', '', True

    def do_catchup(self):
        TimeOfDay.scheduler_time = TimeOfDay.now.time()

        # do the catchup for each real show in turn
        # nothing required for start show, all previous events are just ignored.
        for show_ref in TimeOfDay.events:
            if show_ref != 'start':
                # print '\n*****',show_ref
                times = TimeOfDay.events[show_ref]
                # go through the event list for a show rembering show state until the first future event is found.
                # then if last command was to start the show send it
                show_running = False
                last_start_element = []
                for time_element in reversed(times):
                    # print 'now', now_seconds, 'time from events', time_element[1], time_element[0]
                    # got past current time can give up catch up
                    if time_element[1] >= TimeOfDay.scheduler_time:
                        # print ' gone past time - break'
                        break
                    if time_element[0] == 'open':
                        last_start_element = time_element
                        # print 'open - show-running= true'
                        show_running = True
                    elif time_element[0] == 'close':
                        # print 'close - show-running= false'
                        show_running = False
                if show_running is True:
                    #if self.testing:
                    # print 'End of Catch Up Search', show_ref,last_start_element
                    self.mon.sched(
                        self, TimeOfDay.now, 'Catch up for show: ' + show_ref +
                        ' requires ' + last_start_element[0] + ' ' +
                        str(last_start_element[1]))
                    self.do_event(show_ref, last_start_element)

        return 'not exiting'

    # called by main program only
    def poll(self):
        if self.testing:
            poll_time = TimeOfDay.now
        else:
            poll_time = datetime.now()
        # print 'poll time: ',poll_time.time(),'scheduler time: ',TimeOfDay.now.time()
        # if poll_time != TimeOfDay.now : print 'times different ',poll_time.time(),TimeOfDay.now.time()
        # is current time greater than last time the scheduler was run
        # run in a loop to catch up because root.after can get behind when images are being rendered etc.
        # poll time can be the same twice as poll is run at half second intervals.
        catchup_time = 0
        while TimeOfDay.now <= poll_time:
            if TimeOfDay.now - TimeOfDay.last_now != timedelta(seconds=1):
                print 'POLL TIME FAILED', TimeOfDay.last_now, TimeOfDay.now
            #if catchup_time != 0:
            # print 'scheduler behind by: ',catchup_time, TimeOfDay.now.time(),poll_time.time()
            self.do_scheduler()
            TimeOfDay.last_now = TimeOfDay.now
            catchup_time += 1
            # print 'poll',TimeOfDay.now, timedelta(seconds=1)
            TimeOfDay.now = TimeOfDay.now + timedelta(seconds=1)
        # and loop
        if self.testing:
            self.tick_timer = TimeOfDay.root.after(1000, self.poll)
        else:
            self.tick_timer = TimeOfDay.root.after(self.tod_tick, self.poll)

    # called by main program only
    def terminate(self):
        if self.tick_timer is not None:
            TimeOfDay.root.after_cancel(self.tick_timer)
        self.clear_events_lists()

    # execute events at the appropriate time.
    # called by main program only
    def do_scheduler(self):
        # if its midnight then build the events lists for the new day
        TimeOfDay.scheduler_time = TimeOfDay.now.time()
        if TimeOfDay.scheduler_time == time(hour=0, minute=0, second=0):
            # if self.testing:
            # print 'Its midnight,  today is now', TimeOfDay.now.ctime()
            self.mon.sched(
                self, TimeOfDay.now,
                'Its midnight,  today is now ' + str(TimeOfDay.now.ctime()))
            reason, message = self.build_schedule_for_today()
            if reason == 'error':
                self.mon.err(self, 'system error- illegal time at midnight')
                return
            self.mon.sched(self, TimeOfDay.now, self.pretty_todays_schedule())
            # if self.testing:
            # self.print_todays_schedule()
            self.build_events_lists()
            # self.mon.sched(self,TimeOfDay.now,self.pretty_events_lists())
            # self.print_events_lists()

        # print TimeOfDay.scheduler_time
        for show_ref in TimeOfDay.events:
            # print 'scheduler time match', show_ref
            times = TimeOfDay.events[show_ref]
            # now send a command if time matches
            for time_element in reversed(times):
                # print time_element[1],TimeOfDay.scheduler_time
                if time_element[1] == TimeOfDay.scheduler_time:
                    self.do_event(show_ref, time_element)

    # execute an event
    def do_event(self, show_ref, time_element):
        self.mon.log(
            self, 'Event : ' + time_element[0] + ' ' + show_ref +
            ' required at: ' + time_element[1].isoformat())
        self.mon.sched(
            self, TimeOfDay.now, ' ToD Scheduler : ' + time_element[0] + ' ' +
            show_ref + ' required at: ' + time_element[1].isoformat())
        # if self.testing:
        # print 'Event : ' +  time_element[0] + ' ' + show_ref + ' required at: '+ time_element[1].isoformat()
        if show_ref != 'start':
            self.callback(time_element[0] + ' ' + show_ref)
        else:
            self.callback(time_element[0])

#
# ************************************************
# The methods below can be called from many classes so need to operate on class variables
# ************************************************

# clear events list

    def clear_events_lists(self):
        self.mon.log(self, 'clear time of day  events list ')
        # empty event list
        TimeOfDay.events = {}

# ***********************************
# Preparing schedule and todays event list
# ************************************

    def read_schedule(self):
        # get schedule from showlist
        index = self.showlist.index_of_start_show()
        self.showlist.select(index)
        starter_show = self.showlist.selected_show()

        sched_enabled = starter_show['sched-enable']
        if sched_enabled != 'yes':
            return 'normal', '', False

        if starter_show['simulate-time'] == 'yes':
            self.simulate_time = True

            self.sim_second = starter_show['sim-second']
            if not self.sim_second.isdigit():
                return 'error', 'Simulate time -  second is not a positive integer ' + self.sim_second, False
            if int(self.sim_second) > 59:
                return 'error', 'Simulate time - second is out of range ' + self.sim_second, False

            self.sim_minute = starter_show['sim-minute']
            if not self.sim_minute.isdigit():
                return 'error', 'Simulate time - minute is not a positive integer ' + self.sim_minute, False
            if int(self.sim_minute) > 59:
                return 'error', 'Simulate time -  minute is out of range ' + self.sim_minute, False

            self.sim_hour = starter_show['sim-hour']
            if not self.sim_hour.isdigit():
                return 'error', 'Simulate time - hour is not a positive integer ' + self.sim_hour, False
            if int(self.sim_hour) > 23:
                return 'error', 'Simulate time -  hour is out of range ' + self.sim_hour, False

            self.sim_day = starter_show['sim-day']
            if not self.sim_day.isdigit():
                return 'error', 'Simulate time - day is not a positive integer ' + self.sim_day, False
            if int(self.sim_day) > 31:
                return 'error', 'Simulate time -  day is out of range ' + self.sim_day, False

            self.sim_month = starter_show['sim-month']
            if not self.sim_month.isdigit():
                return 'error', 'Simulate time - month is not a positive integer ' + self.sim_month, False
            if int(self.sim_month) > 12:
                return 'error', 'Simulate time -  month is out of range ' + self.sim_month, False

            self.sim_year = starter_show['sim-year']
            if not self.sim_year.isdigit():
                return 'error', 'Simulate time - year is not a positive integer ' + self.sim_year, False
            if int(self.sim_year) < 2018:
                return 'error', 'Simulate time -  year is out of range ' + self.sim_year, False
        else:
            self.simulate_time = False

        return 'normal', '', True

    def build_schedule_for_today(self):
        # print this_day.year, this_day.month, this_day.day, TimeOfDay.DAYS_OF_WEEK[ this_day.weekday()]
        """
        self.todays_schedule is a dictionary the keys being show-refs.
        Each dictionary entry is a list of time_elements
        Each time element is a list with the fields:
        0 - command
        1 - time hour:min[:sec]

        """
        self.todays_schedule = {}
        for index in range(self.showlist.length()):
            show = self.showlist.show(index)
            show_type = show['type']
            show_ref = show['show-ref']
            # print 'looping build ',show_type,show_ref,self.showlist.length()
            if 'sched-everyday' in show:
                text = show['sched-everyday']
                lines = text.splitlines()
                while len(lines) != 0:
                    status, message, day_lines, lines = self.get_one_day(
                        lines, show_ref)
                    if status == 'error':
                        return 'error', message
                    status, message, days_list, times_list = self.parse_day(
                        day_lines, 'everyday', show_ref, show_type)
                    if status == 'error':
                        return 'error', message
                    #print 'everyday ',status,message,days_list,times_list
                    self.todays_schedule[show['show-ref']] = copy.deepcopy(
                        times_list)

                # print '\nafter everyday'
                # self.print_todays_schedule()

            if 'sched-weekday' in show:
                text = show['sched-weekday']
                lines = text.splitlines()
                while len(lines) != 0:
                    status, message, day_lines, lines = self.get_one_day(
                        lines, show_ref)
                    if status == 'error':
                        return 'error', message
                    status, message, days_list, times_list = self.parse_day(
                        day_lines, 'weekday', show_ref, show_type)
                    if status == 'error':
                        return 'error', message
                    #print 'weekday ',status,message,days_list,times_list
                    # is current day of the week in list of days in schedule
                    if TimeOfDay.DAYS_OF_WEEK[
                            TimeOfDay.now.weekday()] in days_list:
                        self.todays_schedule[show['show-ref']] = copy.deepcopy(
                            times_list)

                #print '\nafter weekday'
                #self.print_todays_schedule()

            if 'sched-monthday' in show:
                text = show['sched-monthday']
                lines = text.splitlines()
                while len(lines) != 0:
                    status, message, day_lines, lines = self.get_one_day(
                        lines, show_ref)
                    # print 'in monthday',day_lines
                    if status == 'error':
                        return 'error', message
                    status, message, days_list, times_list = self.parse_day(
                        day_lines, 'monthday', show_ref, show_type)
                    if status == 'error':
                        return 'error', message
                    #print 'monthday ',status,message,days_list,times_list
                    if TimeOfDay.now.day in map(int, days_list):
                        self.todays_schedule[show['show-ref']] = copy.deepcopy(
                            times_list)

                #print '\nafter monthday'
                #self.print_todays_schedule()

            if 'sched-specialday' in show:

                text = show['sched-specialday']
                lines = text.splitlines()
                while len(lines) != 0:
                    status, message, day_lines, lines = self.get_one_day(
                        lines, show_ref)
                    if status == 'error':
                        return 'error', message

                    status, message, days_list, times_list = self.parse_day(
                        day_lines, 'specialday', show_ref, show_type)
                    if status == 'error':
                        return 'error', message
                    # print 'specialday ',status,message,days_list,times_list
                    for day in days_list:
                        sdate = datetime.strptime(day, '%Y-%m-%d')
                        if sdate.year == TimeOfDay.now.year and sdate.month == TimeOfDay.now.month and sdate.day == TimeOfDay.now.day:
                            self.todays_schedule[
                                show['show-ref']] = copy.deepcopy(times_list)

                #print '\nafter specialday'
                #self.print_todays_schedule()
        return 'normal', ''

    def get_one_day(self, lines, show_ref):
        this_day = []
        left_over = []
        #print 'get one day',lines
        # check first line is day and move tt output
        #print lines[0]
        if not lines[0].startswith('day'):
            return 'error', 'first line of section is not day ' + lines[
                0] + ' ' + show_ref, [], []
        this_day = [lines[0]]
        #print ' this day',this_day
        left_over = lines[1:]
        # print 'left over',left_over
        x_left_over = lines[1:]
        for line in x_left_over:
            #print 'in loop',line
            if line.startswith('day'):
                # print 'one day day',this_day,left_over
                return 'normal', '', this_day, left_over
            this_day.append(line)
            left_over = left_over[1:]
        # print 'one day end',this_day,left_over
        return 'normal', '', this_day, left_over

    def parse_day(self, lines, section, show_ref, show_type):
        # text
        # day monday
        # open 1:42
        # close 1:45
        # returns status,message,list of days,list of time lines
        print 'lines ', len(lines), section
        if section == 'everyday':
            status, message, days_list = self.parse_everyday(
                lines[0], show_ref)
        elif section == 'weekday':
            status, message, days_list = self.parse_weekday(lines[0], show_ref)
        elif section == 'monthday':
            # print 'parse_day',lines
            status, message, days_list = self.parse_monthday(
                lines[0], show_ref)
        elif section == 'specialday':
            status, message, days_list = self.parse_specialday(
                lines[0], show_ref)
        else:
            return 'error','illegal section name '+section + ' '+ show_ref,[],[]
        if status == 'error':
            return 'error', message, [], []
        if len(lines) > 1:
            time_lines = lines[1:]
            status, message, times_list = self.parse_time_lines(
                time_lines, show_ref, show_type)
            if status == 'error':
                return 'error', message, [], []
        else:
            times_list = []
        return 'normal', '', days_list, times_list

    def parse_everyday(self, line, show_ref):
        words = line.split()
        if words[0] != 'day':
            return 'error','day line does not contain day  '+ line + ' ' + show_ref,[]
        if words[1] != 'everyday':
            return 'error','everday line does not contain everyday  '+ show_ref,[]
        return 'normal', '', ['everyday']

    def parse_weekday(self, line, show_ref):
        words = line.split()
        if words[0] != 'day':
            return 'error','day line does not contain day  ' + line + ' ' + show_ref,[]
        days = words[1:]
        for day in days:
            if day not in TimeOfDay.DAYS_OF_WEEK:
                return 'error','weekday line has illegal day '+ day + ' '+ show_ref,[]
        return 'normal', '', days

    def parse_monthday(self, line, show_ref):
        words = line.split()
        if words[0] != 'day':
            return 'error', 'day line does not contain day  ' + show_ref, []
        days = words[1:]
        for day in days:
            if not day.isdigit():
                return 'error','monthday line has illegal day '+ day + ' '+ show_ref,[]
            if int(day) < 1 or int(day) > 31:
                return 'error','monthday line has out of range day '+ line+ ' '+ show_ref,[]
        return 'normal', '', days

    def parse_specialday(self, line, show_ref):
        words = line.split()
        if words[0] != 'day':
            return 'error', 'day line does not contain day  ' + show_ref, []
        days = words[1:]
        for day in days:
            status, message = self.parse_date(day, show_ref)
            if status == 'error':
                return 'error', message, ''
        return 'normal', '', days

    def parse_time_lines(self, lines, show_ref, show_type):
        # lines - list of  lines each with text 'command time'
        # returns list of lists each being [command, time]
        time_lines = []
        for line in lines:
            # split line into time,command
            words = line.split()
            if len(words) < 2:
                return 'error','time line has wrong length '+ line+ ' '+ show_ref,[]
            status, message, time_item = self.parse_time(words[0], show_ref)
            if status == 'error':
                return 'error', message, []

            if show_type == 'start':
                command = ' '.join(words[1:])
                time_lines.append([command, time_item])
            else:
                if words[1] not in ('open', 'close'):
                    return 'error','illegal command in '+ line+ ' '+ show_ref,[]
                time_lines.append([words[1], time_item])
        return 'normal', '', time_lines

    def build_events_lists(self):
        # builds events dictionary from todays_schedule by
        # converting times in todays schedule from hour:min:sec to datetime
        # and sorts them earliest last
        TimeOfDay.events = {}
        for show_ref in self.todays_schedule:
            # print show_ref
            times = self.todays_schedule[show_ref]
            for time_element in times:
                time_element[1] = self.parse_event_time(time_element[1])
            sorted_times = sorted(times,
                                  key=lambda time_element: time_element[1],
                                  reverse=True)
            TimeOfDay.events[show_ref] = sorted_times
            # print times

    def parse_event_time(self, time_text):
        fields = time_text.split(':')
        if len(fields) > 2:
            secs = int(fields[2])
        else:
            secs = 0
        hours = int(fields[0])
        mins = int(fields[1])
        return time(hour=hours, minute=mins, second=secs)

    def parse_time(self, item, show_ref):
        fields = item.split(':')
        if len(fields) == 0:
            return 'error', 'Time field is empty ' + item + ' ' + show_ref, item
        if len(fields) > 3:
            return 'error', 'Too many fields in ' + item + ' ' + show_ref, item
        if len(fields) == 1:
            seconds = fields[0]
            minutes = '0'
            hours = '0'
        if len(fields) == 2:
            seconds = fields[1]
            minutes = fields[0]
            hours = '0'
        if len(fields) == 3:
            seconds = fields[2]
            minutes = fields[1]
            hours = fields[0]
        if not seconds.isdigit() or not minutes.isdigit() or not hours.isdigit(
        ):
            return 'error', 'Fields of  ' + item + ' are not positive integers ' + show_ref, item
        if int(minutes) > 59:
            return 'error', 'Minutes of  ' + item + ' is out of range ' + show_ref, item
        if int(seconds) > 59:
            return 'error', 'Seconds of  ' + item + ' is out of range ' + show_ref, item
        if int(hours) > 23:
            return 'error', 'Hours of  ' + item + ' is out of range ' + show_ref, item
        return 'normal', '', item

    def parse_date(self, item, show_ref):
        fields = item.split('-')
        if len(fields) == 0:
            return 'error', 'Date field is empty ' + item + ' ' + show_ref
        if len(fields) != 3:
            return 'error', 'Too many or few fields in date ' + item + ' ' + show_ref
        year = fields[0]
        month = fields[1]
        day = fields[2]
        if not year.isdigit() or not month.isdigit() or not day.isdigit():
            return 'error', 'Fields of  ' + item + ' are not positive integers ' + show_ref
        if int(year) < 2018:
            return 'error', 'Year of  ' + item + ' is out of range ' + show_ref + year
        if int(month) > 12:
            return 'error', 'Month of  ' + item + ' is out of range ' + show_ref
        if int(day) > 31:
            return 'error', 'Day of  ' + item + ' is out of range ' + show_ref
        return 'normal', ''

# *********************
# print for debug
# *********************

    def pretty_todays_schedule(self):
        op = 'Schedule For ' + TimeOfDay.now.ctime() + '\n'
        for key in self.todays_schedule:
            op += '  ' + key + '\n'
            for show in self.todays_schedule[key]:
                op += '    ' + show[0] + ':   ' + str(show[1]) + '\n'
            op += '\n'
        return op

    def pretty_events_lists(self):
        op = ' Task list for today'
        for key in self.events:
            op += '\n' + key
            for show in self.events[key]:
                op += '\n    ' + show[0] + ' ' + str(show[1].isoformat())
        return op

    def print_todays_schedule(self):
        print '\nSchedule For ' + TimeOfDay.now.ctime()
        for key in self.todays_schedule:
            print '  ' + key
            for show in self.todays_schedule[key]:
                print '    ' + show[0] + ':   ' + show[1]
            print

    def print_events_lists(self):
        print '\nTask list for today'
        for key in self.events:
            print '\n', key
            for show in self.events[key]:
                print show[0], show[1].isoformat()
        print
Esempio n. 36
0
class PPEditor(object):

    # ***************************************
    # INIT
    # ***************************************

    def __init__(self):
    
        self.editor_issue="1.3"

        # get command options
        self.command_options=ed_options()

        # get directory holding the code
        self.pp_dir=sys.path[0]
            
        if not os.path.exists(self.pp_dir+os.sep+"pp_editor.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()
            
          
        # Initialise logging
        Monitor.log_path=self.pp_dir
        self.mon=Monitor()
        self.mon.init()
        
        Monitor.classes  = ['PPEditor','EditItem','Validator']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log (self, "Pi Presents Editor is starting")
        self.mon.log (self," OS and separator " + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: code "+sys.path[0])


        # set up the gui
 
        # root is the Tkinter root widget
        self.root = Tk()
        self.root.title("Editor for Pi Presents")

        # self.root.configure(background='grey')

        self.root.resizable(False,False)

        # define response to main window closing
        self.root.protocol ("WM_DELETE_WINDOW", self.app_exit)

        # bind some display fields
        self.filename = StringVar()
        self.display_selected_track_title = StringVar()
        self.display_show = StringVar()


        # define menu
        menubar = Menu(self.root)

        profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        profilemenu.add_command(label='Open', command = self.open_existing_profile)
        profilemenu.add_command(label='Validate', command = self.validate_profile)
        menubar.add_cascade(label='Profile', menu = profilemenu)

        ptypemenu = Menu(profilemenu, tearoff=0, bg="grey", fg="black")
        ptypemenu.add_command(label='Exhibit', command = self.new_exhibit_profile)
        ptypemenu.add_command(label='Media Show', command = self.new_mediashow_profile)
        ptypemenu.add_command(label='Art Media Show', command = self.new_artmediashow_profile)
        ptypemenu.add_command(label='Menu', command = self.new_menu_profile)
        ptypemenu.add_command(label='Presentation', command = self.new_presentation_profile)
        ptypemenu.add_command(label='Interactive', command = self.new_interactive_profile)
        ptypemenu.add_command(label='Live Show', command = self.new_liveshow_profile)
        ptypemenu.add_command(label='Art Live Show', command = self.new_artliveshow_profile)
        ptypemenu.add_command(label='RadioButton Show', command = self.new_radiobuttonshow_profile)
        ptypemenu.add_command(label='Hyperlink Show', command = self.new_hyperlinkshow_profile)
        ptypemenu.add_command(label='Blank', command = self.new_blank_profile)
        profilemenu.add_cascade(label='New from Template', menu = ptypemenu)
        
        showmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        showmenu.add_command(label='Delete', command = self.remove_show)
        showmenu.add_command(label='Edit', command = self.m_edit_show)
        showmenu.add_command(label='Copy To', command = self.copy_show)
        menubar.add_cascade(label='Show', menu = showmenu)

        stypemenu = Menu(showmenu, tearoff=0, bg="grey", fg="black")
        stypemenu.add_command(label='Menu', command = self.add_menushow)
        stypemenu.add_command(label='MediaShow', command = self.add_mediashow)
        stypemenu.add_command(label='LiveShow', command = self.add_liveshow)
        stypemenu.add_command(label='HyperlinkShow', command = self.add_hyperlinkshow)
        stypemenu.add_command(label='RadioButtonShow', command = self.add_radiobuttonshow)
        stypemenu.add_command(label='ArtMediaShow', command = self.add_artmediashow)
        stypemenu.add_command(label='ArtLiveShow', command = self.add_artliveshow)
        showmenu.add_cascade(label='Add', menu = stypemenu)
        
        medialistmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='MediaList', menu = medialistmenu)
        medialistmenu.add_command(label='Add', command = self.add_medialist)
        medialistmenu.add_command(label='Delete', command = self.remove_medialist)
        medialistmenu.add_command(label='Copy To', command = self.copy_medialist)
      
        trackmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        trackmenu.add_command(label='Delete', command = self.remove_track)
        trackmenu.add_command(label='Edit', command = self.m_edit_track)
        trackmenu.add_command(label='Add from Dir', command = self.add_tracks_from_dir)
        trackmenu.add_command(label='Add from File', command = self.add_track_from_file)


        menubar.add_cascade(label='Track', menu = trackmenu)

        typemenu = Menu(trackmenu, tearoff=0, bg="grey", fg="black")
        typemenu.add_command(label='Video', command = self.new_video_track)
        typemenu.add_command(label='Audio', command = self.new_audio_track)
        typemenu.add_command(label='Image', command = self.new_image_track)
        typemenu.add_command(label='Web', command = self.new_web_track)
        typemenu.add_command(label='Message', command = self.new_message_track)
        typemenu.add_command(label='Show', command = self.new_show_track)
        typemenu.add_command(label='Menu Track', command = self.new_menu_track)
        trackmenu.add_cascade(label='New', menu = typemenu)

        oscmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='OSC', menu = oscmenu)
        oscmenu.add_command(label='Create OSC configuration', command = self.create_osc)
        oscmenu.add_command(label='Edit OSC Configuration', command = self.edit_osc)
        oscmenu.add_command(label='Delete OSC Configuration', command = self.delete_osc)


        toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Tools', menu = toolsmenu)
        toolsmenu.add_command(label='Update All', command = self.update_all)
        
        optionsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Options', menu = optionsmenu)
        optionsmenu.add_command(label='Edit', command = self.edit_options)

        helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Help', menu = helpmenu)
        helpmenu.add_command(label='Help', command = self.show_help)
        helpmenu.add_command(label='About', command = self.about)
         
        self.root.config(menu=menubar)

        top_frame=Frame(self.root)
        top_frame.pack(side=TOP)
        bottom_frame=Frame(self.root)
        bottom_frame.pack(side=TOP, fill=BOTH, expand=1)        

        left_frame=Frame(bottom_frame, padx=5)
        left_frame.pack(side=LEFT)
        middle_frame=Frame(bottom_frame,padx=5)
        middle_frame.pack(side=LEFT)              
        right_frame=Frame(bottom_frame,padx=5,pady=10)
        right_frame.pack(side=LEFT)
        updown_frame=Frame(bottom_frame,padx=5)
        updown_frame.pack(side=LEFT)
        
        tracks_title_frame=Frame(right_frame)
        tracks_title_frame.pack(side=TOP)
        tracks_label = Label(tracks_title_frame, text="Tracks in Selected Medialist")
        tracks_label.pack()
        tracks_frame=Frame(right_frame)
        tracks_frame.pack(side=TOP)
        shows_title_frame=Frame(left_frame)
        shows_title_frame.pack(side=TOP)
        shows_label = Label(shows_title_frame, text="Shows")
        shows_label.pack()
        shows_frame=Frame(left_frame)
        shows_frame.pack(side=TOP)
        shows_title_frame=Frame(left_frame)
        shows_title_frame.pack(side=TOP)
        medialists_title_frame=Frame(left_frame)
        medialists_title_frame.pack(side=TOP)
        medialists_label = Label(medialists_title_frame, text="Medialists")
        medialists_label.pack()
        medialists_frame=Frame(left_frame)
        medialists_frame.pack(side=LEFT)
        
        # define buttons 

        add_button = Button(middle_frame, width = 5, height = 2, text='Edit\nShow',
                            fg='black', command = self.m_edit_show, bg="light grey")
        add_button.pack(side=RIGHT)
        
        add_button = Button(updown_frame, width = 5, height = 1, text='Add',
                            fg='black', command = self.add_track_from_file, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Edit',
                            fg='black', command = self.m_edit_track, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Up',
                            fg='black', command = self.move_track_up, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Down',
                            fg='black', command = self.move_track_down, bg="light grey")
        add_button.pack(side=TOP)


        # define display of showlist 
        scrollbar = Scrollbar(shows_frame, orient=VERTICAL)
        self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12,
                                     width = 40, bg="white",activestyle=NONE,
                                     fg="black", yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.shows_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.shows_display.pack(side=LEFT, fill=BOTH, expand=1)
        self.shows_display.bind("<ButtonRelease-1>", self.e_select_show)

    
        # define display of medialists
        scrollbar = Scrollbar(medialists_frame, orient=VERTICAL)
        self.medialists_display = Listbox(medialists_frame, selectmode=SINGLE, height=12,
                                          width = 40, bg="white",activestyle=NONE,
                                          fg="black",yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.medialists_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.medialists_display.pack(side=LEFT,  fill=BOTH, expand=1)
        self.medialists_display.bind("<ButtonRelease-1>", self.select_medialist)


        # define display of tracks
        scrollbar = Scrollbar(tracks_frame, orient=VERTICAL)
        self.tracks_display = Listbox(tracks_frame, selectmode=SINGLE, height=25,
                                      width = 40, bg="white",activestyle=NONE,
                                      fg="black",yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.tracks_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.tracks_display.pack(side=LEFT,fill=BOTH, expand=1)
        self.tracks_display.bind("<ButtonRelease-1>", self.e_select_track)


        # initialise editor options class and OSC config class
        self.options=Options(self.pp_dir) # creates options file in code directory if necessary
        self.osc_config=OSCConfig()
        
        # initialise variables      
        self.init()
        
        # and enter Tkinter event loop
        self.root.mainloop()        


    # ***************************************
    # INIT AND EXIT
    # ***************************************
    def app_exit(self):
        self.root.destroy()
        exit()


    def init(self):
        self.options.read()
        self.pp_home_dir = self.options.pp_home_dir
        self.pp_profiles_offset = self.options.pp_profiles_offset
        self.initial_media_dir = self.options.initial_media_dir
        self.mon.log(self,"Data Home from options is "+self.pp_home_dir)
        self.mon.log(self,"Current Profiles Offset from options is "+self.pp_profiles_offset)
        self.mon.log(self,"Initial Media from options is "+self.initial_media_dir)
        self.pp_profile_dir=''
        self.osc_config_file = ''
        self.current_medialist=None
        self.current_showlist=None
        self.current_show=None
        self.shows_display.delete(0,END)
        self.medialists_display.delete(0,END)
        self.tracks_display.delete(0,END)



    # ***************************************
    # MISCELLANEOUS
    # ***************************************

    def edit_options(self):
        """edit the options then read them from file"""
        eo = OptionsDialog(self.root, self.options.options_file,'Edit Options')
        if eo.result is True: self.init()



    def show_help (self):
        tkMessageBox.showinfo("Help","Read 'manual.pdf'")
  

    def about (self):
        tkMessageBox.showinfo("About","Editor for Pi Presents Profiles\n"
                              +"For profile version: " + self.editor_issue + "\nAuthor: Ken Thompson"
                              +"\nWebsite: http://pipresents.wordpress.com/")

    def validate_profile(self):
        val =Validator()
        val.validate_profile(self.root,self.pp_dir,self.pp_home_dir,self.pp_profile_dir,self.editor_issue,True)


    # **************
    # OSC CONFIGURATION
    # **************

    def create_osc(self):
        if self.pp_profile_dir=='':
            return
        if self.osc_config.read(self.osc_config_file) is False:
            iodir=self.pp_profile_dir+os.sep+'pp_io_config'
            if not os.path.exists(iodir):
                os.makedirs(iodir)
            self.osc_config.create(self.osc_config_file)

    def edit_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            # print 'no config file'
            return
        osc_ut=OSCUnitType(self.root,self.osc_config.this_unit_type)
        self.req_unit_type=osc_ut.result
        if self.req_unit_type != None:
            # print self.req_unit_type
            eosc = OSCEditor(self.root, self.osc_config_file,self.req_unit_type,'Edit OSC Configuration')
            
    def delete_osc(self):
        if self.osc_config.read(self.osc_config_file) is False:
            return
        os.rename(self.osc_config_file,self.osc_config_file+'.bak')
        

    
    # **************
    # PROFILES
    # **************

    def open_existing_profile(self):
        initial_dir=self.pp_home_dir+os.sep+"pp_profiles"+self.pp_profiles_offset
        if os.path.exists(initial_dir) is False:
            self.mon.err(self,"Profiles directory not found: " + initial_dir + "\n\nHint: Data Home option must end in pp_home")
            return
        dir_path=tkFileDialog.askdirectory(initialdir=initial_dir)
        # dir_path="C:\Users\Ken\pp_home\pp_profiles\\ttt"
        if len(dir_path)>0:
            self.open_profile(dir_path)
        

    def open_profile(self,dir_path):
        showlist_file = dir_path + os.sep + "pp_showlist.json"
        if os.path.exists(showlist_file) is False:
            self.mon.err(self,"Not a Profile: " + dir_path + "\n\nHint: Have you opened the profile directory?")
            return
        self.pp_profile_dir = dir_path
        self.root.title("Editor for Pi Presents - "+ self.pp_profile_dir)
        if self.open_showlist(self.pp_profile_dir) is False:
            self.init()
            return
        self.open_medialists(self.pp_profile_dir)
        self.refresh_tracks_display()
        self.osc_config_file=self.pp_profile_dir+os.sep+'pp_io_config'+os.sep+'osc.cfg'


    def new_profile(self,profile):
        d = Edit1Dialog(self.root,"New Profile","Name", "")
        if d .result  is  None:
            return
        name=str(d.result)
        if name == "":
            tkMessageBox.showwarning("New Profile","Name is blank")
            return
        to = self.pp_home_dir + os.sep + "pp_profiles"+ self.pp_profiles_offset + os.sep + name
        if os.path.exists(to) is  True:
            tkMessageBox.showwarning( "New Profile","Profile exists\n(%s)" % to )
            return
        shutil.copytree(profile, to, symlinks=False, ignore=None)
        self.open_profile(to)


        
    def new_exhibit_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_exhibit_1p3'
        self.new_profile(profile)

    def new_interactive_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_interactive_1p3'
        self.new_profile(profile)

    def new_menu_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_menu_1p3'
        self.new_profile(profile)

    def new_presentation_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_presentation_1p3'
        self.new_profile(profile)

    def new_blank_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep +"ppt_blank_1p3"
        self.new_profile(profile)

    def new_mediashow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_mediashow_1p3'
        self.new_profile(profile)
        
    def new_liveshow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_liveshow_1p3'
        self.new_profile(profile)

    def new_artmediashow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_artmediashow_1p3'
        self.new_profile(profile)
        
    def new_artliveshow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_artliveshow_1p3'
        self.new_profile(profile)

    def new_radiobuttonshow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_radiobuttonshow_1p3'
        self.new_profile(profile)

    def new_hyperlinkshow_profile(self):
        profile = self.pp_dir+os.sep+'pp_resources'+os.sep+'pp_templates'+os.sep + 'ppt_hyperlinkshow_1p3'
        self.new_profile(profile)

    # ***************************************
    # Shows
    # ***************************************

    def open_showlist(self,profile_dir):
        showlist_file = profile_dir + os.sep + "pp_showlist.json"
        if os.path.exists(showlist_file) is False:
            self.mon.err(self,"showlist file not found at " + profile_dir + "\n\nHint: Have you opened the profile directory?")
            self.app_exit()
        self.current_showlist=ShowList()
        self.current_showlist.open_json(showlist_file)
        if float(self.current_showlist.sissue())<float(self.editor_issue) or  (self.command_options['forceupdate']  is  True and float(self.current_showlist.sissue()) == float(self.editor_issue)):
            self.update_profile()
            self.mon.err(self,"Version of profile has been updated to "+self.editor_issue+", please re-open")
            return False
        if float(self.current_showlist.sissue())>float(self.editor_issue):
            self.mon.err(self,"Version of profile is greater than editor, must exit")
            self.app_exit()
        self.refresh_shows_display()
        return True


    def save_showlist(self,showlist_dir):
        if self.current_showlist is not None:
            showlist_file = showlist_dir + os.sep + "pp_showlist.json"
            self.current_showlist.save_list(showlist_file)
            
    def add_mediashow(self):
        self.add_show(PPdefinitions.new_shows['mediashow'])

    def add_liveshow(self):
        self.add_show(PPdefinitions.new_shows['liveshow'])

    def add_radiobuttonshow(self):
        self.add_show(PPdefinitions.new_shows['radiobuttonshow'])

    def add_hyperlinkshow(self):
        self.add_show(PPdefinitions.new_shows['hyperlinkshow'])

    def add_artliveshow(self):
        self.add_show(PPdefinitions.new_shows['artliveshow'])

    def add_artmediashow(self):
        self.add_show(PPdefinitions.new_shows['artmediashow'])
        
    def add_menushow(self):
        self.add_show(PPdefinitions.new_shows['menu'])

    def add_start(self):  
        self.add_show(PPdefinitions.new_shows['start'])


    def add_show(self,default):
        # append it to the showlist and then add the medialist
        if self.current_showlist is not None:
            d = Edit1Dialog(self.root,"AddShow","Show Reference", "")
            if d.result  is  None:
                return
            name=str(d.result)
            if name == "":
                tkMessageBox.showwarning("Add Show","Name is blank")
                return
                                         
            if self.current_showlist.index_of_show(name) != -1:
                tkMessageBox.showwarning("Add Show","A Show with this name already exists")
                return            
            copied_show=self.current_showlist.copy(default,name)
            mediafile=self.add_medialist(name)
            if mediafile != '':
                copied_show['medialist']=mediafile
            self.current_showlist.append(copied_show)
            self.save_showlist(self.pp_profile_dir)
            self.refresh_shows_display()

            
    def remove_show(self):
        if  self.current_showlist is not None and self.current_showlist.length()>0 and self.current_showlist.show_is_selected():
            if tkMessageBox.askokcancel("Delete Show","Delete Show"):
                index= self.current_showlist.selected_show_index()
                self.current_showlist.remove(index)
                self.save_showlist(self.pp_profile_dir)
                self.refresh_shows_display()

    def show_refs(self):
        _show_refs=[]
        for index in range(self.current_showlist.length()):
            if self.current_showlist.show(index)['show-ref'] != "start":
                _show_refs.append(copy.deepcopy(self.current_showlist.show(index)['show-ref']))
        return _show_refs
 
    def refresh_shows_display(self):
        self.shows_display.delete(0,self.shows_display.size())
        for index in range(self.current_showlist.length()):
            self.shows_display.insert(END, self.current_showlist.show(index)['title']+"   ["+self.current_showlist.show(index)['show-ref']+"]")        
        if self.current_showlist.show_is_selected():
            self.shows_display.itemconfig(self.current_showlist.selected_show_index(),fg='red')            
            self.shows_display.see(self.current_showlist.selected_show_index())

            
    def e_select_show(self,event):
        if self.current_showlist is not None and self.current_showlist.length()>0:
            mouse_item_index=int(event.widget.curselection()[0])
            self.current_showlist.select(mouse_item_index)
            self.refresh_shows_display()

    def copy_show(self):
        if  self.current_showlist is not None and self.current_showlist.show_is_selected():
            self.add_show(self.current_showlist.selected_show())

        
    def m_edit_show(self):
        self.edit_show(PPdefinitions.show_types,PPdefinitions.show_field_specs)
        
     

    def edit_show(self,show_types,field_specs):
        if self.current_showlist is not None and self.current_showlist.show_is_selected():
            d=EditItem(self.root,"Edit Show",self.current_showlist.selected_show(),show_types,field_specs,self.show_refs(),
                       self.initial_media_dir,self.pp_home_dir,'show')
            if d.result  is  True:

                self.save_showlist(self.pp_profile_dir)
                self.refresh_shows_display()

 

    # ***************************************
    #   Medialists
    # ***************************************

    def open_medialists(self,profile_dir):
        self.medialists = []
        for this_file in os.listdir(profile_dir):
            if this_file.endswith(".json") and this_file not in ('pp_showlist.json','schedule.json'):
                self.medialists = self.medialists + [this_file]
        self.medialists_display.delete(0,self.medialists_display.size())
        for index in range (len(self.medialists)):
            self.medialists_display.insert(END, self.medialists[index])
        self.current_medialists_index=-1
        self.current_medialist=None


    def add_medialist(self,name=None):
        if name is None:
            d = Edit1Dialog(self.root,"Add Medialist","File", "")
            if d.result  is  None:
                return ''
            name=str(d.result)
            if name == "":
                tkMessageBox.showwarning("Add medialist","Name is blank")
                return ''
            
        if not name.endswith(".json"):
            name=name+(".json")
                
        path = self.pp_profile_dir + os.sep + name
        if os.path.exists(path) is  True:
            tkMessageBox.showwarning("Add medialist","Medialist file exists\n(%s)" % path)
            return ''
        nfile = open(path,'wb')
        nfile.write("{")
        nfile.write("\"issue\":  \""+self.editor_issue+"\",\n")
        nfile.write("\"tracks\": [")
        nfile.write("]")
        nfile.write("}")
        nfile.close()
        # append it to the list
        self.medialists.append(copy.deepcopy(name))
        # add title to medialists display
        self.medialists_display.insert(END, name)  
        # and set it as the selected medialist
        self.refresh_medialists_display()
        return name


    def copy_medialist(self,to_file=None):
        if self.current_medialist is not None:
            #from_file= self.current_medialist 
            from_file= self.medialists[self.current_medialists_index]
            if to_file is None:
                d = Edit1Dialog(self.root,"Copy Medialist","File", "")
                if d.result  is  None:
                    return ''
                to_file=str(d.result)
                if to_file == "":
                    tkMessageBox.showwarning("Copy medialist","Name is blank")
                    return ''
                
            success_file = self.copy_medialist_file(from_file,to_file)
            if success_file =='':
                return ''

            # append it to the list
            self.medialists.append(copy.deepcopy(success_file))
            # add title to medialists display
            self.medialists_display.insert(END, success_file)
            # and reset  selected medialist
            self.current_medialist=None
            self.refresh_medialists_display()
            self.refresh_tracks_display()
            return success_file
        else:
            return ''

    def copy_medialist_file(self,from_file,to_file):
        if not to_file.endswith(".json"):
            to_file+=(".json")
                
        to_path = self.pp_profile_dir + os.sep + to_file
        if os.path.exists(to_path) is  True:
            tkMessageBox.showwarning("Copy medialist","Medialist file exists\n(%s)" % to_path)
            return ''
        
        from_path= self.pp_profile_dir + os.sep + from_file
        if os.path.exists(from_path) is  False:
            tkMessageBox.showwarning("Copy medialist","Medialist file not found\n(%s)" % from_path)
            return ''

        shutil.copy(from_path,to_path)
        return to_file


    def remove_medialist(self):
        if self.current_medialist is not None:
            if tkMessageBox.askokcancel("Delete Medialist","Delete Medialist"):
                os.remove(self.pp_profile_dir+ os.sep + self.medialists[self.current_medialists_index])
                self.open_medialists(self.pp_profile_dir)
                self.refresh_medialists_display()
                self.refresh_tracks_display()


    def select_medialist(self,event):
        """
        user clicks on a medialst in a profile so try and select it.
        """
        # needs forgiving int for possible tkinter upgrade
        if len(self.medialists)>0:
            self.current_medialists_index=int(event.widget.curselection()[0])
            self.current_medialist=MediaList('ordered')
            if not self.current_medialist.open_list(self.pp_profile_dir+ os.sep + self.medialists[self.current_medialists_index],self.current_showlist.sissue()):
                self.mon.err(self,"medialist is a different version to showlist: "+ self.medialists[self.current_medialists_index])
                self.app_exit()        
            self.refresh_tracks_display()
            self.refresh_medialists_display()


    def refresh_medialists_display(self):
        self.medialists_display.delete(0,len(self.medialists))
        for index in range (len(self.medialists)):
            self.medialists_display.insert(END, self.medialists[index])
        if self.current_medialist is not None:
            self.medialists_display.itemconfig(self.current_medialists_index,fg='red')
            self.medialists_display.see(self.current_medialists_index)

    def save_medialist(self):
        basefile=self.medialists[self.current_medialists_index]
        # print type(basefile)
        # basefile=str(basefile)
        # print type(basefile)
        medialist_file = self.pp_profile_dir+ os.sep + basefile
        self.current_medialist.save_list(medialist_file)

  
          
    # ***************************************
    #   Tracks
    # ***************************************
          
    def refresh_tracks_display(self):
        self.tracks_display.delete(0,self.tracks_display.size())
        if self.current_medialist is not None:
            for index in range(self.current_medialist.length()):
                if self.current_medialist.track(index)['track-ref'] != '':
                    track_ref_string="  ["+self.current_medialist.track(index)['track-ref']+"]"
                else:
                    track_ref_string=""
                self.tracks_display.insert(END, self.current_medialist.track(index)['title']+track_ref_string)        
            if self.current_medialist.track_is_selected():
                self.tracks_display.itemconfig(self.current_medialist.selected_track_index(),fg='red')            
                self.tracks_display.see(self.current_medialist.selected_track_index())
            
    def e_select_track(self,event):
        if self.current_medialist is not None and self.current_medialist.length()>0:
            mouse_item_index=int(event.widget.curselection()[0])
            self.current_medialist.select(mouse_item_index)
            self.refresh_tracks_display()

    def m_edit_track(self):
        self.edit_track(PPdefinitions.track_types,PPdefinitions.track_field_specs)

    def edit_track(self,track_types,field_specs):      
        if self.current_medialist is not None and self.current_medialist.track_is_selected():
            d=EditItem(self.root,"Edit Track",self.current_medialist.selected_track(),track_types,field_specs,
                       self.show_refs(),self.initial_media_dir,self.pp_home_dir,'track')
            if d.result  is  True:
                self.save_medialist()
            self.refresh_tracks_display()

    def move_track_up(self):
        if self.current_medialist is not None and self.current_medialist.track_is_selected():
            self.current_medialist.move_up()
            self.refresh_tracks_display()
            self.save_medialist()

    def move_track_down(self):
        if self.current_medialist is not None and self.current_medialist.track_is_selected():
            self.current_medialist.move_down()
            self.refresh_tracks_display()
            self.save_medialist()
        
    def new_track(self,fields,values):
        if self.current_medialist is not None:
            # print '\nfields ', fields
            # print '\nvalues ', values
            new_track=copy.deepcopy(fields)
            # print ',\new track ',new_track
            self.current_medialist.append(new_track)
            # print '\nbefore values ',self.current_medialist.print_list()
            if values is not None:
                self.current_medialist.update(self.current_medialist.length()-1,values)
            self.current_medialist.select(self.current_medialist.length()-1)
            self.refresh_tracks_display()
            self.save_medialist()

    def new_message_track(self):
        self.new_track(PPdefinitions.new_tracks['message'],None)
            
    def new_video_track(self):
        self.new_track(PPdefinitions.new_tracks['video'],None)
  
    def new_audio_track(self):
        self.new_track(PPdefinitions.new_tracks['audio'],None)

    def new_web_track(self):
        self.new_track(PPdefinitions.new_tracks['web'],None)
        
    def new_image_track(self):
        self.new_track(PPdefinitions.new_tracks['image'],None)

    def new_show_track(self):
        self.new_track(PPdefinitions.new_tracks['show'],None)

    def new_menu_track(self):
        self.new_track(PPdefinitions.new_tracks['menu'],None)
 
    def remove_track(self):
        if  self.current_medialist is not None and self.current_medialist.length()>0 and self.current_medialist.track_is_selected():
            if tkMessageBox.askokcancel("Delete Track","Delete Track"):
                index= self.current_medialist.selected_track_index()
                self.current_medialist.remove(index)
                self.save_medialist()
                self.refresh_tracks_display()
                
    def add_track_from_file(self):
        if self.current_medialist is None: return
        # print "initial directory ", self.options.initial_media_dir
        files_path=tkFileDialog.askopenfilename(initialdir=self.options.initial_media_dir, multiple=True)
        # fix for tkinter bug
        files_path =  self.root.tk.splitlist(files_path)
        for file_path in files_path:
            file_path=os.path.normpath(file_path)
            # print "file path ", file_path
            self.add_track(file_path)
        self.save_medialist()

    def add_tracks_from_dir(self):
        if self.current_medialist is None: return
        image_specs =[PPdefinitions.IMAGE_FILES,PPdefinitions.VIDEO_FILES,PPdefinitions.AUDIO_FILES,
                      PPdefinitions.WEB_FILES,('All files', '*')]
        # last one is ignored in finding files in directory, for dialog box only
        directory=tkFileDialog.askdirectory(initialdir=self.options.initial_media_dir)
        # deal with tuple returned on Cancel
        if len(directory) == 0: return
        # make list of exts we recognise
        exts = []
        for image_spec in image_specs[:-1]:
            image_list=image_spec[1:]
            for ext in image_list:
                exts.append(copy.deepcopy(ext))
        for this_file in os.listdir(directory):
            (root_file,ext_file)= os.path.splitext(this_file)
            if ext_file.lower() in exts:
                file_path=directory+os.sep+this_file
                # print "file path before ", file_path
                file_path=os.path.normpath(file_path)
                # print "file path after ", file_path
                self.add_track(file_path)
        self.save_medialist()


    def add_track(self,afile):
        relpath = os.path.relpath(afile,self.pp_home_dir)
        # print "relative path ",relpath
        common = os.path.commonprefix([afile,self.pp_home_dir])
        # print "common ",common
        if common.endswith("pp_home")  is  False:
            location = afile
        else:
            location = "+" + os.sep + relpath
            location = string.replace(location,'\\','/')
            # print "location ",location
        (root,title)=os.path.split(afile)
        (root,ext)= os.path.splitext(afile)
        if ext.lower() in PPdefinitions.IMAGE_FILES:
            self.new_track(PPdefinitions.new_tracks['image'],{'title':title,'track-ref':'','location':location})
        elif ext.lower() in PPdefinitions.VIDEO_FILES:
            self.new_track(PPdefinitions.new_tracks['video'],{'title':title,'track-ref':'','location':location})
        elif ext.lower() in PPdefinitions.AUDIO_FILES:
            self.new_track(PPdefinitions.new_tracks['audio'],{'title':title,'track-ref':'','location':location})
        elif ext.lower() in PPdefinitions.WEB_FILES:
            self.new_track(PPdefinitions.new_tracks['web'],{'title':title,'track-ref':'','location':location})
        else:
            self.mon.err(self,afile + " - cannot determine track type, use menu track>new")



    # *********************************************
    # UPDATE PROFILE
    # **********************************************

    def update_all(self):
        self.init()
        for profile_file in os.listdir(self.pp_home_dir+os.sep+'pp_profiles'+self.pp_profiles_offset):
            # self.mon.log (self,"Updating "+profile_file)
            self.pp_profile_dir = self.pp_home_dir+os.sep+'pp_profiles'+self.pp_profiles_offset + os.sep + profile_file
            if not os.path.exists(self.pp_profile_dir+os.sep+"pp_showlist.json"):
                tkMessageBox.showwarning("Pi Presents","Not a profile, skipping "+self.pp_profile_dir)
            else:
                self.current_showlist=ShowList()
                self.current_showlist.open_json(self.pp_profile_dir+os.sep+"pp_showlist.json")
                self.mon.log (self,"Version of profile "+ profile_file + ' is ' + self.current_showlist.sissue())
                if float(self.current_showlist.sissue())<float(self.editor_issue):
                    self.mon.log(self,"Version of profile "+profile_file+ "  is being updated to "+self.editor_issue)
                    self.update_profile()
                elif (self.command_options['forceupdate']  is  True and float(self.current_showlist.sissue()) == float(self.editor_issue)):
                    self.mon.log(self, "Forced updating of " + profile_file + ' to '+self.editor_issue)
                    self.update_profile()
                elif float(self.current_showlist.sissue())>float(self.editor_issue):
                    tkMessageBox.showwarning("Pi Presents", "Version of profile " +profile_file+ " is greater than editor, skipping")
                else:
                    self.mon.log(self," Skipping Profile " + profile_file + " It is already up to date ")
        self.init()
        tkMessageBox.showwarning("Pi Presents","All profiles updated")
            
    def update_profile(self):

        self.update_medialists()   # medialists and their tracks
        self.update_shows()         #shows in showlist, also creates menu tracks for 1.2>1.3
        

    def update_shows(self):
        # open showlist into a list of dictionaries
        self.mon.log (self,"Updating show ")
        ifile  = open(self.pp_profile_dir + os.sep + "pp_showlist.json", 'rb')
        shows = json.load(ifile)['shows']
        ifile.close()

        # special 1.2>1.3 create menu medialists with menu track from show
        #go through shows - if type = menu and version is greater copy its medialist to a new medialist with  name = <show-ref>-menu1p3.json
        for show in shows:
            #create a new medialist medialist != show-ref as menus can't now share medialists
            if show['type']=='menu' and float(self.current_showlist.sissue())<float(self.editor_issue):
                to_file=show['show-ref']+'-menu1p3.json'
                from_file = show['medialist']
                if to_file != from_file:
                    self.copy_medialist_file(from_file,to_file)
                else:
                    self.mon.warn(self, 'medialist file' + to_file + ' already exists, must exit with incomplete update')
                    return False

                #update the reference to the medialist
                show['medialist']=to_file
                
                #delete show fields so they are recreated with new default content
                del show['controls']
                
                # open the  medialist and add the menu track then populate some of its fields from the show
                ifile  = open(self.pp_profile_dir + os.sep + to_file, 'rb')
                tracks = json.load(ifile)['tracks']
                ifile.close()
                
                new_track=copy.deepcopy(PPdefinitions.new_tracks['menu'])
                tracks.append(copy.deepcopy(new_track))

                # copy menu parameters from menu show to menu track and init values of some              
                self.transfer_show_params(show,tracks,'menu-track',("entry-colour","entry-font", "entry-select-colour", 
                                                                    "hint-colour", "hint-font", "hint-text", "hint-x","hint-y",
                                                                    "menu-bullet", "menu-columns", "menu-direction", "menu-guidelines",
                                                                    "menu-horizontal-padding", "menu-horizontal-separation", "menu-icon-height", "menu-icon-mode",
                                                                    "menu-icon-width", "menu-rows", "menu-strip", "menu-strip-padding",  "menu-text-height", "menu-text-mode", "menu-text-width",
                                                                     "menu-vertical-padding", "menu-vertical-separation",
                                                                    "menu-window"))
                                          
                # and save the medialist
                dic={'issue':self.editor_issue,'tracks':tracks}
                ofile  = open(self.pp_profile_dir + os.sep + to_file, "wb")
                json.dump(dic,ofile,sort_keys=True,indent=1)
                # end for show in shows

        #update the fields in  all shows
        replacement_shows=self.update_shows_in_showlist(shows)
        dic={'issue':self.editor_issue,'shows':replacement_shows}
        ofile  = open(self.pp_profile_dir + os.sep + "pp_showlist.json", "wb")
        json.dump(dic,ofile,sort_keys=True,indent=1)
        return True


    def transfer_show_params(self,show,tracks,track_ref,fields):
        # find the menu track in medialist
        for index,track in enumerate(tracks):
            if track['track-ref']== 'menu-track':
                break
            
        #update some fields with new default content
        tracks[index]['links']=PPdefinitions.new_tracks['menu']['links']

        #transfer values from show to track
        for field in fields:
            tracks[index][field]=show[field]
            # print show[field], tracks[index][field]
            pass
            
        
                                          

    def update_medialists(self):
         # UPDATE MEDIALISTS AND THEIR TRACKS
        for this_file in os.listdir(self.pp_profile_dir):
            if this_file.endswith(".json") and this_file not in  ('pp_showlist.json','schedule.json'):
                self.mon.log (self,"Updating medialist " + this_file)
                # open a medialist and update its tracks
                ifile  = open(self.pp_profile_dir + os.sep + this_file, 'rb')
                tracks = json.load(ifile)['tracks']
                ifile.close()
                replacement_tracks=self.update_tracks(tracks)
                dic={'issue':self.editor_issue,'tracks':replacement_tracks}
                ofile  = open(self.pp_profile_dir + os.sep + this_file, "wb")
                json.dump(dic,ofile,sort_keys=True,indent=1)       



    def update_tracks(self,old_tracks):
        # get correct spec from type of field
        replacement_tracks=[]
        for old_track in old_tracks:
            # print '\nold track ',old_track
            track_type=old_track['type']
            #update if new tracks has the track type otherwise skip
            if track_type in PPdefinitions.new_tracks:
                spec_fields=PPdefinitions.new_tracks[track_type]
                left_overs=dict()
                # go through track and delete fields not in spec
                for key in old_track.keys():
                    if key in spec_fields:
                        left_overs[key]=old_track[key]
                # print '\n leftovers',left_overs
                replacement_track=copy.deepcopy(PPdefinitions.new_tracks[track_type])
                # print '\n before update', replacement_track
                replacement_track.update(left_overs)
                # print '\nafter update',replacement_track
                replacement_tracks.append(copy.deepcopy(replacement_track))
        return replacement_tracks


    def update_shows_in_showlist(self,old_shows):
        # get correct spec from type of field
        replacement_shows=[]
        for old_show in old_shows:
            show_type=old_show['type']
            ## menu to menushow
            spec_fields=PPdefinitions.new_shows[show_type]
            left_overs=dict()
            # go through track and delete fields not in spec
            for key in old_show.keys():
                if key in spec_fields:
                    left_overs[key]=old_show[key]
            # print '\n leftovers',left_overs
            replacement_show=copy.deepcopy(PPdefinitions.new_shows[show_type])
            replacement_show.update(left_overs)
            replacement_shows.append(copy.deepcopy(replacement_show))
        return replacement_shows                
Esempio n. 37
0
class uzblDriver(object):

    def __init__(self,widget):

        self.widget=widget
        
        self.mon=Monitor()
        self.mon.on()
        self._process=None
        self.fifo=''

    def pause(self):
            pass

    def stop(self):
            self.control('exit')


    # kill the subprocess (uzbl). Used for tidy up on exit.
    def terminate(self,reason):
        self.terminate_reason=reason
        if self.exists_fifo():
           self.control('exit')
           #self._process.close(force=True)
        self.end_play_signal=True

               
    def play(self, track, geometry):
        self.start_play_signal = False
        self.end_play_signal=False
        # track= "'"+ track.replace("'","'\\''") + "'"

        cmd='uzbl-browser '  + geometry + '--uri='+track
        self.mon.log(self, "Send command to uzbl: "+ cmd)
        self._process = pexpect.spawn(cmd)       
        # uncomment to monitor output to and input from uzbl (read pexpect manual)
        # fout= file('/home/pi/pipresents/uzbllogfile.txt','w')  #uncomment and change sys.stdout to fout to log to a file
        # self._process.logfile_send = sys.stdout  # send just commands to stdout
        # self._process.logfile=fout  # send all communications to log
        
        # and poll for fifo to be available
        self.get_fifo()

    # poll for fifo to be available
    # when it is set start_play_signal
    # then monitor for it to be delted because browser is closed
    # and the set end_play signal
    
    def get_fifo(self):
        """
        Look for UZBL's FIFO-file in /tmp.
        Don't give up until it has been found.
        """
        candidates = glob('/tmp/uzbl_fifo_*')
        for file in candidates:
            if S_ISFIFO(os_stat(file).st_mode):
                self.mon.log(self, 'Found UZBL fifo  in %s.' % file)
                self.fifo=file
                self.start_play_signal=True
                return
        # print 'not found trying again'
        self.widget.after(500,self.get_fifo)


    def exists_fifo(self):
        if os.path.exists(self.fifo):
            return True
        else:
            return False

    # send commands to uzbl via the fifo
    def control(self,data):
        if self.exists_fifo():
            self.mon.log(self,'send command to uzbl:'+data)
            f = open(self.fifo, 'a')
            f.write('%s\n' % data)
            f.close()

   # test of whether _process is running
    def is_running(self):
        return self._process.isalive()     
Esempio n. 38
0
    def __init__(self):
        gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES
                     | gc.DEBUG_OBJECTS | gc.DEBUG_SAVEALL)
        self.pipresents_issue = "1.3"
        self.pipresents_minorissue = '1.3.1g'
        # position and size of window without -f command line option
        self.nonfull_window_width = 0.45  # proportion of width
        self.nonfull_window_height = 0.7  # proportion of height
        self.nonfull_window_x = 0  # position of top left corner
        self.nonfull_window_y = 0  # position of top left corner
        self.pp_background = 'black'

        StopWatch.global_enable = False

        # set up the handler for SIGTERM
        signal.signal(signal.SIGTERM, self.handle_sigterm)

        # ****************************************
        # Initialisation
        # ***************************************
        # get command line options
        self.options = command_options()

        # get Pi Presents code directory
        pp_dir = sys.path[0]
        self.pp_dir = pp_dir

        if not os.path.exists(pp_dir + "/pipresents.py"):
            if self.options['manager'] is False:
                tkMessageBox.showwarning(
                    "Pi Presents",
                    "Bad Application Directory:\n{0}".format(pp_dir))
            exit(103)

        # Initialise logging and tracing
        Monitor.log_path = pp_dir
        self.mon = Monitor()
        # Init in PiPresents only
        self.mon.init()

        # uncomment to enable control of logging from within a class
        # Monitor.enable_in_code = True # enables control of log level in the code for a class  - self.mon.set_log_level()

        # make a shorter list to log/trace only some classes without using enable_in_code.
        Monitor.classes = [
            'PiPresents', 'pp_paths', 'HyperlinkShow', 'RadioButtonShow',
            'ArtLiveShow', 'ArtMediaShow', 'MediaShow', 'LiveShow', 'MenuShow',
            'PathManager', 'ControlsManager', 'ShowManager', 'PluginManager',
            'MplayerDriver', 'OMXDriver', 'UZBLDriver', 'KbdDriver',
            'GPIODriver', 'TimeOfDay', 'ScreenDriver', 'Animate', 'OSCDriver'
        ]

        # Monitor.classes=['PiPresents','ArtMediaShow','VideoPlayer','OMXDriver']

        # get global log level from command line
        Monitor.log_level = int(self.options['debug'])
        Monitor.manager = self.options['manager']
        # print self.options['manager']
        self.mon.newline(3)
        self.mon.log(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue)
        # self.mon.log (self," OS and separator:" + os.name +'  ' + os.sep)
        self.mon.log(self, "sys.path[0] -  location of code: " + sys.path[0])
        if os.geteuid() != 0:
            user = os.getenv('USER')
        else:
            user = os.getenv('SUDO_USER')
        self.mon.log(self, 'User is: ' + user)
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME')) # does not work
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))   # does not work

        # optional other classes used
        self.root = None
        self.ppio = None
        self.tod = None
        self.animate = None
        self.gpiodriver = None
        self.oscdriver = None
        self.osc_enabled = False
        self.gpio_enabled = False
        self.tod_enabled = False

        # get home path from -o option
        self.pp_home = pp_paths.get_home(self.options['home'])
        if self.pp_home is None:
            self.end('error', 'Failed to find pp_home')

        # get profile path from -p option
        # pp_profile is the full path to the directory that contains
        # pp_showlist.json and other files for the profile
        self.pp_profile = pp_paths.get_profile_dir(self.pp_home,
                                                   self.options['profile'])
        if self.pp_profile is None:
            self.end('error', 'Failed to find profile')

        # check profile exists
        if os.path.exists(self.pp_profile):
            self.mon.log(
                self, "Found Requested profile - pp_profile directory is: " +
                self.pp_profile)
        else:
            self.mon.err(
                self, "Failed to find requested profile: " + self.pp_profile)
            self.end('error', 'Failed to find profile')

        self.mon.start_stats(self.options['profile'])

        # check 'verify' option
        if self.options['verify'] is True:
            val = Validator()
            if val.validate_profile(None, pp_dir, self.pp_home,
                                    self.pp_profile, self.pipresents_issue,
                                    False) is False:
                self.mon.err(self, "Validation Failed")
                self.end('error', 'Validation Failed')

        # initialise and read the showlist in the profile
        self.showlist = ShowList()
        self.showlist_file = self.pp_profile + "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self, "showlist not found at " + self.showlist_file)
            self.end('error', 'showlist not found')

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue()) != float(self.pipresents_issue):
            self.mon.err(
                self, "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents, must exit")
            self.end('error', 'wrong version of profile')

        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >= 0:
            self.showlist.select(index)
            self.starter_show = self.showlist.selected_show()
        else:
            self.mon.err(self, "Show [start] not found in showlist")
            self.end('error', 'start show not found')

        if self.starter_show['start-show'] == '':
            self.mon.warn(self, "No Start Shows in Start Show")

# ********************
# SET UP THE GUI
# ********************
# turn off the screenblanking and saver
        if self.options['noblank'] is True:
            call(["xset", "s", "off"])
            call(["xset", "s", "-dpms"])

        self.root = Tk()

        self.title = 'Pi Presents - ' + self.pp_profile
        self.icon_text = 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg=self.pp_background)

        self.mon.log(
            self, 'native screen dimensions are ' +
            str(self.root.winfo_screenwidth()) + ' x ' +
            str(self.root.winfo_screenheight()) + ' pixcels')
        if self.options['screensize'] == '':
            self.screen_width = self.root.winfo_screenwidth()
            self.screen_height = self.root.winfo_screenheight()
        else:
            reason, message, self.screen_width, self.screen_height = self.parse_screen(
                self.options['screensize'])
            if reason == 'error':
                self.mon.err(self, message)
                self.end('error', message)

        self.mon.log(
            self, 'commanded screen dimensions are ' + str(self.screen_width) +
            ' x ' + str(self.screen_height) + ' pixcels')

        # set window dimensions and decorations
        if self.options['fullscreen'] is False:
            self.window_width = int(self.root.winfo_screenwidth() *
                                    self.nonfull_window_width)
            self.window_height = int(self.root.winfo_screenheight() *
                                     self.nonfull_window_height)
            self.window_x = self.nonfull_window_x
            self.window_y = self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
        else:
            self.window_width = self.screen_width
            self.window_height = self.screen_height
            self.root.attributes('-fullscreen', True)
            os.system(
                'unclutter 1>&- 2>&- &'
            )  # Suppress 'someone created a subwindow' complaints from unclutter
            self.window_x = 0
            self.window_y = 0
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
            self.root.attributes('-zoomed', '1')

        # canvs cover the whole screen whatever the size of the window.
        self.canvas_height = self.screen_height
        self.canvas_width = self.screen_width

        # make sure focus is set.
        self.root.focus_set()

        # define response to main window closing.
        self.root.protocol("WM_DELETE_WINDOW", self.handle_user_abort)

        # setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg=self.pp_background)

        if self.options['fullscreen'] is True:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=0)
        else:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=1,
                               highlightcolor='yellow')

        self.canvas.place(x=0, y=0)
        # self.canvas.config(bg='black')
        self.canvas.focus_set()

        # ****************************************
        # INITIALISE THE INPUT DRIVERS
        # ****************************************

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd = KbdDriver()
        if kbd.read(pp_dir, self.pp_home, self.pp_profile) is False:
            self.end('error', 'cannot find or error in keys.cfg')
        kbd.bind_keys(self.root, self.handle_input_event)

        self.sr = ScreenDriver()
        # read the screen click area config file
        reason, message = self.sr.read(pp_dir, self.pp_home, self.pp_profile)
        if reason == 'error':
            self.end('error', 'cannot find screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        # click areas are made on the Pi Presents canvas not the show canvases.
        reason, message = self.sr.make_click_areas(self.canvas,
                                                   self.handle_input_event)
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required = False
        self.exitpipresents_required = False

        # kick off GPIO if enabled by command line option
        self.gpio_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'gpio.cfg'):
            # initialise the GPIO
            self.gpiodriver = GPIODriver()
            reason, message = self.gpiodriver.init(pp_dir, self.pp_home,
                                                   self.pp_profile,
                                                   self.canvas, 50,
                                                   self.handle_input_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.gpio_enabled = True
                # and start polling gpio
                self.gpiodriver.poll()

        # kick off animation sequencer
        self.animate = Animate()
        self.animate.init(pp_dir, self.pp_home, self.pp_profile, self.canvas,
                          200, self.handle_output_event)
        self.animate.poll()

        #create a showmanager ready for time of day scheduler and osc server
        show_id = -1
        self.show_manager = ShowManager(show_id, self.showlist,
                                        self.starter_show, self.root,
                                        self.canvas, self.pp_dir,
                                        self.pp_profile, self.pp_home)
        # first time through set callback to terminate Pi Presents if all shows have ended.
        self.show_manager.init(self.canvas, self.all_shows_ended_callback,
                               self.handle_command, self.showlist)
        # Register all the shows in the showlist
        reason, message = self.show_manager.register_shows()
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

        # Init OSCDriver, read config and start OSC server
        self.osc_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'osc.cfg'):
            self.oscdriver = OSCDriver()
            reason, message = self.oscdriver.init(
                self.pp_profile, self.handle_command, self.handle_input_event,
                self.e_osc_handle_output_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.osc_enabled = True
                self.root.after(1000, self.oscdriver.start_server())

        # and run the start shows
        self.run_start_shows()

        # set up the time of day scheduler including catchup
        self.tod_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'schedule.json'):
            # kick off the time of day scheduler which may run additional shows
            self.tod = TimeOfDay()
            self.tod.init(pp_dir, self.pp_home, self.pp_profile, self.root,
                          self.handle_command)
            self.tod_enabled = True

        # then start the time of day scheduler
        if self.tod_enabled is True:
            self.tod.poll()

        # start Tkinters event loop
        self.root.mainloop()
Esempio n. 39
0
class HyperlinkShow:
    """
        Aimed at touchscreens but can be used for any purpose where the user is required to follow hyperlinks between tracks
        Profiles for media tracks (message, image, video, audio ) specify links to other tracks
        in a link a symbolic name of an input is associated with a track-reference
        The show begins at first-track and then uses events (GPIO, keypresses etc.) to link to other tracks via their symbolic names
        If using 'call' keeps a record of the tracks it has visited so the 'return' command can go back.
        Executes timeout-track if no user input is received.

        links are of the form:
           symbolic-name command [track-ref]
        
        link commands:
          call <track-ref> play track-ref and add it to the path
          return - return 1 back up the path removing the track from the path, stops at home-track.
          return n - return n tracks back up the path removing the track from the path, stops at home-track.
          return <track-ref> return to <track-ref> removing tracks from the path
          home  - return to home-track removing tracks from the path
          jump <track-ref-> - play trck-ref forgetting the path back to home-track
          goto <track-ref> - play track-ref, forget the path 
          exit - end the hyperlink show
          null - inhibits the link defined in the show with the same symbolic name.

          reserved symbolic names
          pp-onend command  - pseudo symbolic name for end of a track

        interface:
         * play - selects the first track to play (first-track) 
         * input_pressed,  - receives user events passes them to a Shower/Player if a track is playing,
                otherwise actions them depending on the symbolic name supplied
    """

    # *********************
    # external interface
    # ********************

    def __init__(self, show_params, root, canvas, showlist, pp_dir, pp_home,
                 pp_profile):
        """ canvas - the canvas that the tracks of the event show are to be written on
            show_params - the name of the configuration dictionary section for the hyperlinkshow
            showlist  - the showlist, to enable runningnof show type tracks.
            pp_home - Pi presents data_home directory
            pp_profile - Pi presents profile directory
        """

        self.mon = Monitor()
        self.mon.on()

        #instantiate arguments
        self.show_params = show_params
        self.root = root
        self.showlist = showlist
        self.canvas = canvas
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile

        # open resources
        self.rr = ResourceReader()

        #create a path stack
        self.path = PathManager()

        # init variables
        self.drawn = None
        self.player = None
        self.shower = None
        self.timeout_running = None
        self.error = False

    def play(self,
             show_id,
             end_callback,
             ready_callback,
             top=False,
             command='nil'):
        """ starts the hyperlink show at start-track 
              end_callback - function to be called when the show exits
              ready_callback - callback when event-show is ready to display its forst track (not used?)
              top is True when the show is top level (run from [start] or from show control)
              command is not used
        """

        #instantiate arguments
        self.show_id = show_id
        self.end_callback = end_callback
        self.ready_callback = ready_callback
        self.top = top
        self.command = command

        # check data files are available.
        self.medialist_file = self.pp_profile + "/" + self.show_params[
            'medialist']
        if not os.path.exists(self.medialist_file):
            self.mon.err(self,
                         "Medialist file not found: " + self.medialist_file)
            self.end('error', "Medialist file not found")

        #create a medialist object for the hyperlinkshow and read the file into it.
        self.medialist = MediaList()
        if self.medialist.open_list(self.medialist_file,
                                    self.showlist.sissue()) == False:
            self.mon.err(self, "Version of medialist different to Pi Presents")
            self.end('error', "Version of medialist different to Pi Presents")

        #get controls for this show if top level
        controlsmanager = ControlsManager()
        if self.top == True:
            self.controls_list = controlsmanager.default_controls()
            # and merge in controls from profile
            self.controls_list = controlsmanager.merge_show_controls(
                self.controls_list, self.show_params['controls'])

        # read show  links and destinations
        self.first_track_ref = self.show_params['first-track-ref']
        self.home_track_ref = self.show_params['home-track-ref']
        self.timeout_track_ref = self.show_params['timeout-track-ref']

        # state variables and signals
        self.end_hyperlinkshow_signal = False
        self.egg_timer = None
        self.next_track_signal = False
        self.next_track_ref = ''
        self.current_track_ref = ''
        self.current_track_type = ''

        # ready callback for show
        if self.ready_callback <> None:
            self.ready_callback()

        self.canvas.delete('pp-content')
        self.canvas.config(bg='black')

        self.do_first_track()

#stop received from another concurrent show via ShowManager

    def managed_stop(self):
        # set signal to stop the hyperlinkshow when all  sub-shows and players have ended
        self.end_hyperlinkshow_signal = True
        # then stop and shows or tracks.
        if self.shower <> None:
            self.shower.managed_stop()
        elif self.player <> None:
            self.player.input_pressed('stop')
        else:
            self.end('normal', 'stopped by ShowManager')

    # kill or error
    def terminate(self, reason):
        self.end_hyperlinkshow_signal = True
        if self.shower <> None:
            self.shower.terminate(reason)
        elif self.player <> None:
            self.player.terminate(reason)
        else:
            self.end(reason, 'terminated without terminating shower or player')

# respond to inputs

    def input_pressed(self, symbol, edge, source):

        self.mon.log(self, "received symbol: " + symbol)

        #does the symbol match a link, if so execute it
        if self.is_link(symbol, edge, source) == True:
            return

        # controls are disabled so ignore anything else
        if self.show_params['disable-controls'] == 'yes':
            return

        # does it match a control
        # if at top convert symbolic name to operation otherwise lower down we have received an operatio
        # look through list of controls to find match
        if self.top == True:
            operation = self.lookup_control(symbol, self.controls_list)
        else:
            operation = symbol
        # print 'operation',operation
        if operation <> '':
            self.do_operation(operation, edge, source)

    def do_operation(self, operation, edge, source):
        if self.shower <> None:
            # if next lower show is running pass down to stop the show and lower level
            self.shower.input_pressed(operation, edge, source)
        else:
            # control this show and its tracks
            if operation == 'stop':
                if self.player <> None:
                    if self.current_track_ref == self.first_track_ref and self.top == False:
                        self.end_radiobuttonshow_signal = True
                    self.player.input_pressed('stop')

            elif operation == 'pause':
                if self.player <> None:
                    self.player.input_pressed(operation)

            elif operation[0:4] == 'omx-' or operation[
                    0:6] == 'mplay-' or operation[0:5] == 'uzbl-':
                if self.player <> None:
                    self.player.input_pressed(operation)

    def is_link(self, symbol, edge, source):
        # find the first entry in links that matches the symbol and execute its operation
        # print 'hyperlinkshow ',symbol
        found = False
        for link in self.links:
            #print link
            if symbol == link[0]:
                found = True
                if link[1] <> 'null':
                    # print 'match',link[0]
                    link_operation = link[1]
                    if link_operation == 'home':
                        self.do_home(edge, source)
                    elif link_operation == 'return':
                        self.do_return(link[2], edge, source)
                    elif link_operation == 'call':
                        self.do_call(link[2], edge, source)
                    elif link_operation == 'goto':
                        self.do_goto(link[2], edge, source)
                    elif link_operation == 'jump':
                        self.do_jump(link[2], edge, source)
                    elif link_operation == 'exit':
                        self.end('normal', 'executed exit command')
        return found

    def lookup_control(self, symbol, controls_list):
        for control in controls_list:
            if symbol == control[0]:
                return control[1]
        return ''

# *********************
# INTERNAL FUNCTIONS
# ********************

# *********************
# Show Sequencer
# *********************

    def timeout_callback(self):
        self.do_call(self.timeout_track_ref, 'front', 'timeout')

    def do_call(self, track_ref, edge, source):
        if track_ref <> self.current_track_ref:
            self.mon.log(self, 'call: ' + track_ref)
            self.next_track_signal = True
            self.next_track_op = 'call'
            self.next_track_arg = track_ref
            if self.shower <> None:
                self.shower.input_pressed('stop', edge, source)
            elif self.player <> None:
                self.player.input_pressed('stop')
            else:
                self.what_next()

    def do_goto(self, to, edge, source):
        if to <> self.current_track_ref:
            self.mon.log(self, 'goto: ' + to)
            self.next_track_signal = True
            self.next_track_op = 'goto'
            self.next_track_arg = to
            if self.shower <> None:
                self.shower.input_pressed('stop', edge, source)
            elif self.player <> None:
                self.player.input_pressed('stop')
            else:
                self.what_next()

    def do_jump(self, to, edge, source):
        if to <> self.current_track_ref:
            self.mon.log(self, 'jump to: ' + to)
            self.next_track_signal = True
            self.next_track_op = 'jump'
            self.next_track_arg = to
            if self.shower <> None:
                self.shower.input_pressed('stop', edge, source)
            elif self.player <> None:
                self.player.input_pressed('stop')
            else:
                self.what_next()

    def do_return(self, to, edge, source):
        self.next_track_signal = True
        if to.isdigit() or to == '':
            self.mon.log(self, 'hyperlink command - return by: ' + to)
            self.next_track_op = 'return-by'
            if to == '':
                self.next_track_arg = '1'
            else:
                self.next_track_arg = to
        else:
            self.mon.log(self, 'hyperlink command - return to: ' + to)
            self.next_track_op = 'return-to'
            self.next_track_arg = to
        if self.shower <> None:
            self.shower.input_pressed('stop', edge, source)
        elif self.player <> None:
            self.player.input_pressed('stop')
        else:
            self.what_next()

    def do_home(self, edge, source):
        if self.current_track_ref <> self.home_track_ref:
            self.mon.log(self, 'hyperlink command - home')
            self.next_track_signal = True
            self.next_track_op = 'home'
            if self.shower <> None:
                self.shower.input_pressed('stop', edge, source)
            elif self.player <> None:
                self.player.input_pressed('stop')
            else:
                self.what_next()

    def do_first_track(self):
        index = self.medialist.index_of_track(self.first_track_ref)
        if index >= 0:
            #don't use select the track as not using selected_track in hyperlinkshow
            first_track = self.medialist.track(index)
            self.current_track_ref = first_track['track-ref']
            self.path.append(first_track['track-ref'])
            self.play_selected_track(first_track)
        else:
            self.mon.err(
                self, "first-track not found in medialist: " +
                self.show_params['first-track-ref'])
            self.end('error', "first track not found in medialist")

    def what_next(self):
        # user wants to end the show
        if self.end_hyperlinkshow_signal == True:
            self.end_hyperlinkshow_signal = False
            self.end('normal', "show ended by user")

        # user has selected another track
        elif self.next_track_signal == True:
            self.next_track_signal = False

            # home
            if self.next_track_op in ('home'):
                # back to 1 before home
                back_ref = self.path.back_to(self.home_track_ref)
                if back_ref == '':
                    self.mon.err(
                        self, "home - home track not in path: " +
                        self.home_track_ref)
                    self.end('error', "home - home track not in path")
                # play home
                self.next_track_ref = self.home_track_ref
                self.path.append(self.next_track_ref)

            # return-by
            elif self.next_track_op in ('return-by'):
                if self.current_track_ref <> self.home_track_ref:
                    # back n stopping at home
                    # back one more and return it
                    back_ref = self.path.back_by(self.home_track_ref,
                                                 self.next_track_arg)
                    # use returned track
                    self.next_track_ref = back_ref
                    self.path.append(self.next_track_ref)

            # return-to
            elif self.next_track_op in ('return-to'):
                #back to one before return-to track
                back_ref = self.path.back_to(self.next_track_arg)
                if back_ref == '':
                    self.mon.err(
                        self, "return-to - track not in path: " +
                        self.next_track_arg)
                    self.end('error', "return-to - track not in path")
                # and append the return to track
                self.next_track_ref = self.next_track_arg
                self.path.append(self.next_track_ref)

            # call
            elif self.next_track_op in ('call'):
                # append the required track
                self.path.append(self.next_track_arg)
                self.next_track_ref = self.next_track_arg

            # goto
            elif self.next_track_op in ('goto'):
                self.path.pop_for_sibling()
                ##                    #back to first track and remove it
                ##                    back_ref=self.path.back_to(self.first_track_ref)
                ##                    if back_ref=='':
                ##                        self.mon.err(self,"goto - first track not in path: "+self.first_track_ref)
                ##                        self.end('error',"goto - first track not in path")
                #add the goto track
                self.next_track_ref = self.next_track_arg
                self.path.append(self.next_track_arg)

            # jump
            elif self.next_track_op in ('jump'):
                # back to home and remove it
                back_ref = self.path.back_to(self.home_track_ref)
                if back_ref == '':
                    self.mon.err(
                        self, "jump - home track not in path: " +
                        self.home_track_ref)
                    self.end('error', "jump - track not in path")
                # add back the home track without playing it
                self.path.append(self.home_track_ref)
                # append the jumped to track
                self.next_track_ref = self.next_track_arg
                self.path.append(self.next_track_ref)

            else:
                self.mon.err(
                    self, "unaddressed what next: " + self.next_track_op +
                    ' ' + self.next_track_arg)
                self.end('error', "unaddressed what next")

            self.current_track_ref = self.next_track_ref
            index = self.medialist.index_of_track(self.next_track_ref)
            if index >= 0:
                #don't use select the track as not using selected_track in hyperlinkshow
                next_track = self.medialist.track(index)
                self.play_selected_track(next_track)
            else:
                self.mon.err(
                    self, "next-track not found in medialist: " +
                    self.next_track_ref)
                self.end('error', "next track not found in medialist")

        else:
            #track ends naturally
            #then input pp-onend symbolic name
            self.input_pressed('pp-onend', 'front', 'key')

# *********************
# Dispatching to Players
# *********************

    def page_callback(self):
        # called from a Player when ready to play, merge the links from the track with those from the show
        # and then enable the click areas
        self.delete_eggtimer()
        links_text = self.player.get_links()
        reason, message, track_links = self.path.parse_links(links_text)
        if reason == 'error':
            self.mon.err(self, message + " in page")
            self.end('error', message)
        self.path.merge_links(self.links, track_links)

        # enable the click-area that are in the list of links
        self.enable_click_areas()

    def enable_click_areas(self):
        for link in self.links:
            #print 'trying link ',link[0]
            if not ('key-'
                    in link[0]) and link[1] <> 'null' and link[0] <> 'pp-auto':
                # print 'enabling link ',link[0]
                self.canvas.itemconfig(link[0], state='normal')

    def play_selected_track(self, selected_track):
        """ selects the appropriate player from type field of the medialist and computes
              the parameters for that type
              selected track is a dictionary for the track/show
        """

        if self.timeout_running <> None:
            self.canvas.after_cancel(self.timeout_running)
            self.timeout_running = None

        # self.canvas.delete(ALL)
        self.display_eggtimer(self.resource('hyperlinkshow', 'm01'))

        self.current_track_type = selected_track['type']

        #read the show links. Track links will be added by ready_callback
        links_text = self.show_params['links']
        reason, message, self.links = self.path.parse_links(links_text)
        if reason == 'error':
            self.mon.err(self, message + " in show")
            self.end('error', message)

        #start timeout for the track if required

        if self.current_track_ref <> self.first_track_ref and int(
                self.show_params['timeout']) <> 0:
            self.timeout_running = self.canvas.after(
                int(self.show_params['timeout']) * 1000, self.timeout_callback)

        # dispatch track by type
        self.player = None
        self.shower = None
        track_type = selected_track['type']
        self.mon.log(self, "Track type is: " + track_type)

        if track_type == "video":
            # create a videoplayer
            track_file = self.complete_path(selected_track)
            self.player = VideoPlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.page_callback,
                             enable_menu=False)

        elif track_type == "audio":
            # create a audioplayer
            track_file = self.complete_path(selected_track)
            self.player = AudioPlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.page_callback,
                             enable_menu=False)

        elif track_type == "image":
            track_file = self.complete_path(selected_track)
            self.player = ImagePlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(
                track_file,
                self.showlist,
                self.end_player,
                self.page_callback,
                enable_menu=False,
            )

        elif track_type == "web":
            # create a browser
            track_file = self.complete_path(selected_track)
            self.player = BrowserPlayer(self.show_id, self.root, self.canvas,
                                        self.show_params, selected_track,
                                        self.pp_dir, self.pp_home,
                                        self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.page_callback,
                             enable_menu=False)

        elif track_type == "message":
            # bit odd because MessagePlayer is used internally to display text.
            text = selected_track['text']
            self.player = MessagePlayer(self.show_id, self.root, self.canvas,
                                        self.show_params, selected_track,
                                        self.pp_dir, self.pp_home,
                                        self.pp_profile)
            self.player.play(text,
                             self.showlist,
                             self.end_player,
                             self.page_callback,
                             enable_menu=False)

        elif track_type == "show":
            self.enable_click_areas()
            # get the show from the showlist
            index = self.showlist.index_of_show(selected_track['sub-show'])
            if index >= 0:
                self.showlist.select(index)
                selected_show = self.showlist.selected_show()
            else:
                self.mon.err(
                    self, "Show not found in showlist: " +
                    selected_track['sub-show'])
                self.end("Unknown show")

            if selected_show['type'] == "mediashow":
                self.shower = MediaShow(selected_show, self.root, self.canvas,
                                        self.showlist, self.pp_dir,
                                        self.pp_home, self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "liveshow":
                self.shower = LiveShow(selected_show, self.root, self.canvas,
                                       self.showlist, self.pp_dir,
                                       self.pp_home, self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "radiobuttonshow":
                self.shower = RadioButtonShow(selected_show, self.root,
                                              self.canvas, self.showlist,
                                              self.pp_dir, self.pp_home,
                                              self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "hyperlinkshow":
                self.shower = HyperlinkShow(selected_show, self.root,
                                            self.canvas, self.showlist, self,
                                            pp_dir, self.pp_home,
                                            self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "menu":
                self.shower = MenuShow(selected_show, self.root, self.canvas,
                                       self.showlist, self.pp_dir,
                                       self.pp_home, self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')
            else:
                self.mon.err(self,
                             "Unknown Show Type: " + selected_show['type'])
                self.end("Unknown show type")

        else:
            self.mon.err(self, "Unknown Track Type: " + track_type)
            self.end("Unknown track type")

    # callback from when player ends
    def end_player(self, reason, message):
        self.mon.log(self, "Returned from player with message: " + message)
        self.player = None
        # this does not seem to change the colour of the polygon
        self.canvas.itemconfig('pp-click-area', state='hidden')
        self.canvas.update_idletasks()
        if reason in ("killed", "error"):
            self.end(reason, message)
        else:
            self.display_eggtimer(self.resource('hyperlinkshow', 'm02'))
            self.what_next()

    # callback from when shower ends
    def end_shower(self, show_id, reason, message):
        self.mon.log(self, "Returned from shower with message: " + message)
        self.shower = None
        self.canvas.itemconfig('pp-click-area', state='hidden')
        self.canvas.update_idletasks()
        if reason in ("killed", "error"):
            self.end(reason, message)
        else:
            self.display_eggtimer(self.resource('hyperlinkshow', 'm03'))
            self.what_next()

# *********************
# End the show
# *********************
# finish the player for killing, error or normally
# this may be called directly sub/child shows or players are not running
# if they might be running then need to call terminate.

    def end(self, reason, message):
        self.mon.log(self,
                     "Ending hyperlinkshow: " + self.show_params['show-ref'])
        self.end_callback(self.show_id, reason, message)
        self = None
        return

# *********************
# displaying things
# *********************

    def display_eggtimer(self, text):
        #self.egg_timer=self.canvas.create_text(int(self.canvas['width'])/2,
        #int(self.canvas['height'])/2,
        #text= text,
        # fill='white',
        # font="Helvetica 20 bold")
        #self.canvas.update_idletasks( )
        pass

    def delete_eggtimer(self):
        if self.egg_timer != None:
            self.canvas.delete(self.egg_timer)


# *********************
# utilities
# *********************

    def complete_path(self, selected_track):
        #  complete path of the filename of the selected entry
        track_file = selected_track['location']
        if track_file <> '' and track_file[0] == "+":
            track_file = self.pp_home + track_file[1:]
        self.mon.log(self, "Track to play is: " + track_file)
        return track_file

    def resource(self, section, item):
        value = self.rr.get(section, item)
        if value == False:
            self.mon.err(self,
                         "resource: " + section + ': ' + item + " not found")
            # players or showers may be running so need terminate
            self.terminate("error")
        else:
            return value
Esempio n. 40
0
class PiPresents(object):
    def __init__(self):
        gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES
                     | gc.DEBUG_OBJECTS | gc.DEBUG_SAVEALL)
        self.pipresents_issue = "1.3"
        self.pipresents_minorissue = '1.3.1g'
        # position and size of window without -f command line option
        self.nonfull_window_width = 0.45  # proportion of width
        self.nonfull_window_height = 0.7  # proportion of height
        self.nonfull_window_x = 0  # position of top left corner
        self.nonfull_window_y = 0  # position of top left corner
        self.pp_background = 'black'

        StopWatch.global_enable = False

        # set up the handler for SIGTERM
        signal.signal(signal.SIGTERM, self.handle_sigterm)

        # ****************************************
        # Initialisation
        # ***************************************
        # get command line options
        self.options = command_options()

        # get Pi Presents code directory
        pp_dir = sys.path[0]
        self.pp_dir = pp_dir

        if not os.path.exists(pp_dir + "/pipresents.py"):
            if self.options['manager'] is False:
                tkMessageBox.showwarning(
                    "Pi Presents",
                    "Bad Application Directory:\n{0}".format(pp_dir))
            exit(103)

        # Initialise logging and tracing
        Monitor.log_path = pp_dir
        self.mon = Monitor()
        # Init in PiPresents only
        self.mon.init()

        # uncomment to enable control of logging from within a class
        # Monitor.enable_in_code = True # enables control of log level in the code for a class  - self.mon.set_log_level()

        # make a shorter list to log/trace only some classes without using enable_in_code.
        Monitor.classes = [
            'PiPresents', 'pp_paths', 'HyperlinkShow', 'RadioButtonShow',
            'ArtLiveShow', 'ArtMediaShow', 'MediaShow', 'LiveShow', 'MenuShow',
            'PathManager', 'ControlsManager', 'ShowManager', 'PluginManager',
            'MplayerDriver', 'OMXDriver', 'UZBLDriver', 'KbdDriver',
            'GPIODriver', 'TimeOfDay', 'ScreenDriver', 'Animate', 'OSCDriver'
        ]

        # Monitor.classes=['PiPresents','ArtMediaShow','VideoPlayer','OMXDriver']

        # get global log level from command line
        Monitor.log_level = int(self.options['debug'])
        Monitor.manager = self.options['manager']
        # print self.options['manager']
        self.mon.newline(3)
        self.mon.log(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue)
        # self.mon.log (self," OS and separator:" + os.name +'  ' + os.sep)
        self.mon.log(self, "sys.path[0] -  location of code: " + sys.path[0])
        if os.geteuid() != 0:
            user = os.getenv('USER')
        else:
            user = os.getenv('SUDO_USER')
        self.mon.log(self, 'User is: ' + user)
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME')) # does not work
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))   # does not work

        # optional other classes used
        self.root = None
        self.ppio = None
        self.tod = None
        self.animate = None
        self.gpiodriver = None
        self.oscdriver = None
        self.osc_enabled = False
        self.gpio_enabled = False
        self.tod_enabled = False

        # get home path from -o option
        self.pp_home = pp_paths.get_home(self.options['home'])
        if self.pp_home is None:
            self.end('error', 'Failed to find pp_home')

        # get profile path from -p option
        # pp_profile is the full path to the directory that contains
        # pp_showlist.json and other files for the profile
        self.pp_profile = pp_paths.get_profile_dir(self.pp_home,
                                                   self.options['profile'])
        if self.pp_profile is None:
            self.end('error', 'Failed to find profile')

        # check profile exists
        if os.path.exists(self.pp_profile):
            self.mon.log(
                self, "Found Requested profile - pp_profile directory is: " +
                self.pp_profile)
        else:
            self.mon.err(
                self, "Failed to find requested profile: " + self.pp_profile)
            self.end('error', 'Failed to find profile')

        self.mon.start_stats(self.options['profile'])

        # check 'verify' option
        if self.options['verify'] is True:
            val = Validator()
            if val.validate_profile(None, pp_dir, self.pp_home,
                                    self.pp_profile, self.pipresents_issue,
                                    False) is False:
                self.mon.err(self, "Validation Failed")
                self.end('error', 'Validation Failed')

        # initialise and read the showlist in the profile
        self.showlist = ShowList()
        self.showlist_file = self.pp_profile + "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self, "showlist not found at " + self.showlist_file)
            self.end('error', 'showlist not found')

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue()) != float(self.pipresents_issue):
            self.mon.err(
                self, "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents, must exit")
            self.end('error', 'wrong version of profile')

        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >= 0:
            self.showlist.select(index)
            self.starter_show = self.showlist.selected_show()
        else:
            self.mon.err(self, "Show [start] not found in showlist")
            self.end('error', 'start show not found')

        if self.starter_show['start-show'] == '':
            self.mon.warn(self, "No Start Shows in Start Show")

# ********************
# SET UP THE GUI
# ********************
# turn off the screenblanking and saver
        if self.options['noblank'] is True:
            call(["xset", "s", "off"])
            call(["xset", "s", "-dpms"])

        self.root = Tk()

        self.title = 'Pi Presents - ' + self.pp_profile
        self.icon_text = 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg=self.pp_background)

        self.mon.log(
            self, 'native screen dimensions are ' +
            str(self.root.winfo_screenwidth()) + ' x ' +
            str(self.root.winfo_screenheight()) + ' pixcels')
        if self.options['screensize'] == '':
            self.screen_width = self.root.winfo_screenwidth()
            self.screen_height = self.root.winfo_screenheight()
        else:
            reason, message, self.screen_width, self.screen_height = self.parse_screen(
                self.options['screensize'])
            if reason == 'error':
                self.mon.err(self, message)
                self.end('error', message)

        self.mon.log(
            self, 'commanded screen dimensions are ' + str(self.screen_width) +
            ' x ' + str(self.screen_height) + ' pixcels')

        # set window dimensions and decorations
        if self.options['fullscreen'] is False:
            self.window_width = int(self.root.winfo_screenwidth() *
                                    self.nonfull_window_width)
            self.window_height = int(self.root.winfo_screenheight() *
                                     self.nonfull_window_height)
            self.window_x = self.nonfull_window_x
            self.window_y = self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
        else:
            self.window_width = self.screen_width
            self.window_height = self.screen_height
            self.root.attributes('-fullscreen', True)
            os.system(
                'unclutter 1>&- 2>&- &'
            )  # Suppress 'someone created a subwindow' complaints from unclutter
            self.window_x = 0
            self.window_y = 0
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
            self.root.attributes('-zoomed', '1')

        # canvs cover the whole screen whatever the size of the window.
        self.canvas_height = self.screen_height
        self.canvas_width = self.screen_width

        # make sure focus is set.
        self.root.focus_set()

        # define response to main window closing.
        self.root.protocol("WM_DELETE_WINDOW", self.handle_user_abort)

        # setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg=self.pp_background)

        if self.options['fullscreen'] is True:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=0)
        else:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=1,
                               highlightcolor='yellow')

        self.canvas.place(x=0, y=0)
        # self.canvas.config(bg='black')
        self.canvas.focus_set()

        # ****************************************
        # INITIALISE THE INPUT DRIVERS
        # ****************************************

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd = KbdDriver()
        if kbd.read(pp_dir, self.pp_home, self.pp_profile) is False:
            self.end('error', 'cannot find or error in keys.cfg')
        kbd.bind_keys(self.root, self.handle_input_event)

        self.sr = ScreenDriver()
        # read the screen click area config file
        reason, message = self.sr.read(pp_dir, self.pp_home, self.pp_profile)
        if reason == 'error':
            self.end('error', 'cannot find screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        # click areas are made on the Pi Presents canvas not the show canvases.
        reason, message = self.sr.make_click_areas(self.canvas,
                                                   self.handle_input_event)
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required = False
        self.exitpipresents_required = False

        # kick off GPIO if enabled by command line option
        self.gpio_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'gpio.cfg'):
            # initialise the GPIO
            self.gpiodriver = GPIODriver()
            reason, message = self.gpiodriver.init(pp_dir, self.pp_home,
                                                   self.pp_profile,
                                                   self.canvas, 50,
                                                   self.handle_input_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.gpio_enabled = True
                # and start polling gpio
                self.gpiodriver.poll()

        # kick off animation sequencer
        self.animate = Animate()
        self.animate.init(pp_dir, self.pp_home, self.pp_profile, self.canvas,
                          200, self.handle_output_event)
        self.animate.poll()

        #create a showmanager ready for time of day scheduler and osc server
        show_id = -1
        self.show_manager = ShowManager(show_id, self.showlist,
                                        self.starter_show, self.root,
                                        self.canvas, self.pp_dir,
                                        self.pp_profile, self.pp_home)
        # first time through set callback to terminate Pi Presents if all shows have ended.
        self.show_manager.init(self.canvas, self.all_shows_ended_callback,
                               self.handle_command, self.showlist)
        # Register all the shows in the showlist
        reason, message = self.show_manager.register_shows()
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

        # Init OSCDriver, read config and start OSC server
        self.osc_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'osc.cfg'):
            self.oscdriver = OSCDriver()
            reason, message = self.oscdriver.init(
                self.pp_profile, self.handle_command, self.handle_input_event,
                self.e_osc_handle_output_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.osc_enabled = True
                self.root.after(1000, self.oscdriver.start_server())

        # and run the start shows
        self.run_start_shows()

        # set up the time of day scheduler including catchup
        self.tod_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'schedule.json'):
            # kick off the time of day scheduler which may run additional shows
            self.tod = TimeOfDay()
            self.tod.init(pp_dir, self.pp_home, self.pp_profile, self.root,
                          self.handle_command)
            self.tod_enabled = True

        # then start the time of day scheduler
        if self.tod_enabled is True:
            self.tod.poll()

        # start Tkinters event loop
        self.root.mainloop()

    def parse_screen(self, size_text):
        fields = size_text.split('*')
        if len(fields) != 2:
            return 'error', 'do not understand --fullscreen comand option', 0, 0
        elif fields[0].isdigit() is False or fields[1].isdigit() is False:
            return 'error', 'dimensions are not positive integers in ---fullscreen', 0, 0
        else:
            return 'normal', '', int(fields[0]), int(fields[1])

# *********************
#  RUN START SHOWS
# ********************

    def run_start_shows(self):
        self.mon.trace(self, 'run start shows')
        # parse the start shows field and start the initial shows
        show_refs = self.starter_show['start-show'].split()
        for show_ref in show_refs:
            reason, message = self.show_manager.control_a_show(
                show_ref, 'open')
            if reason == 'error':
                self.mon.err(self, message)

# *********************
# User inputs
# ********************
# handles one command provided as a line of text

    def handle_command(self, command_text):
        self.mon.log(self, "command received: " + command_text)
        if command_text.strip() == "":
            return

        if command_text[0] == '/':
            if self.osc_enabled is True:
                self.oscdriver.send_command(command_text)
            return

        fields = command_text.split()
        show_command = fields[0]
        if len(fields) > 1:
            show_ref = fields[1]
        else:
            show_ref = ''

        if show_command in ('open', 'close'):
            if self.shutdown_required is False:
                reason, message = self.show_manager.control_a_show(
                    show_ref, show_command)
            else:
                return
        elif show_command == 'exitpipresents':
            self.exitpipresents_required = True
            if self.show_manager.all_shows_exited() is True:
                # need root.after to get out of st thread
                self.root.after(1, self.e_all_shows_ended_callback)
                return
            else:
                reason, message = self.show_manager.exit_all_shows()

        elif show_command == 'shutdownnow':
            # need root.after to get out of st thread
            self.root.after(1, self.e_shutdown_pressed)
            return
        else:
            reason = 'error'
            message = 'command not recognised: ' + show_command

        if reason == 'error':
            self.mon.err(self, message)
        return

    def e_all_shows_ended_callback(self):
        self.all_shows_ended_callback('normal', 'no shows running')

    def e_shutdown_pressed(self):
        self.shutdown_pressed('now')

    def e_osc_handle_output_event(self, line):
        #jump  out of server thread
        self.root.after(1, lambda arg=line: self.osc_handle_output_event(arg))

    def osc_handle_output_event(self, line):
        self.mon.log(self, "output event received: " + line)
        #osc sends output events as a string
        reason, message, delay, name, param_type, param_values = self.animate.parse_animate_fields(
            line)
        if reason == 'error':
            self.mon.err(self, message)
            self.end(reason, message)
        self.handle_output_event(name, param_type, param_values, 0)

    def handle_output_event(self, symbol, param_type, param_values, req_time):
        if self.gpio_enabled is True:
            reason, message = self.gpiodriver.handle_output_event(
                symbol, param_type, param_values, req_time)
            if reason == 'error':
                self.mon.err(self, message)
                self.end(reason, message)
        else:
            self.mon.warn(self, 'GPIO not enabled')

    # all input events call this callback with a symbolic name.
    # handle events that affect PP overall, otherwise pass to all active shows
    def handle_input_event(self, symbol, source):
        self.mon.log(self, "event received: " + symbol + ' from ' + source)
        if symbol == 'pp-terminate':
            self.handle_user_abort()

        elif symbol == 'pp-shutdown':
            self.shutdown_pressed('delay')

        elif symbol == 'pp-shutdownnow':
            # need root.after to grt out of st thread
            self.root.after(1, self.e_shutdown_pressed)
            return

        elif symbol == 'pp-exitpipresents':
            self.exitpipresents_required = True
            if self.show_manager.all_shows_exited() is True:
                # need root.after to grt out of st thread
                self.root.after(1, self.e_all_shows_ended_callback)
                return
            reason, message = self.show_manager.exit_all_shows()
        else:
            # events for shows affect the show and could cause it to exit.
            for show in self.show_manager.shows:
                show_obj = show[ShowManager.SHOW_OBJ]
                if show_obj is not None:
                    show_obj.handle_input_event(symbol)

    def shutdown_pressed(self, when):
        if when == 'delay':
            self.root.after(5000, self.on_shutdown_delay)
        else:
            self.shutdown_required = True
            if self.show_manager.all_shows_exited() is True:
                self.all_shows_ended_callback('normal', 'no shows running')
            else:
                # calls exit method of all shows, results in all_shows_closed_callback
                self.show_manager.exit_all_shows()

    def on_shutdown_delay(self):
        # 5 second delay is up, if shutdown button still pressed then shutdown
        if self.gpiodriver.shutdown_pressed() is True:
            self.shutdown_required = True
            if self.show_manager.all_shows_exited() is True:
                self.all_shows_ended_callback('normal', 'no shows running')
            else:
                # calls exit method of all shows, results in all_shows_closed_callback
                self.show_manager.exit_all_shows()

    def handle_sigterm(self, signum, frame):
        self.mon.log(self, 'SIGTERM received - ' + str(signum))
        self.terminate()

    def handle_user_abort(self):
        self.mon.log(self, 'User abort received')
        self.terminate()

    def terminate(self):
        self.mon.log(self, "terminate received")
        needs_termination = False
        for show in self.show_manager.shows:
            # print  show[ShowManager.SHOW_OBJ], show[ShowManager.SHOW_REF]
            if show[ShowManager.SHOW_OBJ] is not None:
                needs_termination = True
                self.mon.log(
                    self,
                    "Sent terminate to show " + show[ShowManager.SHOW_REF])
                # call shows terminate method
                # eventually the show will exit and after all shows have exited all_shows_callback will be executed.
                show[ShowManager.SHOW_OBJ].terminate()
        if needs_termination is False:
            self.end('killed', 'killed - no termination of shows required')


# ******************************
# Ending Pi Presents after all the showers and players are closed
# **************************

# callback from ShowManager when all shows have ended

    def all_shows_ended_callback(self, reason, message):
        self.canvas.config(bg=self.pp_background)
        if reason in (
                'killed', 'error'
        ) or self.shutdown_required is True or self.exitpipresents_required is True:
            self.end(reason, message)

    def end(self, reason, message):
        self.mon.log(self, "Pi Presents ending with reason: " + reason)
        if self.root is not None:
            self.root.destroy()
        self.tidy_up()
        # gc.collect()
        # print gc.garbage
        if reason == 'killed':
            self.mon.log(self, "Pi Presents Aborted, au revoir")
            # close logging files
            self.mon.finish()
            sys.exit(101)
        elif reason == 'error':
            self.mon.log(self, "Pi Presents closing because of error, sorry")
            # close logging files
            self.mon.finish()
            sys.exit(102)
        else:
            self.mon.log(self, "Pi Presents  exiting normally, bye")
            # close logging files
            self.mon.finish()
            if self.shutdown_required is True:
                # print 'SHUTDOWN'
                call(['sudo', 'shutdown', '-h', '-t 5', 'now'])
                sys.exit(100)
            else:
                sys.exit(100)

    # tidy up all the peripheral bits of Pi Presents
    def tidy_up(self):
        self.mon.log(self, "Tidying Up")
        # turn screen blanking back on
        if self.options['noblank'] is True:
            call(["xset", "s", "on"])
            call(["xset", "s", "+dpms"])

        # tidy up animation and gpio
        if self.animate is not None:
            self.animate.terminate()

        if self.gpio_enabled == True:
            self.gpiodriver.terminate()

        if self.osc_enabled is True:
            self.oscdriver.terminate()

        # tidy up time of day scheduler
        if self.tod_enabled is True:
            self.tod.terminate()
Esempio n. 41
0
class LiveShow:
    """ plays a set of tracks the content of which is dynamically specified by plaacing track files
                in one of two directories. Tracks are played in file leafname alphabetical order.
                Can be interrupted
    """

    # *******************
    # External interface
    # ********************

    def __init__(self, show_params, root, canvas, showlist, pp_dir, pp_home,
                 pp_profile):

        self.mon = Monitor()
        self.mon.on()

        #instantiate arguments
        self.show_params = show_params
        self.showlist = showlist
        self.root = root
        self.canvas = canvas
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile

        # open resources
        self.rr = ResourceReader()

        #create and instance of TimeOfDay scheduler so we can add events
        self.tod = TimeOfDay()

        # Init variables
        self.player = None
        self.shower = None
        self.end_liveshow_signal = False
        self.end_trigger_signal = False
        self.play_child_signal = False
        self.error = False
        self.egg_timer = None
        self.duration_timer = None
        self.state = 'closed'
        self.livelist = None
        self.new_livelist = None

    def play(self,
             show_id,
             end_callback,
             ready_callback,
             top=False,
             command='nil'):

        #instantiate the arguments
        self.show_id = show_id
        self.end_callback = end_callback
        self.ready_callback = ready_callback
        self.top = top
        self.mon.log(self, "Starting show: " + self.show_params['show-ref'])

        # check  data files are available.
        self.media_file = self.pp_profile + os.sep + self.show_params[
            'medialist']
        if not os.path.exists(self.media_file):
            self.mon.err(self, "Medialist file not found: " + self.media_file)
            self.end_liveshow_signal = True

        self.options = command_options()

        self.pp_live_dir1 = self.pp_home + os.sep + 'pp_live_tracks'
        if not os.path.exists(self.pp_live_dir1):
            os.mkdir(self.pp_live_dir1)

        self.pp_live_dir2 = ''
        if self.options['liveshow'] <> "":
            self.pp_live_dir2 = self.options['liveshow']
            if not os.path.exists(self.pp_live_dir2):
                self.mon.err(
                    self,
                    "live tracks directory not found " + self.pp_live_dir2)
                self.end('error', "live tracks directory not found")

        #create a medialist for the liveshow and read it.
        # it should be empty of anonymous tracks but read it to check its version.
        self.medialist = MediaList()
        if self.medialist.open_list(self.media_file,
                                    self.showlist.sissue()) == False:
            self.mon.err(self, "Version of medialist different to Pi Presents")
            self.end('error', "Version of medialist different to Pi Presents")

        #get control bindings for this show if top level
        controlsmanager = ControlsManager()
        if self.top == True:
            self.controls_list = controlsmanager.default_controls()
            # and merge in controls from profile
            self.controls_list = controlsmanager.merge_show_controls(
                self.controls_list, self.show_params['controls'])

        #set up the time of day triggers for the show
        if self.show_params['trigger-start'] in ('time', 'time-quiet'):
            error_text = self.tod.add_times(
                self.show_params['trigger-start-time'], id(self),
                self.tod_start_callback, self.show_params['trigger-start'])
            if error_text <> '':
                self.mon.err(self, error_text)
                self.end('error', error_text)

        if self.show_params['trigger-end'] == 'time':
            error_text = self.tod.add_times(
                self.show_params['trigger-end-time'], id(self),
                self.tod_end_callback, 'n/a')
            if error_text <> '':
                self.mon.err(self, error_text)
                self.end('error', error_text)

        if self.show_params['trigger-end'] == 'duration':
            error_text = self.calculate_duration(
                self.show_params['trigger-end-time'])
            if error_text <> '':
                self.mon.err(self, error_text)
                self.end('error', error_text)

        self.wait_for_trigger()

    def managed_stop(self):
        # if next lower show eor player is running pass down to stop the show/track
        if self.shower <> None:
            self.shower.managed_stop()
        else:
            self.end_liveshow_signal = True
            if self.player <> None:
                self.player.input_pressed('stop')

    # kill or error
    def terminate(self, reason):
        if self.shower <> None:
            self.shower.terminate(reason)
        elif self.player <> None:
            self.player.terminate(reason)
        else:
            self.end(reason, 'terminated without terminating shower or player')

# respond to key presses.

    def input_pressed(self, symbol, edge, source):
        self.mon.log(self, "received key: " + symbol)
        if self.show_params['disable-controls'] == 'yes':
            return

    # if at top convert symbolic name to operation otherwise lower down we have received an operation
    # look through list of standard symbols to find match (symbolic-name, function name) operation =lookup (symbol
        if self.top == True:
            operation = self.lookup_control(symbol, self.controls_list)
        else:
            operation = symbol
        # print 'operation',operation
        # if no match for symbol against standard operations then return
        if operation == '':
            return

        else:
            #service the standard inputs for this show
            if operation == 'stop':
                # if next lower show eor player is running pass down to stop the show/track
                # ELSE stop this show except for exceptions
                if self.shower <> None:
                    self.shower.input_pressed('stop', edge, source)
                elif self.player <> None:
                    self.player.input_pressed('stop')
                else:
                    # not at top so stop the show
                    if self.top == False:
                        self.end_liveshow_signal = True
                    else:
                        pass

            elif operation in ('up', 'down'):
                # if child or sub-show is running and is a show pass to show, track does not use up/down
                if self.shower <> None:
                    self.shower.input_pressed(operation, edge, source)

            elif operation == 'play':
                # if child show or sub-show is running and is show - pass down
                # ELSE use Return to start child
                if self.shower <> None:
                    self.shower.input_pressed(operation, edge, source)
                else:
                    if self.show_params['has-child'] == "yes":
                        self.play_child_signal = True
                        if self.player <> None:
                            self.player.input_pressed("stop")

            elif operation == 'pause':
                # pass down if show or track running.
                if self.shower <> None:
                    self.shower.input_pressed(operation, edge, source)
                elif self.player <> None:
                    self.player.input_pressed(operation)

            elif operation[0:4] == 'omx-' or operation[0:6] == 'mplay-':
                if self.player <> None:
                    self.player.input_pressed(operation)

    def lookup_control(self, symbol, controls_list):
        for control in controls_list:
            if symbol == control[0]:
                return control[1]
        return ''

# ***************************
# Constructing Livelist
# ***************************

    def livelist_add_track(self, afile):
        (root, title) = os.path.split(afile)
        (root_plus, ext) = os.path.splitext(afile)
        if ext.lower() in PPdefinitions.IMAGE_FILES:
            self.livelist_new_track(PPdefinitions.new_tracks['image'], {
                'title': title,
                'track-ref': '',
                'location': afile
            })
        if ext.lower() in PPdefinitions.VIDEO_FILES:
            self.livelist_new_track(PPdefinitions.new_tracks['video'], {
                'title': title,
                'track-ref': '',
                'location': afile
            })
        if ext.lower() in PPdefinitions.AUDIO_FILES:
            self.livelist_new_track(PPdefinitions.new_tracks['audio'], {
                'title': title,
                'track-ref': '',
                'location': afile
            })
        if ext.lower() in PPdefinitions.WEB_FILES:
            self.livelist_new_track(PPdefinitions.new_tracks['web'], {
                'title': title,
                'track-ref': '',
                'location': afile
            })
        if ext.lower() == '.cfg':
            self.livelist_new_plugin(afile, title)

    def livelist_new_plugin(self, plugin_cfg, title):

        # read the file which is a plugin cfg file into a dictionary
        self.plugin_config = ConfigParser.ConfigParser()
        self.plugin_config.read(plugin_cfg)
        self.plugin_params = dict(self.plugin_config.items('plugin'))
        # create a new livelist entry of a type specified in the config file with plugin
        self.livelist_new_track(
            PPdefinitions.new_tracks[self.plugin_params['type']], {
                'title': title,
                'track-ref': '',
                'plugin': plugin_cfg,
                'location': plugin_cfg
            })

    def livelist_new_track(self, fields, values):
        new_track = fields
        self.new_livelist.append(copy.deepcopy(new_track))
        last = len(self.new_livelist) - 1
        self.new_livelist[last].update(values)

    def new_livelist_create(self):

        self.new_livelist = []
        if os.path.exists(self.pp_live_dir1):
            for file in os.listdir(self.pp_live_dir1):
                file = self.pp_live_dir1 + os.sep + file
                (root_file, ext_file) = os.path.splitext(file)
                if (ext_file.lower() in PPdefinitions.IMAGE_FILES +
                        PPdefinitions.VIDEO_FILES + PPdefinitions.AUDIO_FILES +
                        PPdefinitions.WEB_FILES) or (ext_file.lower()
                                                     == '.cfg'):
                    self.livelist_add_track(file)

        if os.path.exists(self.pp_live_dir2):
            for file in os.listdir(self.pp_live_dir2):
                file = self.pp_live_dir2 + os.sep + file
                (root_file, ext_file) = os.path.splitext(file)
                if ext_file.lower(
                ) in PPdefinitions.IMAGE_FILES + PPdefinitions.VIDEO_FILES + PPdefinitions.AUDIO_FILES + PPdefinitions.WEB_FILES or (
                        ext_file.lower() == '.cfg'):
                    self.livelist_add_track(file)

        self.new_livelist = sorted(
            self.new_livelist,
            key=lambda track: os.path.basename(track['location']).lower())
        # print 'LIVELIST'
        # for it in self.new_livelist:
        # print 'type: ', it['type'], 'loc: ',it['location'],'\nplugin cfg: ', it['plugin']
        # print ''

    def livelist_replace_if_changed(self):
        self.new_livelist_create()
        if self.new_livelist <> self.livelist:
            self.livelist = copy.deepcopy(self.new_livelist)
            self.livelist_index = 0

    def livelist_next(self):
        if self.livelist_index == len(self.livelist) - 1:
            self.livelist_index = 0
        else:
            self.livelist_index += 1

# ***************************
# Sequencing
# ***************************

    def wait_for_trigger(self):
        self.state = 'waiting'
        if self.ready_callback <> None:
            self.ready_callback()

        self.mon.log(
            self, "Waiting for trigger: " + self.show_params['trigger-start'])

        if self.show_params['trigger-start'] in ('time', 'time-quiet'):
            # if next show is this one display text
            next_show = self.tod.next_event_time()
            if next_show[3] <> True:
                if next_show[1] == 'tomorrow':
                    text = self.resource('liveshow', 'm04')
                else:
                    text = self.resource('liveshow', 'm03')
                text = text.replace('%tt', next_show[0])
                self.display_message(self.canvas, 'text', text, 0,
                                     self.play_first_track)

        elif self.show_params['trigger-start'] == "start":
            self.play_first_track()
        else:
            self.mon.err(
                self, "Unknown trigger: " + self.show_params['trigger-start'])
            self.end('error', "Unknown trigger type")

    # callbacks from time of day scheduler
    def tod_start_callback(self):
        if self.state == 'waiting' and self.show_params['trigger-start'] in (
                'time', 'time-quiet'):
            self.play_first_track()

    def tod_end_callback(self):
        if self.state == 'playing' and self.show_params['trigger-end'] in (
                'time', 'duration'):
            self.end_trigger_signal = True
            if self.shower <> None:
                self.shower.input_pressed('stop', 'front', '')
            elif self.player <> None:
                self.player.input_pressed('stop')

    def play_first_track(self):
        self.state = 'playing'
        # start duration timer
        if self.show_params['trigger-end'] == 'duration':
            # print 'set alarm ', self.duration
            self.duration_timer = self.canvas.after(self.duration * 1000,
                                                    self.tod_end_callback)
        self.new_livelist_create()
        self.livelist = copy.deepcopy(self.new_livelist)
        self.livelist_index = 0
        self.play_track()

    def play_track(self):
        self.livelist_replace_if_changed()
        if len(self.livelist) > 0:
            self.play_selected_track(self.livelist[self.livelist_index])
        else:
            self.display_message(self.canvas, None,
                                 self.resource('liveshow', 'm01'), 5,
                                 self.what_next)

    def what_next(self):
        # end of show time trigger
        if self.end_trigger_signal == True:
            self.end_trigger_signal = False
            if self.top == True:
                self.state = 'waiting'
                self.wait_for_trigger()
            else:
                # not at top so stop the show
                self.end('normal', 'sub-show end time trigger')

        # user wants to end
        elif self.end_liveshow_signal == True:
            self.end_liveshow_signal = False
            self.end('normal', "show ended by user")

        # play child?
        elif self.play_child_signal == True:
            self.play_child_signal = False
            index = self.medialist.index_of_track('pp-child-show')
            if index >= 0:
                #don't select the track as need to preserve mediashow sequence.
                child_track = self.medialist.track(index)
                self.display_eggtimer(self.resource('liveshow', 'm02'))
                self.play_selected_track(child_track)
            else:
                self.mon.err(
                    self, "Child show not found in medialist: " +
                    self.show_params['pp-child-show'])
                self.end('error', "child show not found in medialist")

        # otherwise loop to next track
        else:
            self.livelist_next()
            self.play_track()

# ***************************
# Dispatching to Players/Shows
# ***************************

    def ready_callback(self):
        self.delete_eggtimer()

    def play_selected_track(self, selected_track):
        """ selects the appropriate player from type field of the medialist and computes
              the parameters for that type
              selected_track is a dictionary for the track/show
        """
        self.canvas.delete('pp-content')

        # is menu required
        if self.show_params['has-child'] == "yes":
            enable_child = True
        else:
            enable_child = False

        #dispatch track by type
        self.player = None
        self.shower = None
        track_type = selected_track['type']
        self.mon.log(self, "Track type is: " + track_type)

        if track_type == "image":
            track_file = self.complete_path(selected_track)
            # images played from menus don't have children
            self.player = ImagePlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.ready_callback,
                             enable_menu=enable_child)

        elif track_type == "video":
            # create a videoplayer
            track_file = self.complete_path(selected_track)
            self.player = VideoPlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.ready_callback,
                             enable_menu=enable_child)

        elif track_type == "audio":
            # create a audioplayer
            track_file = self.complete_path(selected_track)
            self.player = AudioPlayer(self.show_id, self.root, self.canvas,
                                      self.show_params, selected_track,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.ready_callback,
                             enable_menu=enable_child)

        elif track_type == "message":
            # bit odd because MessagePlayer is used internally to display text.
            text = selected_track['text']
            self.player = MessagePlayer(self.show_id, self.root, self.canvas,
                                        self.show_params, selected_track,
                                        self.pp_dir, self.pp_home,
                                        self.pp_profile)
            self.player.play(text,
                             self.showlist,
                             self.end_player,
                             self.ready_callback,
                             enable_menu=enable_child)

        elif track_type == "web":
            # create a browser
            track_file = self.complete_path(selected_track)
            self.player = BrowserPlayer(self.show_id, self.root, self.canvas,
                                        self.show_params, selected_track,
                                        self.pp_dir, self.pp_home,
                                        self.pp_profile)
            self.player.play(track_file,
                             self.showlist,
                             self.end_player,
                             self.ready_callback,
                             enable_menu=enable_child)

        elif track_type == "show":
            # get the show from the showlist
            index = self.showlist.index_of_show(selected_track['sub-show'])
            if index >= 0:
                self.showlist.select(index)
                selected_show = self.showlist.selected_show()
            else:
                self.mon.err(
                    self, "Show not found in showlist: " +
                    selected_track['sub-show'])
                self.end_liveshow_signal = True

            if selected_show['type'] == "mediashow":
                self.shower = MediaShow(selected_show, self.root, self.canvas,
                                        self.showlist, self.pp_dir,
                                        self.pp_home, self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "menu":
                self.shower = MenuShow(selected_show, self.root, self.canvas,
                                       self.showlist, self.pp_dir,
                                       self.pp_home, self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "radiobuttonshow":
                self.shower = RadioButtonShow(selected_show, self.root,
                                              self.canvas, self.showlist,
                                              self.pp_dir, self.pp_home,
                                              self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            elif selected_show['type'] == "hyperlinkshow":
                self.shower = HyperlinkShow(selected_show, sef.root,
                                            self.canvas, self.showlist,
                                            self.pp_dir, self.pp_home,
                                            self.pp_profile)
                self.shower.play(self.show_id,
                                 self.end_shower,
                                 self.ready_callback,
                                 top=False,
                                 command='nil')

            else:
                self.mon.err(self,
                             "Unknown Show Type: " + selected_show['type'])
                self.end_liveshow_signal = True

        else:
            self.mon.err(self, "Unknown Track Type: " + track_type)
            self.end_liveshow_signal = True

    def end_shower(self, show_id, reason, message):
        self.mon.log(self, "Returned from shower with message: " + message)
        self.shower = None
        if reason in ("killed", "error"):
            self.end(reason, message)
        else:
            self.what_next()

    def end_player(self, reason, message):
        self.mon.log(self, "Returned from player with message: " + message)
        self.player = None
        if reason in ("killed", "error"):
            self.end(reason, message)
        else:
            self.what_next()

# ***************************
# end of show
# ***************************

    def end(self, reason, message):
        self.end_liveshow_signal = False
        self.mon.log(self, "Ending Liveshow: " + self.show_params['show-ref'])
        self.tidy_up()
        self.end_callback(self.show_id, reason, message)
        self = None

    def tidy_up(self):
        if self.duration_timer <> None:
            self.canvas.after_cancel(self.duration_timer)
            self.duration_timer = None
        #clear outstanding time of day events for this show
        # self.tod.clear_times_list(id(self))

# ******************************
# Displaying things
# *********************************

    def display_eggtimer(self, text):
        self.egg_timer = self.canvas.create_text(int(self.canvas['width']) / 2,
                                                 int(self.canvas['height']) /
                                                 2,
                                                 text=text,
                                                 fill='white',
                                                 font="Helvetica 20 bold",
                                                 tag='pp-eggtimer')
        self.canvas.update_idletasks()

    def delete_eggtimer(self):
        self.canvas.delete('pp-eggtimer')
        self.canvas.update_idletasks()

    # used to display internal messages in situations where a medialist entry could not be used.
    def display_message(self, canvas, source, content, duration,
                        display_message_callback):
        self.display_message_callback = display_message_callback
        tp = {
            'duration': duration,
            'message-colour': 'white',
            'message-font': 'Helvetica 20 bold',
            'message-justify': 'left',
            'background-colour': '',
            'background-image': '',
            'show-control-begin': '',
            'show-control-end': '',
            'animate-begin': '',
            'animate-clear': '',
            'animate-end': '',
            'message-x': '',
            'message-y': '',
            'display-show-background': 'no',
            'display-show-text': 'no',
            'show-text': '',
            'track-text': '',
            'plugin': ''
        }
        self.player = MessagePlayer(self.show_id, self.root, canvas, tp, tp,
                                    self.pp_dir, self.pp_home, self.pp_profile)
        self.player.play(content, self.showlist, self.display_message_end,
                         None)

    def display_message_end(self, reason, message):
        self.player = None
        if reason in ("killed", 'error'):
            self.end(reason, message)
        else:
            self.display_message_callback()


# ******************************
# utilities
# *********************************

    def resource(self, section, item):
        value = self.rr.get(section, item)
        if value == False:
            self.mon.err(self,
                         "resource: " + section + ': ' + item + " not found")
            self.terminate("error", 'Cannot find resource')
        else:
            return value

    def complete_path(self, selected_track):
        #  complete path of the filename of the selected entry
        track_file = selected_track['location']
        if track_file <> '' and track_file[0] == "+":
            track_file = self.pp_home + track_file[1:]
        self.mon.log(self, "Track to play is: " + track_file)
        return track_file

    def calculate_duration(self, line):
        fields = line.split(':')
        if len(fields) == 1:
            secs = fields[0]
            minutes = '0'
            hours = '0'
        if len(fields) == 2:
            secs = fields[1]
            minutes = fields[0]
            hours = '0'
        if len(fields) == 3:
            secs = fields[2]
            minutes = fields[1]
            hours = fields[0]
        self.duration = 3600 * long(hours) + 60 * long(minutes) + long(secs)
        return ''
Esempio n. 42
0
    def __init__(self):
        
        self.pipresents_issue="1.2"
        self.pipresents_minorissue = '1.2.3e'
        self.nonfull_window_width = 0.5 # proportion of width
        self.nonfull_window_height= 0.6 # proportion of height
        self.nonfull_window_x = 0 # position of top left corner
        self.nonfull_window_y=0   # position of top left corner
        
        StopWatch.global_enable=False

#****************************************
# Initialisation
# ***************************************
        # get command line options
        self.options=command_options()

        # get pi presents code directory
        pp_dir=sys.path[0]
        self.pp_dir=pp_dir
        
        if not os.path.exists(pp_dir+"/pipresents.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()

        
        #Initialise logging
        Monitor.log_path=pp_dir
        self.mon=Monitor()
        self.mon.on()
        # 0  - errors only
        # 1  - errors and warnings
        # 2  - everything
        if self.options['debug']==True:
            Monitor.global_enable=2
        else:
            Monitor.global_enable=0
            
        # UNCOMMENT THIS TO LOG WARNINGS AND ERRORS ONLY
        # Monitor.global_enable=1

        self.mon.log (self, "\n\n\n\n\n*****************\nPi Presents is starting, Version:"+self.pipresents_minorissue)
        self.mon.log (self, "Version: " + self.pipresents_minorissue)
	self.mon.log (self," OS and separator:" + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: "+sys.path[0])
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME'))
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))

        # optional other classes used
        self.ppio=None
        self.tod=None
         
        #get profile path from -p option
        if self.options['profile']<>"":
            self.pp_profile_path="/pp_profiles/"+self.options['profile']
        else:
            self.pp_profile_path = "/pp_profiles/pp_profile"
        
       #get directory containing pp_home from the command,
        if self.options['home'] =="":
            home = os.path.expanduser('~')+ os.sep+"pp_home"
        else:
            home = self.options['home'] + os.sep+ "pp_home"         
        self.mon.log(self,"pp_home directory is: " + home)
        
        #check if pp_home exists.
        # try for 10 seconds to allow usb stick to automount
        # fall back to pipresents/pp_home
        self.pp_home=pp_dir+"/pp_home"
        found=False
        for i in range (1, 10):
            self.mon.log(self,"Trying pp_home at: " + home +  " (" + str(i)+')')
            if os.path.exists(home):
                found=True
                self.pp_home=home
                break
            time.sleep (1)
        if found==True:
            self.mon.log(self,"Found Requested Home Directory, using pp_home at: " + home)
        else:    
            self.mon.log(self,"FAILED to find requested home directory, using default to display error message: " + self.pp_home)


        #check profile exists, if not default to error profile inside pipresents
        self.pp_profile=self.pp_home+self.pp_profile_path
        if os.path.exists(self.pp_profile):
            self.mon.log(self,"Found Requested profile - pp_profile directory is: " + self.pp_profile)
        else:
            self.pp_profile=pp_dir+"/pp_home/pp_profiles/pp_profile"   
            self.mon.log(self,"FAILED to find requested profile, using default to display error message: pp_profile")
        
        if self.options['verify']==True:
            val =Validator()
            if  val.validate_profile(None,pp_dir,self.pp_home,self.pp_profile,self.pipresents_issue,False) == False:
                tkMessageBox.showwarning("Pi Presents","Validation Failed")
                exit()
                
        # open the resources
        self.rr=ResourceReader()
        # read the file, done once for all the other classes to use.
        if self.rr.read(pp_dir,self.pp_home,self.pp_profile)==False:
            self.end('error','cannot find resources.cfg')            

        #initialise and read the showlist in the profile
        self.showlist=ShowList()
        self.showlist_file= self.pp_profile+ "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self,"showlist not found at "+self.showlist_file)
            self.end('error','showlist not found')

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue())<>float(self.pipresents_issue):
            self.mon.err(self,"Version of profile " + self.showlist.sissue() + " is not  same as Pi Presents, must exit")
            self.end('error','wrong version of profile')
 
        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >=0:
            self.showlist.select(index)
            self.starter_show=self.showlist.selected_show()
        else:
            self.mon.err(self,"Show [start] not found in showlist")
            self.end('error','start show not found')

        
# ********************
# SET UP THE GUI
# ********************
        #turn off the screenblanking and saver
        if self.options['noblank']==True:
            call(["xset","s", "off"])
            call(["xset","s", "-dpms"])

        self.root=Tk()   
       
        self.title='Pi Presents - '+ self.pp_profile
        self.icon_text= 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg='black')
        
        # get size of the screen
        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()

        # set window dimensions and decorations
        if self.options['fullscreen']==True:

            self.root.attributes('-fullscreen', True)
            os.system('unclutter &')
            self.window_width=self.screen_width
            self.window_height=self.screen_height
            self.window_x=0
            self.window_y=0  
            self.root.geometry("%dx%d%+d%+d"  % (self.window_width,self.window_height,self.window_x,self.window_y))
            self.root.attributes('-zoomed','1')
        else:
            self.window_width=int(self.screen_width*self.nonfull_window_width)
            self.window_height=int(self.screen_height*self.nonfull_window_height)
            self.window_x=self.nonfull_window_x
            self.window_y=self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" % (self.window_width,self.window_height,self.window_x,self.window_y))

            
        #canvas covers the whole window
        self.canvas_height=self.screen_height
        self.canvas_width=self.screen_width
        
        # make sure focus is set.
        self.root.focus_set()

        #define response to main window closing.
        self.root.protocol ("WM_DELETE_WINDOW", self.exit_pressed)

        #setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg='black')

        self.canvas.config(height=self.canvas_height,
                                       width=self.canvas_width,
                                       highlightthickness=0)
        # self.canvas.pack()
        self.canvas.place(x=0,y=0)

        self.canvas.focus_set()

                
# ****************************************
# INITIALISE THE INPUT DRIVERS
# ****************************************

        # looks after bindings between symbolic names and internal operations
        controlsmanager=ControlsManager()
        if controlsmanager.read(pp_dir,self.pp_home,self.pp_profile)==False:
                self.end('error','cannot find or error in controls.cfg.cfg')
        else:
            controlsmanager.parse_defaults()

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd=KbdDriver()
        if kbd.read(pp_dir,self.pp_home,self.pp_profile)==False:
                self.end('error','cannot find or error in keys.cfg')
        kbd.bind_keys(self.root,self.input_pressed)

        self.sr=ScreenDriver()
        # read the screen click area config file
        if self.sr.read(pp_dir,self.pp_home,self.pp_profile)==False:
            self.end('error','cannot find screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        reason,message = self.sr.make_click_areas(self.canvas,self.input_pressed)
        if reason=='error':
            self.mon.err(self,message)
            self.end('error',message)


# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required=False
        
        #kick off GPIO if enabled by command line option
        if self.options['gpio']==True:
            from pp_gpio import PPIO
            # initialise the GPIO
            self.ppio=PPIO()
            # PPIO.gpio_enabled=False
            if self.ppio.init(pp_dir,self.pp_home,self.pp_profile,self.canvas,50,self.gpio_pressed)==False:
                self.end('error','gpio error')
                
            # and start polling gpio
            self.ppio.poll()

        #kick off the time of day scheduler
        self.tod=TimeOfDay()
        self.tod.init(pp_dir,self.pp_home,self.canvas,500)
        self.tod.poll()


        # Create list of start shows initialise them and then run them
        self.run_start_shows()

        #start tkinter
        self.root.mainloop( )
Esempio n. 43
0
class PiPresents:
    def __init__(self):

        self.pipresents_issue = "1.2"
        self.pipresents_minorissue = '1.2.3f'
        self.nonfull_window_width = 0.5  # proportion of width
        self.nonfull_window_height = 0.6  # proportion of height
        self.nonfull_window_x = 0  # position of top left corner
        self.nonfull_window_y = 0  # position of top left corner

        StopWatch.global_enable = False

        #****************************************
        # Initialisation
        # ***************************************
        # get command line options
        self.options = command_options()

        # get pi presents code directory
        pp_dir = sys.path[0]
        self.pp_dir = pp_dir

        if not os.path.exists(pp_dir + "/pipresents.py"):
            tkMessageBox.showwarning("Pi Presents",
                                     "Bad Application Directory")
            exit()

        #Initialise logging
        Monitor.log_path = pp_dir
        self.mon = Monitor()
        self.mon.on()
        # 0  - errors only
        # 1  - errors and warnings
        # 2  - everything
        if self.options['debug'] == True:
            Monitor.global_enable = 2
        else:
            Monitor.global_enable = 0

        # UNCOMMENT THIS TO LOG WARNINGS AND ERRORS ONLY
        # Monitor.global_enable=1

        self.mon.log(
            self,
            "\n\n\n\n\n*****************\nPi Presents is starting, Version:" +
            self.pipresents_minorissue)
        self.mon.log(self, "Version: " + self.pipresents_minorissue)
        self.mon.log(self, " OS and separator:" + os.name + '  ' + os.sep)
        self.mon.log(self, "sys.path[0] -  location of code: " + sys.path[0])
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME'))
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))

        # optional other classes used
        self.ppio = None
        self.tod = None

        #get profile path from -p option
        if self.options['profile'] <> "":
            self.pp_profile_path = "/pp_profiles/" + self.options['profile']
        else:
            self.pp_profile_path = "/pp_profiles/pp_profile"

    #get directory containing pp_home from the command,
        if self.options['home'] == "":
            home = os.path.expanduser('~') + os.sep + "pp_home"
        else:
            home = self.options['home'] + os.sep + "pp_home"
        self.mon.log(self, "pp_home directory is: " + home)

        #check if pp_home exists.
        # try for 10 seconds to allow usb stick to automount
        # fall back to pipresents/pp_home
        self.pp_home = pp_dir + "/pp_home"
        found = False
        for i in range(1, 10):
            self.mon.log(self,
                         "Trying pp_home at: " + home + " (" + str(i) + ')')
            if os.path.exists(home):
                found = True
                self.pp_home = home
                break
            time.sleep(1)
        if found == True:
            self.mon.log(
                self,
                "Found Requested Home Directory, using pp_home at: " + home)
        else:
            self.mon.log(
                self,
                "FAILED to find requested home directory, using default to display error message: "
                + self.pp_home)

        #check profile exists, if not default to error profile inside pipresents
        self.pp_profile = self.pp_home + self.pp_profile_path
        if os.path.exists(self.pp_profile):
            self.mon.log(
                self, "Found Requested profile - pp_profile directory is: " +
                self.pp_profile)
        else:
            self.pp_profile = pp_dir + "/pp_home/pp_profiles/pp_profile"
            self.mon.log(
                self,
                "FAILED to find requested profile, using default to display error message: pp_profile"
            )

        if self.options['verify'] == True:
            val = Validator()
            if val.validate_profile(None, pp_dir, self.pp_home,
                                    self.pp_profile, self.pipresents_issue,
                                    False) == False:
                tkMessageBox.showwarning("Pi Presents", "Validation Failed")
                exit()

        # open the resources
        self.rr = ResourceReader()
        # read the file, done once for all the other classes to use.
        if self.rr.read(pp_dir, self.pp_home, self.pp_profile) == False:
            self.end('error', 'cannot find resources.cfg')

        #initialise and read the showlist in the profile
        self.showlist = ShowList()
        self.showlist_file = self.pp_profile + "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self, "showlist not found at " + self.showlist_file)
            self.end('error', 'showlist not found')

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue()) <> float(self.pipresents_issue):
            self.mon.err(
                self, "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents, must exit")
            self.end('error', 'wrong version of profile')

        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >= 0:
            self.showlist.select(index)
            self.starter_show = self.showlist.selected_show()
        else:
            self.mon.err(self, "Show [start] not found in showlist")
            self.end('error', 'start show not found')

# ********************
# SET UP THE GUI
# ********************
#turn off the screenblanking and saver
        if self.options['noblank'] == True:
            call(["xset", "s", "off"])
            call(["xset", "s", "-dpms"])

        self.root = Tk()

        self.title = 'Pi Presents - ' + self.pp_profile
        self.icon_text = 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg='black')

        # get size of the screen
        self.screen_width = self.root.winfo_screenwidth()
        self.screen_height = self.root.winfo_screenheight()

        # set window dimensions and decorations
        if self.options['fullscreen'] == True:

            self.root.attributes('-fullscreen', True)
            os.system('unclutter &')
            self.window_width = self.screen_width
            self.window_height = self.screen_height
            self.window_x = 0
            self.window_y = 0
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
            self.root.attributes('-zoomed', '1')
        else:
            self.window_width = int(self.screen_width *
                                    self.nonfull_window_width)
            self.window_height = int(self.screen_height *
                                     self.nonfull_window_height)
            self.window_x = self.nonfull_window_x
            self.window_y = self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))

        #canvas covers the whole window
        self.canvas_height = self.screen_height
        self.canvas_width = self.screen_width

        # make sure focus is set.
        self.root.focus_set()

        #define response to main window closing.
        self.root.protocol("WM_DELETE_WINDOW", self.exit_pressed)

        #setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg='black')

        self.canvas.config(height=self.canvas_height,
                           width=self.canvas_width,
                           highlightthickness=0)
        # self.canvas.pack()
        self.canvas.place(x=0, y=0)

        self.canvas.focus_set()

        # ****************************************
        # INITIALISE THE INPUT DRIVERS
        # ****************************************

        # looks after bindings between symbolic names and internal operations
        controlsmanager = ControlsManager()
        if controlsmanager.read(pp_dir, self.pp_home,
                                self.pp_profile) == False:
            self.end('error', 'cannot find or error in controls.cfg.cfg')
        else:
            controlsmanager.parse_defaults()

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd = KbdDriver()
        if kbd.read(pp_dir, self.pp_home, self.pp_profile) == False:
            self.end('error', 'cannot find or error in keys.cfg')
        kbd.bind_keys(self.root, self.input_pressed)

        self.sr = ScreenDriver()
        # read the screen click area config file
        if self.sr.read(pp_dir, self.pp_home, self.pp_profile) == False:
            self.end('error', 'cannot find screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        reason, message = self.sr.make_click_areas(self.canvas,
                                                   self.input_pressed)
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required = False

        #kick off GPIO if enabled by command line option
        if self.options['gpio'] == True:
            from pp_gpio import PPIO
            # initialise the GPIO
            self.ppio = PPIO()
            # PPIO.gpio_enabled=False
            if self.ppio.init(pp_dir, self.pp_home, self.pp_profile,
                              self.canvas, 50, self.gpio_pressed) == False:
                self.end('error', 'gpio error')

            # and start polling gpio
            self.ppio.poll()

        #kick off the time of day scheduler
        self.tod = TimeOfDay()
        self.tod.init(pp_dir, self.pp_home, self.canvas, 500)
        self.tod.poll()

        # Create list of start shows initialise them and then run them
        self.run_start_shows()

        #start tkinter
        self.root.mainloop()

# *********************
#  RUN START SHOWS
# ********************

    def run_start_shows(self):
        #start show manager
        show_id = -1  #start show
        self.show_manager = ShowManager(show_id, self.showlist,
                                        self.starter_show, self.root,
                                        self.canvas, self.pp_dir,
                                        self.pp_profile, self.pp_home)

        #first time through so empty show register and set callback to terminate Pi Presents if all shows have ended.
        self.show_manager.init(self.all_shows_ended_callback)

        #parse the start shows field and start the initial shows
        start_shows_text = self.starter_show['start-show']
        self.show_manager.start_initial_shows(start_shows_text)

    #callback from ShowManager when all shows have ended
    def all_shows_ended_callback(self, reason, message, force_shutdown):
        self.mon.log(self, "All shows ended, so terminate Pi Presents")
        if force_shutdown == True:
            self.shutdown_required = True
            self.mon.log(self, "shutdown forced by profile")
            self.terminate('killed')
        else:
            self.end(reason, message)

# *********************
# User inputs
# ********************

#gpio callback - symbol provided by gpio

    def gpio_pressed(self, index, symbol, edge):
        self.mon.log(self, "GPIO Pressed: " + symbol)
        self.input_pressed(symbol, edge, 'gpio')

    # all input events call this callback with a symbolic name.
    def input_pressed(self, symbol, edge, source):
        self.mon.log(self, "input received: " + symbol)
        if symbol == 'pp-exit':
            self.exit_pressed()
        elif symbol == 'pp-shutdown':
            self.shutdown_pressed('delay')
        elif symbol == 'pp-shutdownnow':
            self.shutdown_pressed('now')
        else:
            for show in self.show_manager.shows:
                show_obj = show[ShowManager.SHOW_OBJ]
                if show_obj <> None:
                    show_obj.input_pressed(symbol, edge, source)

# **************************************
# respond to exit inputs by terminating
# **************************************

    def shutdown_pressed(self, when):
        if when == 'delay':
            self.root.after(5000, self.on_shutdown_delay)
        else:
            self.shutdown_required = True
            self.exit_pressed()

    def on_shutdown_delay(self):
        if self.ppio.shutdown_pressed():
            self.shutdown_required = True
            self.exit_pressed()

    def exit_pressed(self):
        self.mon.log(self, "kill received from user")
        #terminate any running shows and players
        self.mon.log(self, "kill sent to shows")
        self.terminate('killed')

    # kill or error
    def terminate(self, reason):
        needs_termination = False
        for show in self.show_manager.shows:
            if show[ShowManager.SHOW_OBJ] <> None:
                needs_termination = True
                self.mon.log(
                    self,
                    "Sent terminate to show " + show[ShowManager.SHOW_REF])
                show[ShowManager.SHOW_OBJ].terminate(reason)
        if needs_termination == False:
            self.end(reason,
                     'terminate - no termination of lower levels required')

# ******************************
# Ending Pi Presents after all the showers and players are closed
# **************************

    def end(self, reason, message):
        self.mon.log(
            self, "Pi Presents ending with message: " + reason + ' ' + message)
        if reason == 'error':
            self.tidy_up()
            self.mon.log(self, "exiting because of error")
            #close logging files
            self.mon.finish()
            exit()
        else:
            self.tidy_up()
            self.mon.log(self, "no error - exiting normally")
            #close logging files
            self.mon.finish()
            if self.shutdown_required == True:
                # call(['sudo', 'shutdown', '-h', '-t 5','now'])
                call(['sudo', 'shutdown', '-h', 'now'])
                exit()
            else:
                exit()

    # tidy up all the peripheral bits of Pi Presents
    def tidy_up(self):
        #turn screen blanking back on
        if self.options['noblank'] == True:
            call(["xset", "s", "on"])
            call(["xset", "s", "+dpms"])

        # tidy up gpio
        if self.options['gpio'] == True and self.ppio <> None:
            self.ppio.terminate()

        #tidy up time of day scheduler
        if self.tod <> None:
            self.tod.terminate()


# *****************************
# utilitities
# ****************************

    def resource(self, section, item):
        value = self.rr.get(section, item)
        if value == False:
            self.mon.err(self,
                         "resource: " + section + ': ' + item + " not found")
            self.terminate("error")
        else:
            return value
Esempio n. 44
0
 def __init__(self,sequence):
     self.clear()
     self.mon=Monitor()
     self.mon.on()
     self.sequence = sequence
     self.mon.log(self, "sequence is " + self.sequence)
Esempio n. 45
0
class OMXDriver(object):

    _STATUS_REXP = re.compile(r"M:\s*(\w*)\s*V:")
    _DONE_REXP = re.compile(r"have a nice day.*")

    _LAUNCH_CMD = '/usr/bin/omxplayer -s '  #needs changing if user has installed his own version of omxplayer elsewhere

    def __init__(self,widget):

        self.widget=widget
        
        self.mon=Monitor()
        self.mon.on()
        
        self.paused=None

        self._process=None

    def control(self,char):
        self._process.send(char)

    def pause(self):
        self._process.send('p')       
        if not self.paused:
            self.paused = True
        else:
            self.paused=False

    def play(self, track, options):
        self._pp(track, options,False)

    def prepare(self, track, options):
        self._pp(track, options,True)
    
    def show(self):
        # unpause to start playing
        self._process.send('p')
        self.paused = False

    def stop(self):
        if self._process<>None:
            self._process.send('q')

    # kill the subprocess (omxplayer.bin). Used for tidy up on exit.
    def terminate(self,reason):
        self.terminate_reason=reason
        if self._process<>None:
            self._process.send('q')
        
    def terminate_reason(self):
        return self.terminate_reason
    

   # test of whether _process is running
    def is_running(self):
        return self._process.isalive()
    
     # kill of omxplayer when it hasn't terminated at the end of a track.
    def kill(self):
        killed = self._process.terminate(force=True)
        os.system('killall omxplayer.bin')
        return killed

# ***********************************
# INTERNAL FUNCTIONS
# ************************************

    def _pp(self, track, options,  pause_before_play):
        self.paused=False
        self.start_play_signal = False
        self.end_play_signal=False
        self.terminate_reason=''
        track= "'"+ track.replace("'","'\\''") + "'"
        cmd = OMXDriver._LAUNCH_CMD + options +" " + track
        self.mon.log(self, "Send command to omxplayer: "+ cmd)
        self._process = pexpect.spawn(cmd)

        # uncomment to monitor output to and input from omxplayer.bin (read pexpect manual)
        fout= file('omxlogfile.txt','w')  #uncomment and change sys.stdout to fout to log to a file
        # self._process.logfile_send = sys.stdout  # send just commands to stdout
        self._process.logfile=fout  # send all communications to log file

        if pause_before_play:
            self._process.send('p')
            self.paused = True
            
        #start the thread that is going to monitor sys.stdout. Presumably needs a thread because of blocking
        self._position_thread = Thread(target=self._get_position)
        self._position_thread.start()

    def _get_position(self):
        self.start_play_signal = True  

        self.video_position=0.0
        self.audio_position=0.0
        
        while True:
            index = self._process.expect([OMXDriver._DONE_REXP,
                                            pexpect.TIMEOUT,
                                            pexpect.EOF,
                                          OMXDriver._STATUS_REXP]
                                            ,timeout=10)
            if index == 1:     #timeout omxplayer should not do this
                self.end_play_signal=True
                self.xbefore=self._process.before
                self.xafter=self._process.after
                self.match=self._process.match
                self.end_play_reason='timeout'
                break
                # continue
            elif index == 2:       #2 is eof omxplayer should not send this
                #eof detected
                self.end_play_signal=True
                self.xbefore=self._process.before
                self.xafter=self._process.after
                self.match=self._process.match
                self.end_play_reason='eof'
                break
            elif index==0:    #0 is done
                #Have a nice day detected
                self.end_play_signal=True
                self.xbefore=self._process.before
                self.xafter=self._process.after
                self.match=self._process.match
                self.end_play_reason='nice_day'
                break            
            else:
                #  - 3 matches _STATUS_REXP so get time stamp
                self.video_position = float(self._process.match.group(1))
                self.audio_position = 0.0             
            #sleep is Ok here as it is a seperate thread. self.widget.after has funny effects as its not in the maion thread.
            sleep(0.05)   # stats output rate seem to be about 170mS.
Esempio n. 46
0
class MediaList:
    """
    manages a media list of tracks and the track selected from the medialist
    """
    

    def __init__(self,sequence):
        self.clear()
        self.mon=Monitor()
        self.mon.on()
        self.sequence = sequence
        self.mon.log(self, "sequence is " + self.sequence)

 # Functions for the editor dealing with complete list

    def clear(self):
        self._tracks = []  #MediaList, stored as a list of dicts
        self._num_tracks=0
        self._selected_track_index=-1 # index of currently selected track

    def print_list(self):
        print '\n'
        print self._tracks

    def first(self):
        self.select(0)

    def length(self):
        return self._num_tracks

    def append(self, track_dict):
        # print '\ntrack dict',track_dict
        """appends a track dictionary to the end of the medialist store"""
        self._tracks.append(copy.deepcopy(track_dict))
        self._num_tracks+=1

    def update(self,index,values):
        self._tracks[index].update(values)


    def remove(self,index):
        self._tracks.pop(index)
        self._num_tracks-=1
        # deselect any track, saves worrying about whether index needs changing
        self._selected_track_index=-1

    def move_up(self):
        if self._selected_track_index<>0:
            self._tracks.insert(self._selected_track_index-1, self._tracks.pop(self._selected_track_index))
            self.select(self._selected_track_index-1)

    def move_down(self):
        if self._selected_track_index<>self._num_tracks-1:
            self._tracks.insert(self._selected_track_index+1, self._tracks.pop(self._selected_track_index))
            self.select(self._selected_track_index+1)

    def replace(self,index,replacement):
        self._tracks[index]= replacement     
        
        
# Common functions work for anything
           

    def track_is_selected(self):
            if self._selected_track_index>=0:
                return True
            else:
                return False
            
    def selected_track_index(self):
        return self._selected_track_index

    def track(self,index):
        return self._tracks[index]
    
    def selected_track(self):
        """returns a dictionary containing all fields in the selected track """
        if self._selected_track_index == -1:
            self.select(0)
        return self._selected_track

    def select(self,index):
        """does housekeeping necessary when a track is selected"""
        if self._num_tracks>0 and index>=0 and index< self._num_tracks:
            self._selected_track_index=index
            self._selected_track = self._tracks[index]
            return True
        else:
            return False

# Dealing with anonymous tracks for use and display
     
    def at_end(self):
        if self._num_tracks == 1:
            return True
        # true is selected track is last anon
        return self._selected_track_index == self._num_tracks-1
        
    def index_of_end(self):
        index=self._num_tracks-1
        while index >= 0:
            if self._tracks[index] ['track-ref'] =="":
                return index
            index -=1
        return -1
   
    def at_start(self):
        index=0
        while index<self._num_tracks:
            if self._tracks[index] ['track-ref'] =="":
                start =  index
                if self._selected_track_index==start:
                    return True
                else:
                    return False
            index +=1
        return False
            
    def index_of_start(self):
        index=0
        while index<self._num_tracks:
            if self._tracks[index] ['track-ref'] =="":
                return index
            index +=1
        return False

    def display_length(self):
        # number of anonymous tracks
        count=0
        index=0
        while index<self._num_tracks:
            if self._tracks[index] ['track-ref'] =="":
                count+=1
            index +=1
        return count

    def start(self):
        # select first anymous track in the list
        # print "Starting media list"
        if self.sequence == 'ordered':
            #print "Selecting first track (ordered)"
            index=0
            while index<self._num_tracks:
                if self._tracks[index] ['track-ref'] =="":
                    self.select(index)
                    return True
                index +=1
            return False
        else:
            # print "Selecting shuffled next"
            return self.next(self.sequence)

    def finish(self):
        # select last anymous track in the list
        index=self._num_tracks-1
        while index>=0:
            if self._tracks[index] ['track-ref'] =="":
                self.select(index)
                return True
            index -=1
        return False

    def next(self,sequence):
        if sequence=='ordered':
            if self._selected_track_index== self._num_tracks-1:
                index=0
            else:
                index= self._selected_track_index+1
                
            end=self._selected_track_index
        else:
            if self._num_tracks == 1:
                index = 0
                end = 0
            else:
                index=random.randint(0,self._num_tracks-1)
                if index==0:
                    end=self._num_tracks-1
                else:
                    end=index-1
        #search for next anonymous track
        self.mon.log(self, " ------ ")
        #print '------------ shuffle result: index=', index, ', end=',end, ', num_tracks=', self._num_tracks
        while index<>end:
            if self._tracks[index] ['track-ref'] =="":
                self.select(index)
                return True
            if self._num_tracks == 1:
                return False
            if index== self._num_tracks-1:
                index=0
            else:
                index= index+1
        return False

    def previous(self,sequence):
        if sequence=='ordered':
            if self._selected_track_index == 0:
                index=self._num_tracks-1
            else:
                index= self._selected_track_index-1
            end = self._selected_track_index
        else:
            index=random.randint(0,self._num_tracks-1)
            if index==self._num_tracks-1:
                end=0
            else:
                end=index+1
        # print 'index', index, 'end',end                
        #search for previous anonymous track            
        while index<>end :
            if self._tracks[index] ['track-ref'] =="":
                self.select(index)
                return True                
            if index == 0:
                index=self._num_tracks-1
            else:
                index= index-1
        return False
    
    
# Lookup for labelled tracks
    
    
    def index_of_track(self,wanted_track):
        index = 0
        for track in self._tracks:
            if track['track-ref']==wanted_track:
                return index
            index +=1
        return -1


# open and save


    def open_list(self,filename,showlist_issue):
        """
        opens a saved medialist
        medialists are stored as json arrays.
        """
        ifile  = open(filename, 'rb')
        mdict = json.load(ifile)
        ifile.close()
        self._tracks = mdict['tracks']
        if 'issue' in mdict:
            self.issue= mdict['issue']
        else:
            self.issue="1.0"
        if self.issue==showlist_issue:
            self._num_tracks=len(self._tracks)
            self._selected_track_index=-1
            return True
        else:
            return False

    def issue(self):
        return self.issue

    def save_list(self,filename):
        """ save a medialist """
        if filename=="":
            return False
        dic={'issue':self.issue,'tracks':self._tracks}
        filename=str(filename)
        filename = string.replace(filename,'\\','/')
        tries = 1
        while tries<=10:
            # print "save  medialist  ",filename
            try:
                ofile  = open(filename, "wb")
                json.dump(dic,ofile,sort_keys=True,indent=1)
                ofile.close()
                self.mon.log(self,"Saved medialist "+ filename)
                break
            except IOError:
                self.mon.err(self,"failed to save medialist, trying again " + str(tries))
                tries+=1
        return


# for the future

    def open_csv(self,filename):
        """
        opens a saved csv medialist
        """
        if filename !="" and os.path.exists(filename):
            ifile  = open(filename, 'rb')
            pl=csv.reader(ifile)
            for pl_row in pl:
                if len(pl_row) != 0:
                    entry=dict([('type',pl_row[2]),('location',pl_row[0]),('title',pl_row[1])])
                    self.append(copy.deepcopy(entry))
            ifile.close()
            return True
        else:
            return False
Esempio n. 47
0
class Player(object):

    # common bits of __init__(...)
    def __init__(self, show_id, showlist, root, canvas, show_params,
                 track_params, pp_dir, pp_home, pp_profile, end_callback,
                 command_callback):

        # create debugging log object
        self.mon = Monitor()

        self.mon.trace(self, '')

        # instantiate arguments
        self.show_id = show_id
        self.showlist = showlist
        self.root = root
        self.canvas = canvas['canvas-obj']
        self.show_canvas_x1 = canvas['show-canvas-x1']
        self.show_canvas_y1 = canvas['show-canvas-y1']
        self.show_canvas_x2 = canvas['show-canvas-x2']
        self.show_canvas_y2 = canvas['show-canvas-y2']
        self.show_canvas_width = canvas['show-canvas-width']
        self.show_canvas_height = canvas['show-canvas-height']
        self.show_canvas_centre_x = canvas['show-canvas-centre-x']
        self.show_canvas_centre_y = canvas['show-canvas-centre-y']
        self.show_canvas_display_name = canvas['display-name']
        self.show_canvas_display_id = canvas['display-id']
        self.show_params = show_params
        self.track_params = track_params
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile
        self.end_callback = end_callback
        self.command_callback = command_callback

        # get background image from profile.
        self.background_file = ''
        if self.track_params['background-image'] != '':
            self.background_file = self.track_params['background-image']

        # get background colour from profile.
        if self.track_params['background-colour'] != '':
            self.background_colour = self.track_params['background-colour']
        else:
            self.background_colour = self.show_params['background-colour']

        # get animation instructions from profile
        self.animate_begin_text = self.track_params['animate-begin']
        self.animate_end_text = self.track_params['animate-end']

        # create an  instance of show manager so we can control concurrent shows
        # self.show_manager=Show Manager(self.show_id,self.showlist,self.show_params,self.root,self.canvas,self.pp_dir,self.pp_profile,self.pp_home)

        # open the plugin Manager
        self.pim = TrackPluginManager(self.show_id, self.root, self.canvas,
                                      self.show_params, self.track_params,
                                      self.pp_dir, self.pp_home,
                                      self.pp_profile)

        # create an instance of Animate so we can send animation commands
        self.animate = Animate()

        # initialise state and signals
        self.background_obj = None
        self.html_show_text_obj = None
        self.show_text_obj = None
        self.track_text_obj = None
        self.html_track_text_obj = None
        self.hint_obj = None
        self.background = None
        self.freeze_at_end_required = 'no'  # overriden by videoplayer
        self.tick_timer = None
        self.terminate_signal = False
        self.play_state = ''

    def pre_load(self):

        pass

    # common bits of show(....)
    def pre_show(self):
        self.mon.trace(self, '')

        # show_x_content moved to just before ready_callback to improve flicker.
        self.show_x_content()

        #ready callback hides and closes players from previous track, also displays show background
        if self.ready_callback is not None:
            self.ready_callback(self.enable_show_background)

        # Control other shows and do counters and osc at beginning
        self.show_control(self.track_params['show-control-begin'])

        # and show whatever the plugin has created
        self.show_plugin()

        # create animation events
        reason, message = self.animate.animate(self.animate_begin_text,
                                               id(self))
        if reason == 'error':
            self.mon.err(self, message)
            self.play_state = 'show-failed'
            if self.finished_callback is not None:
                self.finished_callback('error', message)
        else:
            # return to start playing the track.
            self.mon.log(
                self,
                ">show track received from show Id: " + str(self.show_id))
            return

    # to keep landscape happy
    def ready_callback(self, enable_show_background):
        self.mon.fatal(self, 'ready callback not overridden')
        self.end('error', 'ready callback not overridden')

    def finished_callback(self, reason, message):
        self.mon.fatal(self, 'finished callback not overridden')
        self.end('error', 'finished callback not overridden')

    def closed_callback(self, reason, message):
        self.mon.fatal(self, 'closed callback not overridden')
        self.end('error', 'closed callback not overridden')

# Control shows so pass the show control commands back to PiPresents via the command callback

    def show_control(self, show_control_text):
        lines = show_control_text.split('\n')
        for line in lines:
            if line.strip() == "":
                continue
            # print 'show control command: ',line
            self.command_callback(line,
                                  source='track',
                                  show=self.show_params['show-ref'])

# *****************
# hide content and end animation, show control etc.
# called by ready calback and end
# *****************

    def hide(self):
        self.mon.trace(self, '')
        # abort the timer
        if self.tick_timer is not None:
            self.canvas.after_cancel(self.tick_timer)
            self.tick_timer = None

        self.hide_x_content()

        # stop the plugin
        self.hide_plugin()

        # Control concurrent shows at end
        self.show_control(self.track_params['show-control-end'])

        # clear events list for this track
        if self.track_params['animate-clear'] == 'yes':
            self.animate.clear_events_list(id(self))

        # create animation events for ending
        # !!!!! TEMPORARY FIX
        reason, message = self.animate.animate(self.animate_end_text, id(self))
        if reason == 'error':
            self.mon.err(self, message)
            # self.play_state='show-failed'
            # if self.finished_callback is not None:
            # self.finished_callback('error',message)
        else:
            return

    def terminate(self):
        self.mon.trace(self, '')
        self.terminate_signal = True
        if self.play_state == 'showing':
            # call the derived class's stop method
            self.stop()
        else:
            self.end('killed', 'terminate with no track or show open')

    # must be overriden by derived class
    def stop(self):
        self.mon.fatal(self, 'stop not overidden by derived class')
        self.play_state = 'show-failed'
        if self.finished_callback is not None:
            self.finished_callback('error',
                                   'stop not overidden by derived class')

    def get_play_state(self):
        return self.play_state

# *****************
# ending the player
# *****************

    def end(self, reason, message):
        self.mon.trace(self, '')
        # stop the plugin

        if self.terminate_signal is True:
            reason = 'killed'
            self.terminate_signal = False
            self.hide()

        self.end_callback(reason, message)
        self = None

# *****************
# displaying common things
# *****************

    def load_plugin(self):
        # called in load before load_x_content modify the track here
        if self.track_params['plugin'] != '':
            reason, message, self.track = self.pim.load_plugin(
                self.track, self.track_params['plugin'])
            return reason, message

    def show_plugin(self):
        # called at show time, write to the track here if you need it after show_control_begin (counters)
        if self.track_params['plugin'] != '':
            self.pim.show_plugin()

    def hide_plugin(self):
        # called at the end of the track
        if self.track_params['plugin'] != '':
            self.pim.stop_plugin()

    def load_x_content(self, enable_menu):
        self.mon.trace(self, '')
        self.background_obj = None
        self.background = None
        self.track_text_obj = None
        self.show_text_obj = None
        self.hint_obj = None
        self.track_obj = None
        text_type = 'html'

        # background image
        if self.background_file != '':
            background_img_file = self.complete_path(self.background_file)
            if not os.path.exists(background_img_file):
                return 'error', "Track background file not found " + background_img_file
            else:
                try:
                    pil_background_img = Image.open(background_img_file)
                except:
                    pil_background_img = None
                    self.background = None
                    self.background_obj = None
                    return 'error', 'Track background, not a recognised image format ' + background_img_file
                # print 'pil_background_img ',pil_background_img
                image_width, image_height = pil_background_img.size
                window_width = self.show_canvas_width
                window_height = self.show_canvas_height
                if image_width != window_width or image_height != window_height:
                    pil_background_img = pil_background_img.resize(
                        (window_width, window_height))
                self.background = ImageTk.PhotoImage(pil_background_img)
                del pil_background_img
                self.background_obj = self.canvas.create_image(
                    self.show_canvas_x1,
                    self.show_canvas_y1,
                    image=self.background,
                    anchor=NW)
                # print '\nloaded background_obj: ',self.background_obj

        # load the track content.  Dummy function below is overridden in players
        status, message = self.load_track_content()
        if status == 'error':
            return 'error', message

        self.show_html_background_colour = self.show_params[
            'show-html-background-colour']
        if self.show_params['show-html-width'] == '':
            self.show_html_width = self.show_canvas_x2 - self.show_canvas_x1
        else:
            self.show_html_width = self.show_params['show-html-width']

        if self.show_params['show-html-height'] == '':
            self.show_html_height = self.show_canvas_y2 - self.show_canvas_y1
        else:
            self.show_html_height = self.show_params['show-html-height']

        self.show_text_type = self.show_params['show-text-type']

        if self.show_params['show-text-location'] != '':
            text_path = self.complete_path(
                self.show_params['show-text-location'])
            if not os.path.exists(text_path):
                return 'error', "Show Text file not found " + text_path
            with open(text_path) as f:
                show_text = f.read()
        else:
            show_text = self.show_params['show-text']

        # load show text if enabled
        if show_text != '' and self.track_params['display-show-text'] == 'yes':

            x, y, anchor, justify = calculate_text_position(
                self.show_params['show-text-x'],
                self.show_params['show-text-y'], self.show_canvas_x1,
                self.show_canvas_y1, self.show_canvas_centre_x,
                self.show_canvas_centre_y, self.show_canvas_x2,
                self.show_canvas_y2, self.show_params['show-text-justify'])
            if self.show_text_type == 'html':
                self.html_show_text_obj = HTMLText(
                    self.canvas,
                    background=self.show_html_background_colour,
                    relief=FLAT)

                self.html_show_text_obj.set_html(show_text, self.pp_home,
                                                 self.pp_profile)

                self.show_text_obj = self.canvas.create_window(
                    x,
                    y,
                    window=self.html_show_text_obj,
                    anchor=anchor,
                    width=self.show_html_width,
                    height=self.show_html_height)

            else:
                self.show_text_obj = self.canvas.create_text(
                    x,
                    y,
                    anchor=anchor,
                    justify=justify,
                    text=show_text,
                    fill=self.show_params['show-text-colour'],
                    font=self.show_params['show-text-font'])

        # load track text if enabled

        if self.track_params['track-text-x'] == '':
            track_text_x = self.show_params['track-text-x']
        else:
            track_text_x = self.track_params['track-text-x']

        if self.track_params['track-text-y'] == '':
            track_text_y = self.show_params['track-text-y']
        else:
            track_text_y = self.track_params['track-text-y']

        if self.track_params['track-text-justify'] == '':
            track_text_justify = self.show_params['track-text-justify']
        else:
            track_text_justify = self.track_params['track-text-justify']

        if self.track_params['track-text-font'] == '':
            track_text_font = self.show_params['track-text-font']
        else:
            track_text_font = self.track_params['track-text-font']

        if self.track_params['track-text-colour'] == '':
            track_text_colour = self.show_params['track-text-colour']
        else:
            track_text_colour = self.track_params['track-text-colour']

        self.track_html_background_colour = self.track_params[
            'track-html-background-colour']

        if self.track_params['track-html-width'] == '':
            self.track_html_width = self.show_canvas_x2 - self.show_canvas_x1
        else:
            self.track_html_width = self.track_params['track-html-width']

        if self.track_params['track-html-height'] == '':
            self.track_html_height = self.show_canvas_y2 - self.show_canvas_y1
        else:
            self.track_html_height = self.track_params['track-html-height']

        self.track_text_type = self.track_params['track-text-type']

        if self.track_params['track-text-location'] != '':
            text_path = self.complete_path(
                self.track_params['track-text-location'])
            if not os.path.exists(text_path):
                return 'error', "Track Text file not found " + text_path
            with open(text_path) as f:
                track_text = f.read()
        else:
            track_text = self.track_params['track-text']

        if track_text != '':

            x, y, anchor, justify = calculate_text_position(
                track_text_x, track_text_y, self.show_canvas_x1,
                self.show_canvas_y1, self.show_canvas_centre_x,
                self.show_canvas_centre_y, self.show_canvas_x2,
                self.show_canvas_y2, track_text_justify)

            if self.track_text_type == 'html':
                self.html_track_text_obj = HTMLText(
                    self.canvas,
                    background=self.track_html_background_colour,
                    relief=FLAT)
                # self.html_text.pack(fill="both", expand=True)
                self.html_track_text_obj.set_html(track_text, self.pp_home,
                                                  self.pp_profile)
                # self.html_text.fit_height()
                self.track_text_obj = self.canvas.create_window(
                    x,
                    y,
                    window=self.html_track_text_obj,
                    anchor=anchor,
                    width=self.track_html_width,
                    height=self.track_html_height)
            else:
                self.track_text_obj = self.canvas.create_text(
                    x,
                    y,
                    anchor=anchor,
                    justify=justify,
                    text=track_text,
                    fill=track_text_colour,
                    font=track_text_font)
        # load instructions if enabled
        if enable_menu is True:

            x, y, anchor, justify = calculate_text_position(
                self.show_params['hint-x'], self.show_params['hint-y'],
                self.show_canvas_x1, self.show_canvas_y1,
                self.show_canvas_centre_x, self.show_canvas_centre_y,
                self.show_canvas_x2, self.show_canvas_y2,
                self.show_params['hint-justify'])

            self.hint_obj = self.canvas.create_text(
                x,
                y,
                justify=justify,
                text=self.show_params['hint-text'],
                fill=self.show_params['hint-colour'],
                font=self.show_params['hint-font'],
                anchor=anchor)

        self.display_show_canvas_rectangle()

        self.canvas.tag_raise('pp-click-area')
        self.canvas.itemconfig(self.background_obj, state='hidden')
        self.canvas.itemconfig(self.show_text_obj, state='hidden')
        self.canvas.itemconfig(self.track_text_obj, state='hidden')
        self.canvas.itemconfig(self.hint_obj, state='hidden')
        self.canvas.update_idletasks()
        return 'normal', 'x-content loaded'

    # display the rectangle that is the show canvas
    def display_show_canvas_rectangle(self):
        # coords=[self.show_canvas_x1,self.show_canvas_y1,self.show_canvas_x2-1,self.show_canvas_y2-1]
        # self.canvas.create_rectangle(coords,
        #            outline='yellow',
        #          fill='')
        pass

    # dummy functions to manipulate the track content, overidden in some players,
    # message text in messageplayer
    # image in imageplayer
    # menu stuff in menuplayer

    def load_track_content(self):
        return 'normal', 'player has no track content to load'

    def show_track_content(self):
        pass

    def hide_track_content(self):
        pass

    def show_x_content(self):
        self.mon.trace(self, '')
        # background colour
        if self.background_colour != '':
            self.canvas.config(bg=self.background_colour)
        # print 'showing background_obj: ', self.background_obj
        # reveal background image and text
        self.canvas.itemconfig(self.background_obj, state='normal')
        self.show_track_content()

        self.canvas.itemconfig(self.show_text_obj, state='normal')
        self.canvas.itemconfig(self.track_text_obj, state='normal')
        self.canvas.itemconfig(self.hint_obj, state='normal')
        # self.canvas.update_idletasks( )

        # decide whether the show background should be enabled.
        # print 'DISPLAY SHOW BG',self.track_params['display-show-background'],self.background_obj
        if self.background_obj is None and self.track_params[
                'display-show-background'] == 'yes':
            self.enable_show_background = True
        else:
            self.enable_show_background = False
        # print 'ENABLE SB',self.enable_show_background

    def hide_x_content(self):
        self.mon.trace(self, '')
        self.hide_track_content()
        self.canvas.itemconfig(self.background_obj, state='hidden')
        self.canvas.itemconfig(self.show_text_obj, state='hidden')
        self.canvas.itemconfig(self.track_text_obj, state='hidden')
        self.canvas.itemconfig(self.hint_obj, state='hidden')
        # self.canvas.update_idletasks( )

        # need to delete html parser to stop garbage
        if self.html_show_text_obj != None:
            self.html_show_text_obj.delete_parser()
        if self.html_track_text_obj != None:
            self.html_track_text_obj.delete_parser()

        self.canvas.delete(self.background_obj)
        self.canvas.delete(self.show_text_obj)
        self.canvas.delete(self.track_text_obj)
        self.canvas.delete(self.hint_obj)

        self.background = None
        # self.canvas.update_idletasks( )

# ****************
# utilities
# *****************

    def get_links(self):
        return self.track_params['links']

    # produce an absolute path from the relative one in track paramters
    def complete_path(self, track_file):
        #  complete path of the filename of the selected entry
        if track_file[0] == "+":
            track_file = self.pp_home + track_file[1:]
        elif track_file[0] == "@":
            track_file = self.pp_profile + track_file[1:]
        return track_file

    # get a text string from resources.cfg
    def resource(self, section, item):
        value = self.rr.get(section, item)
        return value  # False if not found

    def parse_duration(s):
        if s == '0':
            #print ('OK: infinite',0)
            return 'normal', '', 0
        try:
            val = float(s) * 10
        except:
            #print ('error: not a float')
            return 'error', 'duration must be a decimal number: ' + s, -1
        if val < 0:
            #print ('error: negative')
            return 'error', 'duration must be a positive number: ' + s, -1
        if val < 1:
            #print('error:must be >= 0.1')
            return 'error', 'duration must be >= 0.1 or be 0: ' + s, -1
        result = math.floor(val)
        #print ('OK:',result)
        return 'normal', '', result
Esempio n. 48
0
class MessagePlayer:
    """ Displays lines of text in the centre of a black screen"""

    # *******************
    # external commands
    # *******************

    def __init__(self, canvas, cd, track_params):
        """
                canvas - the canvas onto which the image is to be drawn
                cd - configuration dictionary for the show from which player was called
        """

        self.mon = Monitor()
        self.mon.on()

        self.canvas = canvas
        self.cd = cd
        self.track_params = track_params

        # get config from medialist if there.

        if 'duration' in self.track_params and self.track_params[
                'duration'] <> "":
            self.duration = int(self.track_params['duration'])
        else:
            self.duration = int(self.cd['duration'])

        # keep dwell and porch as an integer multiple of tick
        self.tick = 100  # tick time for image display (milliseconds)
        self.dwell = (1000 * self.duration)

        self.centre_x = int(self.canvas['width']) / 2
        self.centre_y = int(self.canvas['height']) / 2

    def play(self,
             text,
             end_callback,
             ready_callback,
             enable_menu=False,
             starting_callback=None,
             playing_callback=None,
             ending_callback=None):

        # instantiate arguments
        self.text = text
        self.enable_menu = enable_menu
        self.ready_callback = ready_callback
        self.end_callback = end_callback
        #init state and signals
        self.quit_signal = False
        self.kill_required_signal = False
        self.error = False
        self._tick_timer = None
        self.drawn = None

        # and start text display
        self._start_dwell()

    def key_pressed(self, key_name):
        self.mon.log(self, "key received: " + key_name)
        if key_name == '':
            return
        elif key_name in ('p'):
            return
        elif key_name == 'escape':
            self._stop()
            return

    def button_pressed(self, button, edge):
        self.mon.log(self, "button received: " + button)
        if button == 'pause':
            return
        elif button == 'stop':
            self._stop()
            return

    def terminate(self, reason):
        if reason == 'error':
            self.error = True
        else:
            self.kill_required_signal = True
        self.quit_signal = True

# *******************
# internal functions
# *******************

    def _stop(self):
        self.quit_signal = True

    def _error(self):
        self.error = True
        self.quit_signal = True

    #called when dwell has completed or quit signal is received
    def _end(self, reason, message):
        if self._tick_timer <> None:
            self.canvas.after_cancel(self._tick_timer)
            self._tick_timer = None
        self.quit_signal = False
        #self.canvas.delete(ALL)
        self.canvas.update_idletasks()
        if self.error == True:
            self.end_callback("error", message)
            self = None
        elif self.kill_required_signal == True:
            self.end_callback("killed", message)
            self = None
        else:
            self.end_callback('normal', message)
            self = None

    def _start_dwell(self):
        self.dwell_counter = 0
        if self.ready_callback <> None:
            self.ready_callback()
        # display text
        self.canvas.create_text(self.centre_x,
                                self.centre_y,
                                text=self.text.rstrip('\n'),
                                fill=self.track_params['message-colour'],
                                font=self.track_params['message-font'])

        # display instructions (hint)
        if self.enable_menu == True:
            self.canvas.create_text(int(self.canvas['width']) / 2,
                                    int(self.canvas['height']) -
                                    int(self.cd['hint-y']),
                                    text=self.cd['hint-text'],
                                    fill=self.cd['hint-colour'],
                                    font=self.cd['hint-font'])

        self.canvas.update_idletasks()
        self._tick_timer = self.canvas.after(self.tick, self._do_dwell)

    def _do_dwell(self):
        if self.quit_signal == True:
            self.mon.log(self, "quit received")
            self._end('normal', 'user quit')
        else:
            if self.dwell <> 0:
                self.dwell_counter = self.dwell_counter + 1
                if self.dwell_counter == self.dwell / self.tick:
                    self._end('normal', 'finished')
                else:
                    self._tick_timer = self.canvas.after(
                        self.tick, self._do_dwell)
            else:
                self._tick_timer = self.canvas.after(self.tick, self._do_dwell)
Esempio n. 49
0
class IOPluginManager(object):

    plugins=[]

    def __init__(self):
        self.mon=Monitor()



    def init(self,pp_dir,pp_profile,widget,callback,pp_home):
        self.pp_dir=pp_dir
        self.pp_profile=pp_profile
        self.pp_home=pp_home
        IOPluginManager.plugins=[]

        if os.path.exists(self.pp_profile+os.sep+'pp_io_config'):
            # read the .cfg files in /pp_io_config in profile registring the I/O plugin
            for cfgfile in os.listdir(self.pp_profile+os.sep+'pp_io_config'):
                if cfgfile in ('screen.cfg','osc.cfg'):
                    continue
                cfgfilepath = self.pp_profile+os.sep+'pp_io_config'+os.sep+cfgfile
                status,message=self.init_config(cfgfile,cfgfilepath,widget,callback)
                if status == 'error':
                    return status,message

        #read .cfg file in /pipresents/pp_io_config if file not present in profile then use this one
        for cfgfile in os.listdir(self.pp_dir+os.sep+'pp_io_config'):
            if cfgfile in ('screen.cfg','osc.cfg'):
                continue
            if not os.path.exists(self.pp_profile+os.sep+'pp_io_config'+os.sep+cfgfile):
                cfgfilepath=self.pp_dir+os.sep+'pp_io_config'+os.sep+cfgfile
                status,message=self.init_config(cfgfile,cfgfilepath,widget,callback)
                if status == 'error':
                    return status,message
                 
        # print IOPluginManager.plugins
        return 'normal','I/O Plugins registered'

    def init_config(self,cfgfile,cfgfilepath,widget,callback):
        # print cfgfile,cfgfilepath
        reason,message,config=self._read(cfgfile,cfgfilepath)
        if reason =='error':
            self.mon.err(self,'Failed to read '+cfgfile + ' ' + message)
            return 'error','Failed to read '+cfgfile + ' ' + message                
        if config.has_section('DRIVER') is False:
            self.mon.err(self,'No DRIVER section in '+cfgfilepath)
            return 'error','No DRIVER section in '+cfgfilepath
        entry = dict()
        #read information from DRIVER section
        entry['title']=config.get('DRIVER','title')
        if config.get('DRIVER','enabled')=='yes':
            driver_name=config.get('DRIVER','module')
            driver_path=self.pp_dir+os.sep+'pp_io_plugins'+os.sep+driver_name+'.py'
            if not os.path.exists(driver_path):
                self.mon.err(self,driver_name + ' Driver not found in ' + driver_path)
                return 'error',driver_name + ' Driver not found in ' + driver_path
            
            instance = self._load_plugin_file(driver_name,self.pp_dir+os.sep+'pp_io_plugins')
            reason,message=instance.init(cfgfile,cfgfilepath,widget,self.pp_dir,self.pp_home,self.pp_profile,callback)
            if reason=='warn':
                self.mon.warn(self,message)
                return 'error',message
            if reason=='error':
                self.mon.warn(self,message)
                return 'error',message
            entry['instance']=instance
            self.mon.log(self,message)
            IOPluginManager.plugins.append(entry)
        return 'normal','I/O Plugins registered'
    

    def start(self):
        for entry in IOPluginManager.plugins:
            plugin=entry['instance']
            if plugin.is_active() is True:
                plugin.start()
                
        
    def terminate(self):
        for entry in IOPluginManager.plugins:
            plugin=entry['instance']
            if plugin.is_active() is True:
                plugin.terminate()
                self.mon.log(self,'I/O plugin '+entry['title']+ ' terminated')

    def get_input(self,key):
        for entry in IOPluginManager.plugins:
            plugin=entry['instance']
            # print 'trying ',entry['title'],plugin.is_active()
            if plugin.is_active() is True:
                found,value = plugin.get_input(key)
                if found is True:
                    return found,value
        # key not found in any plugin
        return False,None

    def handle_output_event(self,name,param_type,param_values,req_time):
        for entry in IOPluginManager.plugins:
            plugin=entry['instance']
            # print 'trying ',entry['title'],name,param_type,plugin.is_active()
            if plugin.is_active() is True:
                reason,message= plugin.handle_output_event(name,param_type,param_values,req_time)
                if reason == 'error':
                    # self.mon.err(self,message)
                    return 'error',message
                else:
                    self.mon.log(self,message)
        return 'normal','output scan complete'

    def _load_plugin_file(self, name, driver_dir):
        fp, pathname,description = imp.find_module(name,[driver_dir])
        module_id =  imp.load_module(name,fp,pathname,description)
        plugin_class = getattr(module_id,name)
        return plugin_class()

        

    def _read(self,filename,filepath):
        if os.path.exists(filepath):
            config = configparser.ConfigParser(inline_comment_prefixes = (';',))
            config.read(filepath)
            self.mon.log(self,filename+" read from "+ filepath)
            return 'normal',filename+' read',config
        else:
            return 'error',filename+' not found at: '+filepath,None
class Animate(object):
    """
     allows players to put events, which request the change of state of pins, into a queue. Events are executed at the required time.
     using the interface to an output driver.
   """

    # constants for sequencer events list

    name = 0  # GPIO pin number, the xx in P1-xx
    param_type = 1
    param_values = 2  # off , on
    time = 3  # time since the epoch in seconds
    tag = 4  # tag used to delete all matching events, usually a track reference.
    event_template = ['', '', '', 0, None]

    # CLASS VARIABLES (Animate.)
    events = []
    last_poll_time = 0

    # executed by main program and by each object using animate
    def __init__(self):
        self.mon = Monitor()

    # executed once from main program
    def init(self, pp_dir, pp_home, pp_profile, widget, sequencer_tick,
             event_callback):

        # instantiate arguments
        self.widget = widget  #something to hang 'after' on
        self.pp_dir = pp_dir
        self.pp_profile = pp_profile
        self.pp_home = pp_home
        self.sequencer_tick = sequencer_tick
        self.event_callback = event_callback

        # Initialise time used by sequencer
        Animate.sequencer_time = int(time.time())

        # init timer
        self.sequencer_tick_timer = None

    # called by main program only
    def terminate(self):
        if self.sequencer_tick_timer is not None:
            self.widget.after_cancel(self.sequencer_tick_timer)
        self.clear_events_list(None)

# ************************************************
# output sequencer
# ************************************************

# called by main program only

    def poll(self):
        poll_time = int(time.time())
        # is current time greater than last time the scheduler was run (previous second or more)
        # run in a loop to catch up because root.after can get behind when images are being rendered etc.
        while Animate.sequencer_time <= poll_time:
            # kick off output pin sequencer
            self.do_sequencer()
            Animate.sequencer_time += 1

        # and loop the polling
        self.sequencer_tick_timer = self.widget.after(self.sequencer_tick,
                                                      self.poll)

    # execute events at the appropriate time and remove from list (runs from main program only)
    # runs through list a number of times because of problems with pop messing up list
    def do_sequencer(self):
        # print 'sequencer run for: ' + str(sequencer_time) + ' at ' + str(long(time.time()))
        while True:
            event_found = False
            for index, item in enumerate(Animate.events):
                if item[Animate.time] <= Animate.sequencer_time:
                    event = Animate.events.pop(index)
                    event_found = True
                    self.send_event(event[Animate.name],
                                    event[Animate.param_type],
                                    event[Animate.param_values],
                                    item[Animate.time])
                    break
            if event_found is False: break

    def send_event(self, name, param_type, param_values, req_time):
        self.mon.log(
            self, 'send event ' + name + ' ' + param_type + ' ' +
            ' '.join(param_values))
        self.event_callback(name, param_type, param_values, req_time)

# ************************************************
# output sequencer interface methods
# these can be called from many classes so need to operate on class variables
# ************************************************

    def animate(self, text, tag):
        lines = text.split("\n")
        for line in lines:
            reason, message, delay, name, param_type, param_values = self.parse_animate_fields(
                line)
            if reason == 'error':
                return 'error', message
            if name != '':
                self.add_event(name, param_type, param_values, delay, tag)
        return 'normal', 'events processed'

    def add_event(self, name, param_type, param_values, delay, tag):
        poll_time = int(time.time())
        # prepare the event
        event = Animate.event_template
        event[Animate.name] = name
        event[Animate.param_type] = param_type
        event[Animate.param_values] = param_values
        event[Animate.time] = delay + poll_time  #+1?
        event[Animate.tag] = tag
        # print '\nadd event ',event
        # find the place in the events list and insert
        # first item in the list is earliest, if two have the same time then last to be added is fired last.
        # events are fired from top of list
        abs_time = poll_time + delay
        # print 'new event',abs_time
        copy_event = copy.deepcopy(event)
        length = len(Animate.events)
        if length == 0:
            Animate.events.append(copy_event)
            # print 'append to empty ist',abs_time
            return copy_event
        else:
            index = length - 1
            if abs_time > Animate.events[index][Animate.time]:
                Animate.events.append(copy_event)
                # print 'append to end of list if greater than last item',abs_time
                return copy_event
            while index != -1:
                if abs_time == Animate.events[index][Animate.time]:
                    Animate.events.insert(index + 1, copy_event)
                    # print 'insert after if equal',abs_time
                    return copy_event
                if abs_time > Animate.events[index][Animate.time]:
                    Animate.events.insert(index + 1, copy_event)
                    # print 'insert after if later',abs_time
                    return copy_event
                if index == 0:
                    Animate.events.insert(index, copy_event)
                    # print 'insert before if at start of list',abs_time
                    return copy_event
                index -= 1
            # print 'error at start of list',abs_time

    def print_events(self):
        print('events list')
        for event in Animate.events:
            print('EVENT: ', event)

    # remove all the events with the same tag, usually a track reference
    def remove_events(self, tag):
        left = []
        for item in Animate.events:
            if tag != item[Animate.tag]:
                left.append(item)
        Animate.events = left
        # self.print_events()

    # clear event list
    def clear_events_list(self, tag):
        self.mon.log(self, 'clear events list ')
        # empty event list
        Animate.events = []

    # [delay],symbol,type,values(one or more)
    def parse_animate_fields(self, line):
        if line == '':
            return 'normal', 'no fields', '', '', [], 0
        # split the line using "" for text with spaces
        for l in csv.reader([line],
                            delimiter=' ',
                            skipinitialspace=True,
                            quotechar='"'):
            fields = l

        if len(fields) == 0:
            return 'normal', 'no fields', '', '', [], 0

        elif len(fields) < 3:
            return 'error', 'too few fields in : ' + line, '', '', [], 0

        delay_text = fields[0]
        # check each field
        if not delay_text.isdigit():
            return 'error', 'Delay is not an integer in : ' + line, '', '', [], 0
        else:
            delay = int(delay_text)

        name = fields[1]

        if len(fields) == 2:
            param_type = ''
            params = []
        else:
            param_type = fields[2]
            params = []
            for index in range(3, len(fields)):
                param = fields[index]
                params.append(param)

        # print 'event parsed OK',delay,name,param_type,params
        return 'normal', 'event parsed OK', delay, name, param_type, params
Esempio n. 51
0
class EditItem(tkSimpleDialog.Dialog):

    def __init__(self, parent, title, field_content, record_specs,field_specs,show_refs,initial_media_dir,pp_home_dir,initial_tab):
        self.mon=Monitor()
        # save the extra arg to instance variable
        self.field_content = field_content   # dictionary - the track parameters to be edited
        self.record_specs= record_specs # list of field names and seps/tabs in the order that they appear
        self.field_specs=field_specs  # dictionary of specs referenced by field name
        
        self.show_refs=show_refs
        self.show_refs.append('')
        self.initial_media_dir=initial_media_dir
        self.pp_home_dir=pp_home_dir
        self.initial_tab=initial_tab
        
        # list of stringvars from which to get edited values (for optionmenu only??)
        self.entries=[]

        # and call the base class _init_which calls body immeadiately and apply on OK pressed
        tkSimpleDialog.Dialog.__init__(self, parent, title)

    def body(self,root):
        self.root=root
        bar = TabBar(root, init_name=self.initial_tab)
        self.body_fields(root,bar)
        # bar.config(bd=1, relief=RIDGE)   # add some border
        bar.show()

        
    def body_fields(self, master,bar):
        # get fields for this record using the record type in the loaded record
        record_fields=self.record_specs[self.field_content['type']]

        # init results of building the form
        self.tab_row=1 # row on form
        self.fields=[]  # generated by body_fields - list of field objects in record  fields order, not for sep or tab
        self.field_index=0 # index to self.fields incremented after each field except tab and sep
        self.entries=[]   # generated by body_fields - list of stringvars in record fields order, used option-menus only
        
        # populate the dialog box using the record fields to determine the order
        for field in record_fields:
            #print 'BODY_FIELDS',field,field['shape']
            # get list of values where required
            values=[]
            if self.field_specs[field]['shape']in("option-menu",'spinbox'):
                # print 'should be field name', field
                # print 'should be shape',self.field_specs[field]['shape']
                if field in ('sub-show','start-show'):
                    values=self.show_refs                    
                else:
                    values=self.field_specs[field]['values']
            else:
                values=[]
            # make the entry
            obj=self.make_entry(master,field,self.field_specs[field],values,bar)
            if obj is not  None:
                self.fields.append(obj)
                self.field_index +=1
        return None # No initial focus



    # create an entry in a dialog box
    def make_entry(self,master,field,field_spec,values,bar):
        # print 'make entry',self.field_index,field,field_spec
        if field_spec['shape']=='tab':
            self.current_tab = Tab(master, field_spec['name'])
            bar.add(self.current_tab,field_spec['text'])
            self.tab_row=1
            return None
        elif field_spec['shape']=='sep':
            Label(self.current_tab,text='', anchor=W).grid(row=self.tab_row,column=0,sticky=W)
            self.tab_row+=1
            return None

        else:

            # print 'replace param in make entry',field
            # print 'content', field, self.field_content[field]
            # is it in the field content dictionary
            if not field in self.field_content:
                self.mon.log(self,"Value for field not found in opened file: " + field)
                return None
            else:
                if field_spec['must']=='yes':
                    bg='pink'
                else:
                    bg='white'
                    
                # write the label
                Label(self.current_tab,text=field_spec['text'], anchor=W).grid(row=self.tab_row,column=0,sticky=W)
                
                # make the editable field
                if field_spec['shape']in ('entry','colour','browse','font'):
                    obj=Entry(self.current_tab,bg=bg,width=40,font='arial 11')
                    obj.insert(END,self.field_content[field])
                    
                elif field_spec['shape']=='text':
                    obj=ScrolledText(self.current_tab,bg=bg,height=8,width=40,font='arial 11')
                    obj.insert(END,self.field_content[field])
                    
                elif field_spec['shape']=='spinbox':
                    obj=Spinbox(self.current_tab,bg=bg,values=values,wrap=True)
                    obj.insert(END,self.field_content[field])
                    
                elif field_spec['shape']=='option-menu': 
                    self.option_val = StringVar(self.current_tab)    
                    self.option_val.set(self.field_content[field])
                    obj = apply(OptionMenu, [self.current_tab, self.option_val] + values)
                    self.entries.append(self.option_val)
                    
                else:
                    self.mon.log(self,"Uknown shape for: " + field)
                    return None
                
                if field_spec['read-only']=='yes':
                    obj.config(state="readonly",bg='dark grey')
                    
                obj.grid(row=self.tab_row,column=1,sticky=W)

                # display buttons where required
                if field_spec['shape']=='browse':
                    but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.browse(o)))
                    but.grid(row=self.tab_row,column=2,sticky=W)
                    
                elif field_spec['shape']=='colour':
                    but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_colour(o)))
                    but.grid(row=self.tab_row,column=2,sticky=W)
                    
                elif field_spec['shape']=='font':
                    but=Button(self.current_tab,width=1,height=1,bg='dark grey',command=(lambda o=obj: self.pick_font(o)))
                    but.grid(row=self.tab_row,column=2,sticky=W)

                self.tab_row+=1    
                return obj


    def apply(self):
        # get list of fields in the record in the same order as the form was generated
        record_fields=self.record_specs[self.field_content['type']]
        
        field_index=0 # index to self.fields - not incremented for tab and sep
        entry_index=0  # index of stringvars for option_menu

        for field in record_fields:
            # print field
            # get the details of this field
            field_spec=self.field_specs[field]
            # print  'reading row',field_index,field_spec['shape']
            
            # and get the value
            if field_spec['shape']not in ('sep','tab'):

                
                if field_spec['shape']=='text':
                    self.field_content[field]=self.fields[field_index].get(1.0,END).rstrip('\n')
                    
                elif field_spec['shape']=='option-menu':
                    self.field_content[field]=self.entries[entry_index].get()
                    entry_index+=1
                else:
                    self.field_content[field]=self.fields[field_index].get().strip()
                    
                # print self.field_content[field]    
                field_index +=1
                
        self.result=True
        return self.result
        


    def pick_colour(self,obj):
        rgb,colour=askcolor()
        # print rgb,colour
        if colour is not None:
            obj.delete(0,END)
            obj.insert(END,colour)
            
    def pick_font(self,obj):
        font=askChooseFont(self.root)
        # print font
        if font is not None:
            obj.delete(0,END)
            obj.insert(END,font)

    def browse(self,obj):
        # print "initial directory ", self.options.initial_media_dir
        file_path=tkFileDialog.askopenfilename(initialdir=self.initial_media_dir, multiple=False)
        if file_path=='':
            return
        file_path=os.path.normpath(file_path)
        # print "file path ", file_path
        relpath = os.path.relpath(file_path,self.pp_home_dir)
        # print "relative path ",relpath
        common = os.path.commonprefix([file_path,self.pp_home_dir])
        # print "common ",common
        if common.endswith("pp_home") is False:
            obj.delete(0,END)
            obj.insert(END,file_path)
        else:
            location = "+" + os.sep + relpath
            location = string.replace(location,'\\','/')
            # print "location ",location
            obj.delete(0,END)
            obj.insert(END,location)


    def buttonbox(self):
        '''add modified button box.
        override standard one to get rid of key bindings which cause trouble with text widget
        '''

        box = Frame(self)
        w = Button(box, text="OK", width=10, command=self.ok, default=ACTIVE)
        w.pack(side=LEFT, padx=5, pady=5)
        w = Button(box, text="Cancel", width=10, command=self.cancel)
        w.pack(side=LEFT, padx=5, pady=5)
        # self.bind("<Return>", self.ok)
        # self.bind("<Escape>", self.cancel)
        box.pack()
Esempio n. 52
0
class PiPresents(object):
    def __init__(self):
        gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES
                     | gc.DEBUG_OBJECTS | gc.DEBUG_SAVEALL)
        self.pipresents_issue = "1.3"
        self.pipresents_minorissue = '1.3.1i'
        # position and size of window without -f command line option
        self.nonfull_window_width = 0.45  # proportion of width
        self.nonfull_window_height = 0.7  # proportion of height
        self.nonfull_window_x = 0  # position of top left corner
        self.nonfull_window_y = 0  # position of top left corner
        self.pp_background = 'black'

        StopWatch.global_enable = False

        # set up the handler for SIGTERM
        signal.signal(signal.SIGTERM, self.handle_sigterm)

        # ****************************************
        # Initialisation
        # ***************************************
        # get command line options
        self.options = command_options()

        # get Pi Presents code directory
        pp_dir = sys.path[0]
        self.pp_dir = pp_dir

        if not os.path.exists(pp_dir + "/pipresents.py"):
            if self.options['manager'] is False:
                tkMessageBox.showwarning("Pi Presents",
                                         "Bad Application Directory")
            exit(102)

        # Initialise logging and tracing
        Monitor.log_path = pp_dir
        self.mon = Monitor()
        # Init in PiPresents only
        self.mon.init()

        # uncomment to enable control of logging from within a class
        # Monitor.enable_in_code = True # enables control of log level in the code for a class  - self.mon.set_log_level()

        # make a shorter list to log/trace only some classes without using enable_in_code.
        Monitor.classes = [
            'PiPresents', 'HyperlinkShow', 'RadioButtonShow', 'ArtLiveShow',
            'ArtMediaShow', 'MediaShow', 'LiveShow', 'MenuShow', 'GapShow',
            'Show', 'ArtShow', 'AudioPlayer', 'BrowserPlayer', 'ImagePlayer',
            'MenuPlayer', 'MessagePlayer', 'VideoPlayer', 'Player',
            'MediaList', 'LiveList', 'ShowList', 'PathManager',
            'ControlsManager', 'ShowManager', 'PluginManager', 'MplayerDriver',
            'OMXDriver', 'UZBLDriver', 'KbdDriver', 'GPIODriver', 'TimeOfDay',
            'ScreenDriver', 'Animate', 'OSCDriver', 'Network', 'Mailer',
            'RadioMediaShow'
        ]

        # Monitor.classes=['PiPresents','MediaShow','GapShow','Show','VideoPlayer','Player','OMXDriver']

        # get global log level from command line
        Monitor.log_level = int(self.options['debug'])
        Monitor.manager = self.options['manager']
        # print self.options['manager']
        self.mon.newline(3)
        self.mon.sched(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue +
            ' at ' + time.strftime("%Y-%m-%d %H:%M.%S"))
        self.mon.log(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue +
            ' at ' + time.strftime("%Y-%m-%d %H:%M.%S"))
        # self.mon.log (self," OS and separator:" + os.name +'  ' + os.sep)
        self.mon.log(self, "sys.path[0] -  location of code: " + sys.path[0])

        # log versions of Raspbian and omxplayer, and GPU Memory
        with open("/boot/issue.txt") as file:
            self.mon.log(self, '\nRaspbian: ' + file.read())

        self.mon.log(self, '\n' + check_output(["omxplayer", "-v"]))
        self.mon.log(
            self,
            '\nGPU Memory: ' + check_output(["vcgencmd", "get_mem", "gpu"]))

        # optional other classes used
        self.root = None
        self.ppio = None
        self.tod = None
        self.animate = None
        self.gpiodriver = None
        self.oscdriver = None
        self.osc_enabled = False
        self.gpio_enabled = False
        self.tod_enabled = False
        self.email_enabled = False

        if os.geteuid() == 0:
            self.mon.err(self, 'Do not run Pi Presents with sudo')
            self.end('error', 'Do not run Pi Presents with sudo')

        user = os.getenv('USER')

        self.mon.log(self, 'User is: ' + user)
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME')) # does not work
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))   # does not work

        # check network is available
        self.network_connected = False
        self.network_details = False
        self.interface = ''
        self.ip = ''
        self.unit = ''

        # sets self.network_connected and self.network_details
        self.init_network()

        # start the mailer and send email when PP starts
        self.email_enabled = False
        if self.network_connected is True:
            self.init_mailer()
            if self.email_enabled is True and self.mailer.email_at_start is True:
                subject = '[Pi Presents] ' + self.unit + ': PP Started on ' + time.strftime(
                    "%Y-%m-%d %H:%M")
                message = time.strftime(
                    "%Y-%m-%d %H:%M"
                ) + '\n ' + self.unit + '\n ' + self.interface + '\n ' + self.ip
                self.send_email('start', subject, message)

        # get profile path from -p option
        if self.options['profile'] != '':
            self.pp_profile_path = "/pp_profiles/" + self.options['profile']
        else:
            self.mon.err(self, "Profile not specified in command ")
            self.end('error',
                     'Profile not specified with the commands -p option')

    # get directory containing pp_home from the command,
        if self.options['home'] == "":
            home = os.sep + 'home' + os.sep + user + os.sep + "pp_home"
        else:
            home = self.options['home'] + os.sep + "pp_home"
        self.mon.log(self, "pp_home directory is: " + home)

        # check if pp_home exists.
        # try for 10 seconds to allow usb stick to automount
        found = False
        for i in range(1, 10):
            self.mon.log(self,
                         "Trying pp_home at: " + home + " (" + str(i) + ')')
            if os.path.exists(home):
                found = True
                self.pp_home = home
                break
            time.sleep(1)
        if found is True:
            self.mon.log(
                self,
                "Found Requested Home Directory, using pp_home at: " + home)
        else:
            self.mon.err(self, "Failed to find pp_home directory at " + home)
            self.end('error', "Failed to find pp_home directory at " + home)

        # check profile exists
        self.pp_profile = self.pp_home + self.pp_profile_path
        if os.path.exists(self.pp_profile):
            self.mon.sched(self, "Running profile: " + self.pp_profile_path)
            self.mon.log(
                self, "Found Requested profile - pp_profile directory is: " +
                self.pp_profile)
        else:
            self.mon.err(
                self, "Failed to find requested profile: " + self.pp_profile)
            self.end('error',
                     "Failed to find requested profile: " + self.pp_profile)

        self.mon.start_stats(self.options['profile'])

        if self.options['verify'] is True:
            val = Validator()
            if val.validate_profile(None, pp_dir, self.pp_home,
                                    self.pp_profile, self.pipresents_issue,
                                    False) is False:
                self.mon.err(self, "Validation Failed")
                self.end('error', 'Validation Failed')

        # initialise and read the showlist in the profile
        self.showlist = ShowList()
        self.showlist_file = self.pp_profile + "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self, "showlist not found at " + self.showlist_file)
            self.end('error', "showlist not found at " + self.showlist_file)

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue()) != float(self.pipresents_issue):
            self.mon.err(
                self, "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents")
            self.end(
                'error', "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents")

        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >= 0:
            self.showlist.select(index)
            self.starter_show = self.showlist.selected_show()
        else:
            self.mon.err(self, "Show [start] not found in showlist")
            self.end('error', "Show [start] not found in showlist")

# ********************
# SET UP THE GUI
# ********************
# turn off the screenblanking and saver
        if self.options['noblank'] is True:
            call(["xset", "s", "off"])
            call(["xset", "s", "-dpms"])

        self.root = Tk()

        self.title = 'Pi Presents - ' + self.pp_profile
        self.icon_text = 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg=self.pp_background)

        self.mon.log(
            self, 'native screen dimensions are ' +
            str(self.root.winfo_screenwidth()) + ' x ' +
            str(self.root.winfo_screenheight()) + ' pixcels')
        if self.options['screensize'] == '':
            self.screen_width = self.root.winfo_screenwidth()
            self.screen_height = self.root.winfo_screenheight()
        else:
            reason, message, self.screen_width, self.screen_height = self.parse_screen(
                self.options['screensize'])
            if reason == 'error':
                self.mon.err(self, message)
                self.end('error', message)

        self.mon.log(
            self, 'commanded screen dimensions are ' + str(self.screen_width) +
            ' x ' + str(self.screen_height) + ' pixcels')

        # set window dimensions and decorations
        if self.options['fullscreen'] is False:
            self.window_width = int(self.root.winfo_screenwidth() *
                                    self.nonfull_window_width)
            self.window_height = int(self.root.winfo_screenheight() *
                                     self.nonfull_window_height)
            self.window_x = self.nonfull_window_x
            self.window_y = self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
        else:
            self.window_width = self.screen_width
            self.window_height = self.screen_height
            self.root.attributes('-fullscreen', True)
            os.system('unclutter &')
            self.window_x = 0
            self.window_y = 0
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
            self.root.attributes('-zoomed', '1')

        # canvas cover the whole screen whatever the size of the window.
        self.canvas_height = self.screen_height
        self.canvas_width = self.screen_width

        # make sure focus is set.
        self.root.focus_set()

        # define response to main window closing.
        self.root.protocol("WM_DELETE_WINDOW", self.handle_user_abort)

        # setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg=self.pp_background)

        if self.options['fullscreen'] is True:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=0)
        else:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=1,
                               highlightcolor='yellow')

        self.canvas.place(x=0, y=0)
        # self.canvas.config(bg='black')
        self.canvas.focus_set()

        # ****************************************
        # INITIALISE THE INPUT DRIVERS
        # ****************************************

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd = KbdDriver()
        if kbd.read(pp_dir, self.pp_home, self.pp_profile) is False:
            self.end('error', 'cannot find, or error in keys.cfg')
        kbd.bind_keys(self.root, self.handle_input_event)

        self.sr = ScreenDriver()
        # read the screen click area config file
        reason, message = self.sr.read(pp_dir, self.pp_home, self.pp_profile)
        if reason == 'error':
            self.end('error', 'cannot find, or error in screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        # click areas are made on the Pi Presents canvas not the show canvases.
        reason, message = self.sr.make_click_areas(self.canvas,
                                                   self.handle_input_event)
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required = False
        self.exitpipresents_required = False

        # delete omxplayer dbus files
        # if os.path.exists("/tmp/omxplayerdbus.{}".format(user)):
        # os.remove("/tmp/omxplayerdbus.{}".format(user))
        # if os.path.exists("/tmp/omxplayerdbus.{}.pid".format(user)):
        # os.remove("/tmp/omxplayerdbus.{}.pid".format(user))

        # kick off GPIO if enabled by command line option
        self.gpio_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'gpio.cfg'):
            # initialise the GPIO
            self.gpiodriver = GPIODriver()
            reason, message = self.gpiodriver.init(pp_dir, self.pp_home,
                                                   self.pp_profile,
                                                   self.canvas, 50,
                                                   self.handle_input_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.gpio_enabled = True
                # and start polling gpio
                self.gpiodriver.poll()

        # kick off animation sequencer
        self.animate = Animate()
        self.animate.init(pp_dir, self.pp_home, self.pp_profile, self.canvas,
                          200, self.handle_output_event)
        self.animate.poll()

        #create a showmanager ready for time of day scheduler and osc server
        show_id = -1
        self.show_manager = ShowManager(show_id, self.showlist,
                                        self.starter_show, self.root,
                                        self.canvas, self.pp_dir,
                                        self.pp_profile, self.pp_home)
        # first time through set callback to terminate Pi Presents if all shows have ended.
        self.show_manager.init(self.canvas, self.all_shows_ended_callback,
                               self.handle_command, self.showlist)
        # Register all the shows in the showlist
        reason, message = self.show_manager.register_shows()
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

        # Init OSCDriver, read config and start OSC server
        self.osc_enabled = False
        if self.network_connected is True:
            if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' +
                              os.sep + 'osc.cfg'):
                self.oscdriver = OSCDriver()
                reason, message = self.oscdriver.init(
                    self.pp_profile, self.handle_command,
                    self.handle_input_event, self.e_osc_handle_output_event)
                if reason == 'error':
                    self.end('error', message)
                else:
                    self.osc_enabled = True
                    self.root.after(1000, self.oscdriver.start_server())

        # enable ToD scheduler if schedule exists
        if os.path.exists(self.pp_profile + os.sep + 'schedule.json'):
            self.tod_enabled = True
        else:
            self.tod_enabled = False

        # warn if the network not available when ToD required

        if self.tod_enabled is True and self.network_connected is False:
            self.mon.warn(
                self,
                'Network not connected  so Time of Day scheduler may be using the internal clock'
            )

        # warn about start shows and scheduler

        if self.starter_show['start-show'] == '' and self.tod_enabled is False:
            self.mon.sched(
                self, "No Start Shows in Start Show and no shows scheduled")
            self.mon.warn(
                self, "No Start Shows in Start Show and no shows scheduled")

        if self.starter_show['start-show'] != '' and self.tod_enabled is True:
            self.mon.sched(
                self,
                "Start Shows in Start Show and shows scheduled - conflict?")
            self.mon.warn(
                self,
                "Start Shows in Start Show and shows scheduled - conflict?")

        # run the start shows
        self.run_start_shows()

        # kick off the time of day scheduler which may run additional shows
        if self.tod_enabled is True:
            self.tod = TimeOfDay()
            self.tod.init(pp_dir, self.pp_home, self.pp_profile, self.root,
                          self.handle_command)
            self.tod.poll()

        # start Tkinters event loop
        self.root.mainloop()

    def parse_screen(self, size_text):
        fields = size_text.split('*')
        if len(fields) != 2:
            return 'error', 'do not understand --fullscreen comand option', 0, 0
        elif fields[0].isdigit() is False or fields[1].isdigit() is False:
            return 'error', 'dimensions are not positive integers in --fullscreen', 0, 0
        else:
            return 'normal', '', int(fields[0]), int(fields[1])

# *********************
#  RUN START SHOWS
# ********************

    def run_start_shows(self):
        self.mon.trace(self, 'run start shows')
        # parse the start shows field and start the initial shows
        show_refs = self.starter_show['start-show'].split()
        for show_ref in show_refs:
            reason, message = self.show_manager.control_a_show(
                show_ref, 'open')
            if reason == 'error':
                self.mon.err(self, message)

# *********************
# User inputs
# ********************
# handles one command provided as a line of text

    def handle_command(self, command_text, source=''):
        self.mon.log(self, "command received: " + command_text)
        if command_text.strip() == "":
            return

        if command_text[0] == '/':
            if self.osc_enabled is True:
                self.oscdriver.send_command(command_text)
            return

        fields = command_text.split()
        show_command = fields[0]
        if len(fields) > 1:
            show_ref = fields[1]
        else:
            show_ref = ''

        if show_command in ('open', 'close'):
            self.mon.sched(self,
                           command_text + ' received from show:' + source)
            if self.shutdown_required is False:
                reason, message = self.show_manager.control_a_show(
                    show_ref, show_command)
            else:
                return
        elif show_command == 'exitpipresents':
            self.exitpipresents_required = True
            if self.show_manager.all_shows_exited() is True:
                # need root.after to get out of st thread
                self.root.after(1, self.e_all_shows_ended_callback)
                return
            else:
                reason, message = self.show_manager.exit_all_shows()

        elif show_command == 'shutdownnow':
            # need root.after to get out of st thread
            self.root.after(1, self.e_shutdown_pressed)
            return
        else:
            reason = 'error'
            message = 'command not recognised: ' + show_command

        if reason == 'error':
            self.mon.err(self, message)
        return

    def e_all_shows_ended_callback(self):
        self.all_shows_ended_callback('normal', 'no shows running')

    def e_shutdown_pressed(self):
        self.shutdown_pressed('now')

    def e_osc_handle_output_event(self, line):
        #jump  out of server thread
        self.root.after(1, lambda arg=line: self.osc_handle_output_event(arg))

    def osc_handle_output_event(self, line):
        self.mon.log(self, "output event received: " + line)
        #osc sends output events as a string
        reason, message, delay, name, param_type, param_values = self.animate.parse_animate_fields(
            line)
        if reason == 'error':
            self.mon.err(self, message)
            self.end(reason, message)
        self.handle_output_event(name, param_type, param_values, 0)

    def handle_output_event(self, symbol, param_type, param_values, req_time):
        if self.gpio_enabled is True:
            reason, message = self.gpiodriver.handle_output_event(
                symbol, param_type, param_values, req_time)
            if reason == 'error':
                self.mon.err(self, message)
                self.end(reason, message)
        else:
            self.mon.warn(self, 'GPIO not enabled')

    # all input events call this callback with a symbolic name.
    # handle events that affect PP overall, otherwise pass to all active shows
    def handle_input_event(self, symbol, source):
        self.mon.log(self, "event received: " + symbol + ' from ' + source)
        if symbol == 'pp-terminate':
            self.handle_user_abort()

        elif symbol == 'pp-shutdown':
            self.shutdown_pressed('delay')

        elif symbol == 'pp-shutdownnow':
            # need root.after to grt out of st thread
            self.root.after(1, self.e_shutdown_pressed)
            return

        elif symbol == 'pp-exitpipresents':
            self.exitpipresents_required = True
            if self.show_manager.all_shows_exited() is True:
                # need root.after to grt out of st thread
                self.root.after(1, self.e_all_shows_ended_callback)
                return
            reason, message = self.show_manager.exit_all_shows()
        else:
            # events for shows affect the show and could cause it to exit.
            for show in self.show_manager.shows:
                show_obj = show[ShowManager.SHOW_OBJ]
                if show_obj is not None:
                    show_obj.handle_input_event(symbol)

    def shutdown_pressed(self, when):
        if when == 'delay':
            self.root.after(5000, self.on_shutdown_delay)
        else:
            self.shutdown_required = True
            if self.show_manager.all_shows_exited() is True:
                self.all_shows_ended_callback('normal', 'no shows running')
            else:
                # calls exit method of all shows, results in all_shows_closed_callback
                self.show_manager.exit_all_shows()

    def on_shutdown_delay(self):
        # 5 second delay is up, if shutdown button still pressed then shutdown
        if self.gpiodriver.shutdown_pressed() is True:
            self.shutdown_required = True
            if self.show_manager.all_shows_exited() is True:
                self.all_shows_ended_callback('normal', 'no shows running')
            else:
                # calls exit method of all shows, results in all_shows_closed_callback
                self.show_manager.exit_all_shows()

    def handle_sigterm(self, signum, frame):
        self.mon.log(self, 'SIGTERM received - ' + str(signum))
        self.terminate()

    def handle_user_abort(self):
        self.mon.log(self, 'User abort received')
        self.terminate()

    def terminate(self):
        self.mon.log(self, "terminate received")
        needs_termination = False
        for show in self.show_manager.shows:
            # print  show[ShowManager.SHOW_OBJ], show[ShowManager.SHOW_REF]
            if show[ShowManager.SHOW_OBJ] is not None:
                needs_termination = True
                self.mon.log(
                    self,
                    "Sent terminate to show " + show[ShowManager.SHOW_REF])
                # call shows terminate method
                # eventually the show will exit and after all shows have exited all_shows_callback will be executed.
                show[ShowManager.SHOW_OBJ].terminate()
        if needs_termination is False:
            self.end('killed', 'killed - no termination of shows required')

# ******************************
# Ending Pi Presents after all the showers and players are closed
# **************************

# callback from ShowManager when all shows have ended

    def all_shows_ended_callback(self, reason, message):
        self.canvas.config(bg=self.pp_background)
        if reason in (
                'killed', 'error'
        ) or self.shutdown_required is True or self.exitpipresents_required is True:
            self.end(reason, message)

    def end(self, reason, message):
        self.mon.log(self, "Pi Presents ending with reason: " + reason)
        if self.root is not None:
            self.root.destroy()
        self.tidy_up()
        # gc.collect()
        # print gc.garbage
        if reason == 'killed':
            if self.email_enabled is True and self.mailer.email_on_terminate is True:
                subject = '[Pi Presents] ' + self.unit + ': PP Exited with reason: Terminated'
                message = time.strftime(
                    "%Y-%m-%d %H:%M"
                ) + '\n ' + self.unit + '\n ' + self.interface + '\n ' + self.ip
                self.send_email(reason, subject, message)
            self.mon.sched(self, "Pi Presents Terminated, au revoir\n")
            self.mon.log(self, "Pi Presents Terminated, au revoir")

            # close logging files
            self.mon.finish()
            sys.exit(101)

        elif reason == 'error':
            if self.email_enabled is True and self.mailer.email_on_error is True:
                subject = '[Pi Presents] ' + self.unit + ': PP Exited with reason: Error'
                message_text = 'Error message: ' + message + '\n' + time.strftime(
                    "%Y-%m-%d %H:%M"
                ) + '\n ' + self.unit + '\n ' + self.interface + '\n ' + self.ip
                self.send_email(reason, subject, message_text)
            self.mon.sched(self,
                           "Pi Presents closing because of error, sorry\n")
            self.mon.log(self, "Pi Presents closing because of error, sorry")

            # close logging files
            self.mon.finish()
            sys.exit(102)

        else:
            self.mon.sched(self, "Pi Presents  exiting normally, bye\n")
            self.mon.log(self, "Pi Presents  exiting normally, bye")

            # close logging files
            self.mon.finish()
            if self.shutdown_required is True:
                # print 'SHUTDOWN'
                call(['sudo', 'shutdown', '-h', '-t 5', 'now'])
            sys.exit(100)

    def init_network(self):

        timeout = int(self.options['nonetwork'])
        if timeout == 0:
            self.network_connected = False
            self.unit = ''
            self.ip = ''
            self.interface = ''
            return

        self.network = Network()
        self.network_connected = False

        # try to connect to network
        self.mon.log(self,
                     'Waiting up to ' + str(timeout) + ' seconds for network')
        success = self.network.wait_for_network(timeout)
        if success is False:
            self.mon.warn(
                self, 'Failed to connect to network after ' + str(timeout) +
                ' seconds')
            # tkMessageBox.showwarning("Pi Presents","Failed to connect to network so using fake-hwclock")
            return

        self.network_connected = True
        self.mon.sched(
            self, 'Time after network check is ' +
            time.strftime("%Y-%m-%d %H:%M.%S"))
        self.mon.log(
            self, 'Time after network check is ' +
            time.strftime("%Y-%m-%d %H:%M.%S"))

        # Get web configuration
        self.network_details = False
        network_options_file_path = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_web.cfg'
        if not os.path.exists(network_options_file_path):
            self.mon.warn(
                self, "pp_web.cfg not found at " + network_options_file_path)
            return
        self.mon.log(self, 'Found pp_web.cfg in ' + network_options_file_path)

        self.network.read_config(network_options_file_path)
        self.unit = self.network.unit

        # get interface and IP details of preferred interface
        self.interface, self.ip = self.network.get_preferred_ip()
        if self.interface == '':
            self.network_connected = False
            return
        self.network_details = True
        self.mon.log(
            self, 'Network details ' + self.unit + ' ' + self.interface + ' ' +
            self.ip)

    def init_mailer(self):

        self.email_enabled = False
        email_file_path = self.pp_dir + os.sep + 'pp_config' + os.sep + 'pp_email.cfg'
        if not os.path.exists(email_file_path):
            self.mon.log(self, 'pp_email.cfg not found at ' + email_file_path)
            return
        self.mon.log(self, 'Found pp_email.cfg at ' + email_file_path)
        self.mailer = Mailer()
        self.mailer.read_config(email_file_path)
        # all Ok so can enable email if config file allows it.
        if self.mailer.email_allowed is True:
            self.email_enabled = True
            self.mon.log(self, 'Email Enabled')


##    def send_email(self,reason,subject,message):
##        success, error = self.mailer.connect()
##        if success is False:
##            self.mon.log(self, 'Failed to connect to email SMTP server ' + str(error))
##            return
##        else:
##            success,error = self.mailer.send(subject,message)
##            if success is False:
##                self.mon.log(self, 'Failed to send email: ' + str(error))
##                self.mailer.disconnect()
##                return
##            else:
##                self.mon.log(self, 'Sent email for ' + reason)
##                self.mailer.disconnect()
##                return

    def send_email(self, reason, subject, message):
        if self.try_connect() is False:
            return False
        else:
            success, error = self.mailer.send(subject, message)
            if success is False:
                self.mon.log(self, 'Failed to send email: ' + str(error))
                success, error = self.mailer.disconnect()
                if success is False:
                    self.mon.log(self,
                                 'Failed disconnect after send:' + str(error))
                return False
            else:
                self.mon.log(self, 'Sent email for ' + reason)
                success, error = self.mailer.disconnect()
                if success is False:
                    self.mon.log(
                        self,
                        'Failed disconnect from email server ' + str(error))
                return True

    def try_connect(self):
        tries = 1
        while True:
            success, error = self.mailer.connect()
            if success is True:
                return True
            else:
                self.mon.log(
                    self, 'Failed to connect to email SMTP server ' +
                    str(tries) + '\n ' + str(error))
                tries += 1
                if tries > 5:
                    self.mon.log(
                        self, 'Failed to connect to email SMTP server after ' +
                        str(tries))
                    return False

    # tidy up all the peripheral bits of Pi Presents
    def tidy_up(self):
        self.mon.log(self, "Tidying Up")
        # turn screen blanking back on
        if self.options['noblank'] is True:
            call(["xset", "s", "on"])
            call(["xset", "s", "+dpms"])

        # tidy up animation and gpio
        if self.animate is not None:
            self.animate.terminate()

        if self.gpio_enabled == True:
            self.gpiodriver.terminate()

        if self.osc_enabled is True:
            self.oscdriver.terminate()

        # tidy up time of day scheduler
        if self.tod_enabled is True:
            self.tod.terminate()
Esempio n. 53
0
 def __init__(self):
     self.mon = Monitor()
     self.dm = DisplayManager()
Esempio n. 54
0
    def __init__(self):
        gc.set_debug(gc.DEBUG_UNCOLLECTABLE | gc.DEBUG_INSTANCES
                     | gc.DEBUG_OBJECTS | gc.DEBUG_SAVEALL)
        self.pipresents_issue = "1.3"
        self.pipresents_minorissue = '1.3.1i'
        # position and size of window without -f command line option
        self.nonfull_window_width = 0.45  # proportion of width
        self.nonfull_window_height = 0.7  # proportion of height
        self.nonfull_window_x = 0  # position of top left corner
        self.nonfull_window_y = 0  # position of top left corner
        self.pp_background = 'black'

        StopWatch.global_enable = False

        # set up the handler for SIGTERM
        signal.signal(signal.SIGTERM, self.handle_sigterm)

        # ****************************************
        # Initialisation
        # ***************************************
        # get command line options
        self.options = command_options()

        # get Pi Presents code directory
        pp_dir = sys.path[0]
        self.pp_dir = pp_dir

        if not os.path.exists(pp_dir + "/pipresents.py"):
            if self.options['manager'] is False:
                tkMessageBox.showwarning("Pi Presents",
                                         "Bad Application Directory")
            exit(102)

        # Initialise logging and tracing
        Monitor.log_path = pp_dir
        self.mon = Monitor()
        # Init in PiPresents only
        self.mon.init()

        # uncomment to enable control of logging from within a class
        # Monitor.enable_in_code = True # enables control of log level in the code for a class  - self.mon.set_log_level()

        # make a shorter list to log/trace only some classes without using enable_in_code.
        Monitor.classes = [
            'PiPresents', 'HyperlinkShow', 'RadioButtonShow', 'ArtLiveShow',
            'ArtMediaShow', 'MediaShow', 'LiveShow', 'MenuShow', 'GapShow',
            'Show', 'ArtShow', 'AudioPlayer', 'BrowserPlayer', 'ImagePlayer',
            'MenuPlayer', 'MessagePlayer', 'VideoPlayer', 'Player',
            'MediaList', 'LiveList', 'ShowList', 'PathManager',
            'ControlsManager', 'ShowManager', 'PluginManager', 'MplayerDriver',
            'OMXDriver', 'UZBLDriver', 'KbdDriver', 'GPIODriver', 'TimeOfDay',
            'ScreenDriver', 'Animate', 'OSCDriver', 'Network', 'Mailer',
            'RadioMediaShow'
        ]

        # Monitor.classes=['PiPresents','MediaShow','GapShow','Show','VideoPlayer','Player','OMXDriver']

        # get global log level from command line
        Monitor.log_level = int(self.options['debug'])
        Monitor.manager = self.options['manager']
        # print self.options['manager']
        self.mon.newline(3)
        self.mon.sched(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue +
            ' at ' + time.strftime("%Y-%m-%d %H:%M.%S"))
        self.mon.log(
            self,
            "Pi Presents is starting, Version:" + self.pipresents_minorissue +
            ' at ' + time.strftime("%Y-%m-%d %H:%M.%S"))
        # self.mon.log (self," OS and separator:" + os.name +'  ' + os.sep)
        self.mon.log(self, "sys.path[0] -  location of code: " + sys.path[0])

        # log versions of Raspbian and omxplayer, and GPU Memory
        with open("/boot/issue.txt") as file:
            self.mon.log(self, '\nRaspbian: ' + file.read())

        self.mon.log(self, '\n' + check_output(["omxplayer", "-v"]))
        self.mon.log(
            self,
            '\nGPU Memory: ' + check_output(["vcgencmd", "get_mem", "gpu"]))

        # optional other classes used
        self.root = None
        self.ppio = None
        self.tod = None
        self.animate = None
        self.gpiodriver = None
        self.oscdriver = None
        self.osc_enabled = False
        self.gpio_enabled = False
        self.tod_enabled = False
        self.email_enabled = False

        if os.geteuid() == 0:
            self.mon.err(self, 'Do not run Pi Presents with sudo')
            self.end('error', 'Do not run Pi Presents with sudo')

        user = os.getenv('USER')

        self.mon.log(self, 'User is: ' + user)
        # self.mon.log(self,"os.getenv('HOME') -  user home directory (not used): " + os.getenv('HOME')) # does not work
        # self.mon.log(self,"os.path.expanduser('~') -  user home directory: " + os.path.expanduser('~'))   # does not work

        # check network is available
        self.network_connected = False
        self.network_details = False
        self.interface = ''
        self.ip = ''
        self.unit = ''

        # sets self.network_connected and self.network_details
        self.init_network()

        # start the mailer and send email when PP starts
        self.email_enabled = False
        if self.network_connected is True:
            self.init_mailer()
            if self.email_enabled is True and self.mailer.email_at_start is True:
                subject = '[Pi Presents] ' + self.unit + ': PP Started on ' + time.strftime(
                    "%Y-%m-%d %H:%M")
                message = time.strftime(
                    "%Y-%m-%d %H:%M"
                ) + '\n ' + self.unit + '\n ' + self.interface + '\n ' + self.ip
                self.send_email('start', subject, message)

        # get profile path from -p option
        if self.options['profile'] != '':
            self.pp_profile_path = "/pp_profiles/" + self.options['profile']
        else:
            self.mon.err(self, "Profile not specified in command ")
            self.end('error',
                     'Profile not specified with the commands -p option')

    # get directory containing pp_home from the command,
        if self.options['home'] == "":
            home = os.sep + 'home' + os.sep + user + os.sep + "pp_home"
        else:
            home = self.options['home'] + os.sep + "pp_home"
        self.mon.log(self, "pp_home directory is: " + home)

        # check if pp_home exists.
        # try for 10 seconds to allow usb stick to automount
        found = False
        for i in range(1, 10):
            self.mon.log(self,
                         "Trying pp_home at: " + home + " (" + str(i) + ')')
            if os.path.exists(home):
                found = True
                self.pp_home = home
                break
            time.sleep(1)
        if found is True:
            self.mon.log(
                self,
                "Found Requested Home Directory, using pp_home at: " + home)
        else:
            self.mon.err(self, "Failed to find pp_home directory at " + home)
            self.end('error', "Failed to find pp_home directory at " + home)

        # check profile exists
        self.pp_profile = self.pp_home + self.pp_profile_path
        if os.path.exists(self.pp_profile):
            self.mon.sched(self, "Running profile: " + self.pp_profile_path)
            self.mon.log(
                self, "Found Requested profile - pp_profile directory is: " +
                self.pp_profile)
        else:
            self.mon.err(
                self, "Failed to find requested profile: " + self.pp_profile)
            self.end('error',
                     "Failed to find requested profile: " + self.pp_profile)

        self.mon.start_stats(self.options['profile'])

        if self.options['verify'] is True:
            val = Validator()
            if val.validate_profile(None, pp_dir, self.pp_home,
                                    self.pp_profile, self.pipresents_issue,
                                    False) is False:
                self.mon.err(self, "Validation Failed")
                self.end('error', 'Validation Failed')

        # initialise and read the showlist in the profile
        self.showlist = ShowList()
        self.showlist_file = self.pp_profile + "/pp_showlist.json"
        if os.path.exists(self.showlist_file):
            self.showlist.open_json(self.showlist_file)
        else:
            self.mon.err(self, "showlist not found at " + self.showlist_file)
            self.end('error', "showlist not found at " + self.showlist_file)

        # check profile and Pi Presents issues are compatible
        if float(self.showlist.sissue()) != float(self.pipresents_issue):
            self.mon.err(
                self, "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents")
            self.end(
                'error', "Version of profile " + self.showlist.sissue() +
                " is not  same as Pi Presents")

        # get the 'start' show from the showlist
        index = self.showlist.index_of_show('start')
        if index >= 0:
            self.showlist.select(index)
            self.starter_show = self.showlist.selected_show()
        else:
            self.mon.err(self, "Show [start] not found in showlist")
            self.end('error', "Show [start] not found in showlist")

# ********************
# SET UP THE GUI
# ********************
# turn off the screenblanking and saver
        if self.options['noblank'] is True:
            call(["xset", "s", "off"])
            call(["xset", "s", "-dpms"])

        self.root = Tk()

        self.title = 'Pi Presents - ' + self.pp_profile
        self.icon_text = 'Pi Presents'
        self.root.title(self.title)
        self.root.iconname(self.icon_text)
        self.root.config(bg=self.pp_background)

        self.mon.log(
            self, 'native screen dimensions are ' +
            str(self.root.winfo_screenwidth()) + ' x ' +
            str(self.root.winfo_screenheight()) + ' pixcels')
        if self.options['screensize'] == '':
            self.screen_width = self.root.winfo_screenwidth()
            self.screen_height = self.root.winfo_screenheight()
        else:
            reason, message, self.screen_width, self.screen_height = self.parse_screen(
                self.options['screensize'])
            if reason == 'error':
                self.mon.err(self, message)
                self.end('error', message)

        self.mon.log(
            self, 'commanded screen dimensions are ' + str(self.screen_width) +
            ' x ' + str(self.screen_height) + ' pixcels')

        # set window dimensions and decorations
        if self.options['fullscreen'] is False:
            self.window_width = int(self.root.winfo_screenwidth() *
                                    self.nonfull_window_width)
            self.window_height = int(self.root.winfo_screenheight() *
                                     self.nonfull_window_height)
            self.window_x = self.nonfull_window_x
            self.window_y = self.nonfull_window_y
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
        else:
            self.window_width = self.screen_width
            self.window_height = self.screen_height
            self.root.attributes('-fullscreen', True)
            os.system('unclutter &')
            self.window_x = 0
            self.window_y = 0
            self.root.geometry("%dx%d%+d%+d" %
                               (self.window_width, self.window_height,
                                self.window_x, self.window_y))
            self.root.attributes('-zoomed', '1')

        # canvas cover the whole screen whatever the size of the window.
        self.canvas_height = self.screen_height
        self.canvas_width = self.screen_width

        # make sure focus is set.
        self.root.focus_set()

        # define response to main window closing.
        self.root.protocol("WM_DELETE_WINDOW", self.handle_user_abort)

        # setup a canvas onto which will be drawn the images or text
        self.canvas = Canvas(self.root, bg=self.pp_background)

        if self.options['fullscreen'] is True:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=0)
        else:
            self.canvas.config(height=self.canvas_height,
                               width=self.canvas_width,
                               highlightthickness=1,
                               highlightcolor='yellow')

        self.canvas.place(x=0, y=0)
        # self.canvas.config(bg='black')
        self.canvas.focus_set()

        # ****************************************
        # INITIALISE THE INPUT DRIVERS
        # ****************************************

        # each driver takes a set of inputs, binds them to symboic names
        # and sets up a callback which returns the symbolic name when an input event occurs/

        # use keyboard driver to bind keys to symbolic names and to set up callback
        kbd = KbdDriver()
        if kbd.read(pp_dir, self.pp_home, self.pp_profile) is False:
            self.end('error', 'cannot find, or error in keys.cfg')
        kbd.bind_keys(self.root, self.handle_input_event)

        self.sr = ScreenDriver()
        # read the screen click area config file
        reason, message = self.sr.read(pp_dir, self.pp_home, self.pp_profile)
        if reason == 'error':
            self.end('error', 'cannot find, or error in screen.cfg')

        # create click areas on the canvas, must be polygon as outline rectangles are not filled as far as find_closest goes
        # click areas are made on the Pi Presents canvas not the show canvases.
        reason, message = self.sr.make_click_areas(self.canvas,
                                                   self.handle_input_event)
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

# ****************************************
# INITIALISE THE APPLICATION AND START
# ****************************************
        self.shutdown_required = False
        self.exitpipresents_required = False

        # delete omxplayer dbus files
        # if os.path.exists("/tmp/omxplayerdbus.{}".format(user)):
        # os.remove("/tmp/omxplayerdbus.{}".format(user))
        # if os.path.exists("/tmp/omxplayerdbus.{}.pid".format(user)):
        # os.remove("/tmp/omxplayerdbus.{}.pid".format(user))

        # kick off GPIO if enabled by command line option
        self.gpio_enabled = False
        if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' + os.sep +
                          'gpio.cfg'):
            # initialise the GPIO
            self.gpiodriver = GPIODriver()
            reason, message = self.gpiodriver.init(pp_dir, self.pp_home,
                                                   self.pp_profile,
                                                   self.canvas, 50,
                                                   self.handle_input_event)
            if reason == 'error':
                self.end('error', message)
            else:
                self.gpio_enabled = True
                # and start polling gpio
                self.gpiodriver.poll()

        # kick off animation sequencer
        self.animate = Animate()
        self.animate.init(pp_dir, self.pp_home, self.pp_profile, self.canvas,
                          200, self.handle_output_event)
        self.animate.poll()

        #create a showmanager ready for time of day scheduler and osc server
        show_id = -1
        self.show_manager = ShowManager(show_id, self.showlist,
                                        self.starter_show, self.root,
                                        self.canvas, self.pp_dir,
                                        self.pp_profile, self.pp_home)
        # first time through set callback to terminate Pi Presents if all shows have ended.
        self.show_manager.init(self.canvas, self.all_shows_ended_callback,
                               self.handle_command, self.showlist)
        # Register all the shows in the showlist
        reason, message = self.show_manager.register_shows()
        if reason == 'error':
            self.mon.err(self, message)
            self.end('error', message)

        # Init OSCDriver, read config and start OSC server
        self.osc_enabled = False
        if self.network_connected is True:
            if os.path.exists(self.pp_profile + os.sep + 'pp_io_config' +
                              os.sep + 'osc.cfg'):
                self.oscdriver = OSCDriver()
                reason, message = self.oscdriver.init(
                    self.pp_profile, self.handle_command,
                    self.handle_input_event, self.e_osc_handle_output_event)
                if reason == 'error':
                    self.end('error', message)
                else:
                    self.osc_enabled = True
                    self.root.after(1000, self.oscdriver.start_server())

        # enable ToD scheduler if schedule exists
        if os.path.exists(self.pp_profile + os.sep + 'schedule.json'):
            self.tod_enabled = True
        else:
            self.tod_enabled = False

        # warn if the network not available when ToD required

        if self.tod_enabled is True and self.network_connected is False:
            self.mon.warn(
                self,
                'Network not connected  so Time of Day scheduler may be using the internal clock'
            )

        # warn about start shows and scheduler

        if self.starter_show['start-show'] == '' and self.tod_enabled is False:
            self.mon.sched(
                self, "No Start Shows in Start Show and no shows scheduled")
            self.mon.warn(
                self, "No Start Shows in Start Show and no shows scheduled")

        if self.starter_show['start-show'] != '' and self.tod_enabled is True:
            self.mon.sched(
                self,
                "Start Shows in Start Show and shows scheduled - conflict?")
            self.mon.warn(
                self,
                "Start Shows in Start Show and shows scheduled - conflict?")

        # run the start shows
        self.run_start_shows()

        # kick off the time of day scheduler which may run additional shows
        if self.tod_enabled is True:
            self.tod = TimeOfDay()
            self.tod.init(pp_dir, self.pp_home, self.pp_profile, self.root,
                          self.handle_command)
            self.tod.poll()

        # start Tkinters event loop
        self.root.mainloop()
Esempio n. 55
0
class Player(object):

    # common bits of __init__(...)
    def __init__(self, show_id, showlist, root, canvas, show_params,
                 track_params, pp_dir, pp_home, pp_profile, end_callback,
                 command_callback):

        # create debugging log object
        self.mon = Monitor()

        self.mon.trace(self, '')

        # instantiate arguments
        self.show_id = show_id
        self.showlist = showlist
        self.root = root
        self.canvas = canvas['canvas-obj']
        self.show_canvas_x1 = canvas['show-canvas-x1']
        self.show_canvas_y1 = canvas['show-canvas-y1']
        self.show_canvas_x2 = canvas['show-canvas-x2']
        self.show_canvas_y2 = canvas['show-canvas-y2']
        self.show_canvas_width = canvas['show-canvas-width']
        self.show_canvas_height = canvas['show-canvas-height']
        self.show_canvas_centre_x = canvas['show-canvas-centre-x']
        self.show_canvas_centre_y = canvas['show-canvas-centre-y']
        self.show_params = show_params
        self.track_params = track_params
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile
        self.end_callback = end_callback
        self.command_callback = command_callback

        # get background image from profile.
        self.background_file = ''
        if self.track_params['background-image'] != '':
            self.background_file = self.track_params['background-image']

        # get background colour from profile.
        if self.track_params['background-colour'] != '':
            self.background_colour = self.track_params['background-colour']
        else:
            self.background_colour = self.show_params['background-colour']

        # get animation instructions from profile
        self.animate_begin_text = self.track_params['animate-begin']
        self.animate_end_text = self.track_params['animate-end']

        # create an  instance of showmanager so we can control concurrent shows
        # self.show_manager=ShowManager(self.show_id,self.showlist,self.show_params,self.root,self.canvas,self.pp_dir,self.pp_profile,self.pp_home)

        # open the plugin Manager
        self.pim = PluginManager(self.show_id, self.root, self.canvas,
                                 self.show_params, self.track_params,
                                 self.pp_dir, self.pp_home, self.pp_profile)

        # create an instance of Animate so we can send animation commands
        self.animate = Animate()

        # initialise state and signals
        self.background_obj = None
        self.show_text_obj = None
        self.track_text_obj = None
        self.hint_obj = None
        self.background = None
        self.freeze_at_end_required = 'no'  # overriden by videoplayer
        self.tick_timer = None
        self.terminate_signal = False
        self.play_state = ''

    def pre_load(self):
        # Control other shows at beginning
        self.show_control(self.track_params['show-control-begin'])
        pass

    # common bits of show(....)
    def pre_show(self):
        self.mon.trace(self, '')

        # show_x_content moved to just before ready_callback to improve flicker.
        self.show_x_content()

        # and whatecer the plugin has created
        self.pim.show_plugin()

        #ready callback hides and closes players from previous track, also displays show background
        if self.ready_callback is not None:
            self.ready_callback(self.enable_show_background)

        # create animation events
        reason, message = self.animate.animate(self.animate_begin_text,
                                               id(self))
        if reason == 'error':
            self.mon.err(self, message)
            self.play_state = 'show-failed'
            if self.finished_callback is not None:
                self.finished_callback('error', message)
        else:
            # return to start playing the track.
            self.mon.log(
                self,
                ">show track received from show Id: " + str(self.show_id))
            return

    # to keep landscape happy
    def ready_callback(self, enable_show_background):
        self.mon.fatal(self, 'ready callback not overridden')
        self.end('error', 'ready callback not overridden')

    def finished_callback(self, reason, message):
        self.mon.fatal(self, 'finished callback not overridden')
        self.end('error', 'finished callback not overridden')

    def closed_callback(self, reason, message):
        self.mon.fatal(self, 'closed callback not overridden')
        self.end('error', 'closed callback not overridden')

# Control shows so pass the show control commands back to PiPresents via the command callback

    def show_control(self, show_control_text):
        lines = show_control_text.split('\n')
        for line in lines:
            if line.strip() == "":
                continue
            # print 'show control command: ',line
            self.command_callback(line, self.show_params['show-ref'])

# *****************
# hide content and end animation, show control etc.
# called by ready calback and end
# *****************

    def hide(self):
        self.mon.trace(self, '')
        # abort the timer
        if self.tick_timer is not None:
            self.canvas.after_cancel(self.tick_timer)
            self.tick_timer = None

        self.hide_x_content()

        # stop the plugin
        if self.track_params['plugin'] != '':
            self.pim.stop_plugin()

        # Control concurrent shows at end
        self.show_control(self.track_params['show-control-end'])

        # clear events list for this track
        if self.track_params['animate-clear'] == 'yes':
            self.animate.clear_events_list(id(self))

        # create animation events for ending
        reason, message = self.animate.animate(self.animate_end_text, id(self))
        if reason == 'error':
            self.play_state = 'show-failed'
            if self.finished_callback is not None:
                self.finished_callback('error', message)
        else:
            return

    def terminate(self):
        self.mon.trace(self, '')
        self.terminate_signal = True
        if self.play_state == 'showing':
            # call the derived class's stop method
            self.stop()
        else:
            self.end('killed', 'terminate with no track or show open')

    # must be overriden by derived class
    def stop(self):
        self.mon.fatal(self, 'stop not overidden by derived class')
        self.play_state = 'show-failed'
        if self.finished_callback is not None:
            self.finished_callback('error',
                                   'stop not overidden by derived class')

    def get_play_state(self):
        return self.play_state

# *****************
# ending the player
# *****************

    def end(self, reason, message):
        self.mon.trace(self, '')
        # stop the plugin

        if self.terminate_signal is True:
            reason = 'killed'
            self.terminate_signal = False
            self.hide()

        self.end_callback(reason, message)
        self = None

# *****************
# displaying common things
# *****************

    def load_plugin(self):
        # load the plugin if required
        if self.track_params['plugin'] != '':
            reason, message, self.track = self.pim.load_plugin(
                self.track, self.track_params['plugin'])
            return reason, message

    def draw_plugin(self):
        # load the plugin if required
        if self.track_params['plugin'] != '':
            self.pim.draw_plugin()
            return

    def load_x_content(self, enable_menu):
        self.mon.trace(self, '')
        self.background_obj = None
        self.background = None
        self.track_text_obj = None
        self.show_text_obj = None
        self.hint_obj = None
        self.track_obj = None

        # background image
        if self.background_file != '':
            background_img_file = self.complete_path(self.background_file)
            if not os.path.exists(background_img_file):
                return 'error', "Track background file not found " + background_img_file
            else:
                pil_background_img = Image.open(background_img_file)
                # print 'pil_background_img ',pil_background_img
                image_width, image_height = pil_background_img.size
                window_width = self.show_canvas_width
                window_height = self.show_canvas_height
                if image_width != window_width or image_height != window_height:
                    pil_background_img = pil_background_img.resize(
                        (window_width, window_height))
                self.background = ImageTk.PhotoImage(pil_background_img)
                del pil_background_img
                self.background_obj = self.canvas.create_image(
                    self.show_canvas_x1,
                    self.show_canvas_y1,
                    image=self.background,
                    anchor=NW)
                # print '\nloaded background_obj: ',self.background_obj

        # load the track content.  Dummy function below is overridden in players
        status, message = self.load_track_content()
        if status == 'error':
            return 'error', message

        # load show text if enabled
        if self.show_params['show-text'] != '' and self.track_params[
                'display-show-text'] == 'yes':
            self.show_text_obj = self.canvas.create_text(
                int(self.show_params['show-text-x']) + self.show_canvas_x1,
                int(self.show_params['show-text-y']) + self.show_canvas_y1,
                anchor=NW,
                text=self.show_params['show-text'],
                fill=self.show_params['show-text-colour'],
                font=self.show_params['show-text-font'])

        # load track text if enabled
        if self.track_params['track-text'] != '':
            self.track_text_obj = self.canvas.create_text(
                int(self.track_params['track-text-x']) + self.show_canvas_x1,
                int(self.track_params['track-text-y']) + self.show_canvas_y1,
                anchor=NW,
                text=self.track_params['track-text'],
                fill=self.track_params['track-text-colour'],
                font=self.track_params['track-text-font'])

        # load instructions if enabled
        if enable_menu is True:
            self.hint_obj = self.canvas.create_text(
                int(self.show_params['hint-x']) + self.show_canvas_x1,
                int(self.show_params['hint-y']) + self.show_canvas_y1,
                text=self.show_params['hint-text'],
                fill=self.show_params['hint-colour'],
                font=self.show_params['hint-font'],
                anchor=NW)

        self.display_show_canvas_rectangle()

        self.pim.draw_plugin()

        self.canvas.tag_raise('pp-click-area')
        self.canvas.itemconfig(self.background_obj, state='hidden')
        self.canvas.itemconfig(self.show_text_obj, state='hidden')
        self.canvas.itemconfig(self.track_text_obj, state='hidden')
        self.canvas.itemconfig(self.hint_obj, state='hidden')
        self.canvas.update_idletasks()
        return 'normal', 'x-content loaded'

    # display the rectangle that is the show canvas
    def display_show_canvas_rectangle(self):
        # coords=[self.show_canvas_x1,self.show_canvas_y1,self.show_canvas_x2-1,self.show_canvas_y2-1]
        # self.canvas.create_rectangle(coords,
        #            outline='yellow',
        #          fill='')
        pass

    # dummy functions to manipulate the track content, overidden in some players,
    # message text in messageplayer
    # image in imageplayer
    # menu stuff in menuplayer

    def load_track_content(self):
        return 'normal', 'player has no track content to load'

    def show_track_content(self):
        pass

    def hide_track_content(self):
        pass

    def show_x_content(self):
        self.mon.trace(self, '')
        # background colour
        if self.background_colour != '':
            self.canvas.config(bg=self.background_colour)
        # print 'showing background_obj: ', self.background_obj
        # reveal background image and text
        self.canvas.itemconfig(self.background_obj, state='normal')
        self.show_track_content()

        self.canvas.itemconfig(self.show_text_obj, state='normal')
        self.canvas.itemconfig(self.track_text_obj, state='normal')
        self.canvas.itemconfig(self.hint_obj, state='normal')
        # self.canvas.update_idletasks( )

        # decide whether the show background should be enabled.
        # print 'DISPLAY SHOW BG',self.track_params['display-show-background'],self.background_obj
        if self.background_obj is None and self.track_params[
                'display-show-background'] == 'yes':
            self.enable_show_background = True
        else:
            self.enable_show_background = False
        # print 'ENABLE SB',self.enable_show_background

    def hide_x_content(self):
        self.mon.trace(self, '')
        self.hide_track_content()
        self.canvas.itemconfig(self.background_obj, state='hidden')
        self.canvas.itemconfig(self.show_text_obj, state='hidden')
        self.canvas.itemconfig(self.track_text_obj, state='hidden')
        self.canvas.itemconfig(self.hint_obj, state='hidden')
        # self.canvas.update_idletasks( )

        self.canvas.delete(self.background_obj)
        self.canvas.delete(self.show_text_obj)
        self.canvas.delete(self.track_text_obj)
        self.canvas.delete(self.hint_obj)
        self.background = None
        # self.canvas.update_idletasks( )

# ****************
# utilities
# *****************

    def get_links(self):
        return self.track_params['links']

    # produce an absolute path from the relative one in track paramters
    def complete_path(self, track_file):
        #  complete path of the filename of the selected entry
        if track_file[0] == "+":
            track_file = self.pp_home + track_file[1:]
        # self.mon.log(self,"Background image is "+ track_file)
        return track_file

    # get a text string from resources.cfg
    def resource(self, section, item):
        value = self.rr.get(section, item)
        return value  # False if not found
Esempio n. 56
0
class OSCDriver(object):

    # executed by main program
    def  init(self,pp_profile,manager_unit,preferred_interface,my_ip,show_command_callback,input_event_callback,animate_callback):

        self.pp_profile=pp_profile
        self.show_command_callback=show_command_callback
        self.input_event_callback=input_event_callback
        self.animate_callback=animate_callback

        self.mon=Monitor()
        config_file=self.pp_profile + os.sep +'pp_io_config'+os.sep+ 'osc.cfg'
        if not os.path.exists(config_file):
            self.mon.err(self, 'OSC Configuration file not found: '+config_file)
            return'error','OSC Configuration file nof found: '+config_file
        
        self.mon.log(self, 'OSC Configuration file found at: '+config_file)        
        self.osc_config=OSCConfig()
        
        # reads config data 
        if self.osc_config.read(config_file) ==False:
            return 'error','failed to read osc.cfg'

        # unpack config data and initialise

        if self.osc_config.this_unit_name =='':
            return 'error','OSC Config -  This Unit has no name'
        if len(self.osc_config.this_unit_name.split())>1:
            return 'error','OSC config - This Unit Name not a single word: '+self.osc_config.this_unit_name
        self.this_unit_name=self.osc_config.this_unit_name
               
                 
        if self.osc_config.this_unit_ip=='':
            self.this_unit_ip=my_ip
        else:
            self.this_unit_ip=self.osc_config.this_unit_ip

        if self.osc_config.slave_enabled == 'yes':
            if not self.osc_config.listen_port.isdigit():
                return 'error','OSC Config - Listen port is not a positve number: '+ self.osc_config.listen_port
            self.listen_port= self.osc_config.listen_port

        if self.osc_config.master_enabled == 'yes':
            if not self.osc_config.reply_listen_port.isdigit():
                return 'error','OSC Config - Reply Listen port is not a positve number: '+ self.osc_config.reply_listen_port
            self.reply_listen_port= self.osc_config.reply_listen_port

            # prepare the list of slaves
            status,message=self.parse_slaves()
            if status=='error':
                return status,message
             

        self.prefix='/pipresents'
        self.this_unit='/' + self.this_unit_name
        
        self.input_server=None
        self.input_reply_client=None
        self.input_st=None
        
        self.output_client=None
        self.output_reply_server=None
        self.output_reply_st=None


        if self.osc_config.slave_enabled == 'yes' and self.osc_config.master_enabled == 'yes' and self.listen_port == self.reply_listen_port:
            # The two listen ports are the same so use one server for input and output

            #start the client that sends commands to the slaves
            self.output_client=OSC.OSCClient()
            self.mon.log(self, 'sending commands to slaves and replies to master on: '+self.reply_listen_port)

            #start the input+output reply server
            self.mon.log(self, 'listen to commands and replies from slave units using: ' + self.this_unit_ip+':'+self.reply_listen_port)
            self.output_reply_server=myOSCServer((self.this_unit_ip,int(self.reply_listen_port)),self.output_client)
            self.add_default_handler(self.output_reply_server)
            self.add_input_handlers(self.output_reply_server)
            self.add_output_reply_handlers(self.output_reply_server)

            self.input_server=self.output_reply_server
            
        else:

            if self.osc_config.slave_enabled == 'yes':
                # we want this to be a slave to something else

                # start the client that sends replies to controlling unit
                self.input_reply_client=OSC.OSCClient()
                
                #start the input server
                self.mon.log(self, 'listening to commands on: ' + self.this_unit_ip+':'+self.listen_port)
                self.input_server=myOSCServer((self.this_unit_ip,int(self.listen_port)),self.input_reply_client)
                self.add_default_handler(self.input_server)
                self.add_input_handlers(self.input_server)
                print self.pretty_list(self.input_server.getOSCAddressSpace(),'\n')
                
            if self.osc_config.master_enabled =='yes':
                #we want to control other units
               
                #start the client that sends commands to the slaves
                self.output_client=OSC.OSCClient()
                self.mon.log(self, 'sending commands to slaves on port: '+self.reply_listen_port)

                #start the output reply server
                self.mon.log(self, 'listen to replies from slave units using: ' + self.this_unit_ip+':'+self.reply_listen_port)
                self.output_reply_server=myOSCServer((self.this_unit_ip,int(self.reply_listen_port)),self.output_client)
                self.add_default_handler(self.output_reply_server)
                self.add_output_reply_handlers(self.output_reply_server)
        
        return 'normal','osc.cfg read'


    def terminate(self):
        if self.input_server != None:
            self.input_server.close()
        if self.output_reply_server != None:
            self.output_reply_server.close()
        self.mon.log(self, 'Waiting for Server threads to finish')
        if self.input_st != None:
            self.input_st.join() ##!!!
        if self.output_reply_st != None:
            self.output_reply_st.join() ##!!!
        self.mon.log(self,'server threads closed')
        if self.input_reply_client !=None:
            self.input_reply_client.close()
        if self.output_client !=None:
            self.output_client.close()


    def start_server(self):
        # Start input Server
        self.mon.log(self,'Starting input OSCServer')
        if self.input_server != None:
            self.input_st = threading.Thread( target = self.input_server.serve_forever )
            self.input_st.start()

        # Start output_reply server
        self.mon.log(self,'Starting output reply OSCServer')
        if self.output_reply_server != None:
            self.output_reply_st = threading.Thread( target = self.output_reply_server.serve_forever )
            self.output_reply_st.start()

    def parse_slaves(self):
        name_list=self.osc_config.slave_units_name.split()
        ip_list=self.osc_config.slave_units_ip.split()
        if len(name_list)==0:
            return 'error','OSC Config - List of slaves name is empty'
        if len(name_list) != len(ip_list):
            return 'error','OSC Config - Lengths of list of slaves name and slaves IP is different'       
        self.slave_name_list=[]
        self.slave_ip_list=[]
        for i, name in enumerate(name_list):
            self.slave_name_list.append(name)
            self.slave_ip_list.append(ip_list[i])
        return 'normal','slaves parsed'


    def parse_osc_command(self,fields):
    # send message to slave unit - INTERFACE WITH pipresents
        if len(fields) <2:
               return 'error','too few fields in OSC command '+' '.join(fields)
        to_unit_name=fields[0]
        show_command=fields[1]
        # print 'FIELDS ',fields
        
        # send an arbitary osc message            
        if show_command == 'send':
            if len(fields)>2:
                osc_address= fields[2]
                arg_list=[]
                if len(fields)>3:
                    arg_list=fields[3:]
            else:
                return 'error','OSC - wrong nmber of fields in '+ ' '.join(fields)

        elif show_command in ('open','close','openexclusive'):
            if len(fields)==3:
                osc_address=self.prefix+'/'+ to_unit_name + '/core/'+ show_command
                arg_list= [fields[2]]
            else:
                return 'error','OSC - wrong number of fields in '+ ' '.join(fields)
                
        elif show_command =='monitor':
            if fields[2] in ('on','off'):
                osc_address=self.prefix+'/'+ to_unit_name + '/core/'+ show_command
                arg_list=[fields[2]]
            else:
                self.mon.err(self,'OSC - illegal state in '+ show_command + ' '+fields[2])
        
        elif show_command =='event':                
            if len(fields)==3:
                osc_address=self.prefix+'/'+ to_unit_name + '/core/'+ show_command
                arg_list= [fields[2]]


        elif show_command == 'animate':                
            if len(fields)>2:
                osc_address=self.prefix+'/'+ to_unit_name + '/core/'+ show_command
                arg_list= fields[2:]
            else:
                return 'error','OSC - wrong nmber of fields in '+ ' '.join(fields)
            
        elif show_command in ('closeall','exitpipresents','shutdownnow','reboot'):
            if len(fields)==2:
                osc_address=self.prefix+'/'+ to_unit_name + '/core/'+ show_command
                arg_list= []
            else:
                return 'error','OSC - wrong nmber of fields in '+ ' '.join(fields)

        elif show_command in ('loopback','server-info'):
            if len(fields)==2:
                osc_address=self.prefix+'/'+ to_unit_name + '/system/'+ show_command
                arg_list= []
            else:
                return 'error','OSC - wrong nmber of fields in '+ ' '.join(fields)
            
        else:
            return 'error','OSC - unkown command in '+ ' '.join(fields)

        
        ip=self.find_ip(to_unit_name,self.slave_name_list,self.slave_ip_list)
        if ip=='':
            return 'warn','OSC Unit Name not in the list of slaves: '+ to_unit_name
        self.sendto(ip,osc_address,arg_list)
        return 'normal','osc command sent'


    def find_ip(self,name,name_list,ip_list):
        i=0
        for j in name_list:
            if j == name:
                break
            i=i+1
            
        if i==len(name_list):
            return ''
        else:
            return ip_list[i]
                    

    def sendto(self,ip,osc_address,arg_list):
        # print ip,osc_address,arg_list
        if self.output_client is None:
            self.mon.warn(self,'Master not enabled, ignoring OSC command')
            return
        msg = OSC.OSCMessage()
        # print address
        msg.setAddress(osc_address)
        for arg in arg_list:
            # print arg
            msg.append(arg)
            
        try:
            self.output_client.sendto(msg,(ip,int(self.reply_listen_port)))
            self.mon.log(self,'Sent OSC command: '+osc_address+' '+' '.join(arg_list) + ' to '+ ip +':'+self.reply_listen_port)
        except Exception as e:
            self.mon.warn(self,'error in client when sending OSC command: '+ str(e))


# **************************************
# Handlers for fallback
# **************************************

    def add_default_handler(self,server):
        server.addMsgHandler('default', self.no_match_handler)

    def no_match_handler(self,addr, tags, stuff, source):
        text= "No handler for message from %s" % OSC.getUrlStr(source)+'\n'
        text+= "     %s" % addr+ self.pretty_list(stuff,'')
        self.mon.warn(self,text)
        return None

# **************************************
# Handlers for Slave (input)
# **************************************    

    def add_input_handlers(self,server):
        server.addMsgHandler(self.prefix + self.this_unit+"/system/server-info", self.server_info_handler)
        server.addMsgHandler(self.prefix + self.this_unit+"/system/loopback", self.loopback_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/open', self.open_show_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/close', self.close_show_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/openexclusive', self.openexclusive_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/closeall', self.closeall_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/exitpipresents', self.exitpipresents_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/shutdownnow', self.shutdownnow_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/reboot', self.reboot_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/event', self.input_event_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/animate', self.animate_handler)
        server.addMsgHandler(self.prefix+ self.this_unit+'/core/monitor', self.monitor_handler)


    # reply to master unit with name of this unit and commands
    def server_info_handler(self,addr, tags, stuff, source):

        msg = OSC.OSCMessage(self.prefix+'/system/server-info-reply')
        msg.append(self.this_unit_name)
        msg.append(self.input_server.getOSCAddressSpace())
        self.mon.log(self,'Sent Server Info reply to %s:' % OSC.getUrlStr(source))
        return msg


    # reply to master unit with a loopback message
    def loopback_handler(self,addr, tags, stuff, source):
        msg = OSC.OSCMessage(self.prefix+'/system/loopback-reply')
        self.mon.log(self,'Sent loopback reply to %s:' % OSC.getUrlStr(source))
        return msg


 
    def open_show_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('open ',args,1)

    def openexclusive_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('openexclusive ',args,1)
        
    def close_show_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('close ', args,1)

    def closeall_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('closeall',args,0)

    def monitor_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('monitor ', args,1)

    def exitpipresents_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('exitpipresents',args,0)

    def reboot_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('reboot',args,0)

    def shutdownnow_handler(self,address, tags, args, source):
        self.prepare_show_command_callback('shutdownnow',args,0)

    def prepare_show_command_callback(self,command,args,limit):
        if len(args) == limit:
            if limit !=0:
                self.mon.sched(self,TimeOfDay.now,'Received from OSC: '+ command + ' ' +args[0])
                self.show_command_callback(command+args[0])
            else:
                self.mon.sched(self,TimeOfDay.now,'Received from OSC: '+ command)
                self.show_command_callback(command)                
        else:
            self.mon.warn(self,'OSC show command does not have '+limit +' argument - ignoring')  

    def input_event_handler(self,address, tags, args, source):
        if len(args) == 1:
            self.input_event_callback(args[0],'OSC')
        else:
            self.mon.warn(self,'OSC input event does not have 1 argument - ignoring')    


    def animate_handler(self,address, tags, args, source):
        if len(args) !=0:
            # delay symbol,param_type,param_values,req_time as a string
            text='0 '
            for arg in args:
                text= text+ arg + ' '
            text = text + '0'
            print text
            self.animate_callback(text)
        else:
            self.mon.warn(self,'OSC output event has no arguments - ignoring')      

# **************************************
# Handlers for Master- replies from slaves (output)
# **************************************

    # reply handlers do not have the destinatuion unit in the address as they are always sent to the originator
    def add_output_reply_handlers(self,server):
        server.addMsgHandler(self.prefix+"/system/server-info-reply", self.server_info_reply_handler)
        server.addMsgHandler(self.prefix+"/system/loopback-reply", self.loopback_reply_handler)
        
        
    # print result of info request from slave unit
    def server_info_reply_handler(self,addr, tags, stuff, source):
        self.mon.log(self,'server info reply from slave '+OSC.getUrlStr(source)+ self.pretty_list(stuff,'\n'))
        print 'Received reply to Server-Info command from slave: ',OSC.getUrlStr(source), self.pretty_list(stuff,'\n')
        return None

    #print result of info request from slave unit
    def loopback_reply_handler(self,addr, tags, stuff, source):
        self.mon.log(self,'server info reply from slave '+OSC.getUrlStr(source)+ self.pretty_list(stuff,'\n'))
        print 'Received reply to Loopback command from slave: ' + OSC.getUrlStr(source)+ ' '+ self.pretty_list(stuff,'\n')
        return None


    def pretty_list(self,fields, separator):
        text=' '
        for field in fields:
            text += str(field) + separator
        return text+'\n'
Esempio n. 57
0
    def __init__(self, show_id, showlist, root, canvas, show_params,
                 track_params, pp_dir, pp_home, pp_profile, end_callback,
                 command_callback):

        # create debugging log object
        self.mon = Monitor()

        self.mon.trace(self, '')

        # instantiate arguments
        self.show_id = show_id
        self.showlist = showlist
        self.root = root
        self.canvas = canvas['canvas-obj']
        self.show_canvas_x1 = canvas['show-canvas-x1']
        self.show_canvas_y1 = canvas['show-canvas-y1']
        self.show_canvas_x2 = canvas['show-canvas-x2']
        self.show_canvas_y2 = canvas['show-canvas-y2']
        self.show_canvas_width = canvas['show-canvas-width']
        self.show_canvas_height = canvas['show-canvas-height']
        self.show_canvas_centre_x = canvas['show-canvas-centre-x']
        self.show_canvas_centre_y = canvas['show-canvas-centre-y']
        self.show_params = show_params
        self.track_params = track_params
        self.pp_dir = pp_dir
        self.pp_home = pp_home
        self.pp_profile = pp_profile
        self.end_callback = end_callback
        self.command_callback = command_callback

        # get background image from profile.
        self.background_file = ''
        if self.track_params['background-image'] != '':
            self.background_file = self.track_params['background-image']

        # get background colour from profile.
        if self.track_params['background-colour'] != '':
            self.background_colour = self.track_params['background-colour']
        else:
            self.background_colour = self.show_params['background-colour']

        # get animation instructions from profile
        self.animate_begin_text = self.track_params['animate-begin']
        self.animate_end_text = self.track_params['animate-end']

        # create an  instance of showmanager so we can control concurrent shows
        # self.show_manager=ShowManager(self.show_id,self.showlist,self.show_params,self.root,self.canvas,self.pp_dir,self.pp_profile,self.pp_home)

        # open the plugin Manager
        self.pim = PluginManager(self.show_id, self.root, self.canvas,
                                 self.show_params, self.track_params,
                                 self.pp_dir, self.pp_home, self.pp_profile)

        # create an instance of Animate so we can send animation commands
        self.animate = Animate()

        # initialise state and signals
        self.background_obj = None
        self.show_text_obj = None
        self.track_text_obj = None
        self.hint_obj = None
        self.background = None
        self.freeze_at_end_required = 'no'  # overriden by videoplayer
        self.tick_timer = None
        self.terminate_signal = False
        self.play_state = ''
class ShowManager(object):
    """
    ShowManager manages PiPresents' concurrent shows. It does not manage sub-shows or child-shows but has a bit of common code to initilise them
    concurrent shows are always top level (level 0) shows:
    They can be opened/closed  by the start show(open only) or by 'open/close myshow' in the Show Control field of players, by time of day sceduler or by OSC
    
   Two shows with the same show reference cannot be run concurrently as there is no way to reference an individual instance.
   However a workaround is to make the secong instance a subshow of a mediashow with a different reference.

    """

    # Declare class variables
    shows = []
    canvas = None  #canvas for all shows
    shutdown_required = False
    SHOW_TEMPLATE = ['', None]
    SHOW_REF = 0  # show-reference  - name of the show as in editor
    SHOW_OBJ = 1  # the python object
    showlist = []

    # Initialise class variables, first time through only in pipresents.py

    def init(self, canvas, all_shows_ended_callback, command_callback,
             showlist):
        ShowManager.all_shows_ended_callback = all_shows_ended_callback
        ShowManager.shows = []
        ShowManager.shutdown_required = False
        ShowManager.canvas = canvas
        ShowManager.command_callback = command_callback
        ShowManager.showlist = showlist

# **************************************
# functions to manipulate show register
# **************************************

    def register_shows(self):
        for show in ShowManager.showlist.shows():
            if show['show-ref'] != 'start':
                reason, message = self.register_show(show['show-ref'])
                if reason == 'error':
                    return reason, message
        return 'normal', 'shows regiistered'

    def register_show(self, ref):
        registered = self.show_registered(ref)
        if registered == -1:
            ShowManager.shows.append(copy.deepcopy(ShowManager.SHOW_TEMPLATE))
            index = len(ShowManager.shows) - 1
            ShowManager.shows[index][ShowManager.SHOW_REF] = ref
            ShowManager.shows[index][ShowManager.SHOW_OBJ] = None
            self.mon.trace(
                self, ' - register show: show_ref = ' + ref + ' index = ' +
                str(index))
            return 'normal', 'show registered'
        else:
            # self.mon.err(self, ' more than one show in showlist with show-ref: ' + ref )
            return 'error', ' more than one show in showlist with show-ref: ' + ref

    # is the show registered?
    # can be used to return the index to the show
    def show_registered(self, show_ref):
        index = 0
        for show in ShowManager.shows:
            if show[ShowManager.SHOW_REF] == show_ref:
                return index
            index += 1
        return -1

    # needs calling program to check that the show is not already running
    def set_running(self, index, show_obj):
        ShowManager.shows[index][ShowManager.SHOW_OBJ] = show_obj
        self.mon.trace(
            self,
            'show_ref= ' + ShowManager.shows[index][ShowManager.SHOW_REF] +
            ' show_id= ' + str(index))

    # is the show running?
    def show_running(self, index):
        if ShowManager.shows[index][ShowManager.SHOW_OBJ] is not None:
            return ShowManager.shows[index][ShowManager.SHOW_OBJ]
        else:
            return None

    def set_exited(self, index):
        ShowManager.shows[index][ShowManager.SHOW_OBJ] = None
        self.mon.trace(
            self,
            'show_ref= ' + ShowManager.shows[index][ShowManager.SHOW_REF] +
            ' show_id= ' + str(index))

    # are all shows exited?
    def all_shows_exited(self):
        all_exited = True
        for show in ShowManager.shows:
            if show[ShowManager.SHOW_OBJ] is not None:
                all_exited = False
        return all_exited

    # fromat for printing
    def pretty_shows(self):
        shows = '\n'
        for show in ShowManager.shows:
            shows += show[ShowManager.SHOW_REF] + '\n'
        return shows


# *********************************
# show control
# *********************************

# show manager can be initialised by a player, shower or by pipresents.py
# if by pipresents.py then show_id=-1

    def __init__(self, show_id, showlist, show_params, root, canvas, pp_dir,
                 pp_profile, pp_home):
        self.show_id = show_id
        self.showlist = showlist
        self.show_params = show_params
        self.root = root
        self.show_canvas = canvas
        self.pp_dir = pp_dir
        self.pp_profile = pp_profile
        self.pp_home = pp_home

        self.mon = Monitor()

    def control_a_show(self, show_ref, show_command):
        if show_command == 'open':
            return self.start_show(show_ref)
        elif show_command == 'close':
            return self.exit_show(show_ref)
        else:
            return 'error', 'command not recognised ' + show_command

    def exit_all_shows(self):
        for show in ShowManager.shows:
            self.exit_show(show[ShowManager.SHOW_REF])
        return 'normal', 'exited all shows'

    # kick off the exit sequence of a show by calling the shows exit method.
    # it will result in all the shows in a stack being closed and end_play_show being called
    def exit_show(self, show_ref):
        index = self.show_registered(show_ref)
        self.mon.log(self,
                     "Exiting show " + show_ref + ' show index:' + str(index))
        show_obj = self.show_running(index)
        if show_obj is not None:
            show_obj.exit()
        return 'normal', 'exited a concurrent show'

    def start_show(self, show_ref):
        index = self.show_registered(show_ref)
        if index < 0:
            return 'error', "Show not found in showlist: " + show_ref
        show_index = self.showlist.index_of_show(show_ref)
        show = self.showlist.show(show_index)
        reason, message, show_canvas = self.compute_show_canvas(show)
        if reason == 'error':
            return reason, message
        # print 'STARTING TOP LEVEL SHOW',show_canvas
        self.mon.sched(
            self, 'Starting Show: ' + show_ref + ' from show: ' +
            self.show_params['show-ref'])
        self.mon.log(
            self, 'Starting Show: ' + show_ref + ' from: ' +
            self.show_params['show-ref'])
        if self.show_running(index):
            self.mon.sched(
                self, "show already running so ignoring command: " + show_ref)
            self.mon.warn(
                self, "show already running so ignoring command: " + show_ref)
            return 'normal', 'this concurrent show already running'
        show_obj = self.init_show(index, show, show_canvas)
        if show_obj is None:
            return 'error', "unknown show type in start concurrent show - " + show[
                'type']
        else:
            self.set_running(index, show_obj)
            # params - end_callback, show_ready_callback, parent_kickback_signal, level
            show_obj.play(self._end_play_show, None, False, 0, [])
            return 'normal', 'concurrent show started'

    # used by shows to create subshows or child shows
    def init_subshow(self, show_id, show, show_canvas):
        return self.init_show(show_id, show, show_canvas)

    def _end_play_show(self, index, reason, message):
        show_ref_to_exit = ShowManager.shows[index][ShowManager.SHOW_REF]
        show_to_exit = ShowManager.shows[index][ShowManager.SHOW_OBJ]
        self.mon.sched(self, 'Closed show: ' + show_ref_to_exit)
        self.mon.log(
            self, 'Exited from show: ' + show_ref_to_exit + ' ' + str(index))
        self.mon.log(self, 'Exited with Reason = ' + reason)
        self.mon.trace(
            self,
            ' Show is: ' + show_ref_to_exit + ' show index ' + str(index))
        # closes the video/audio from last track then closes the track
        # print 'show to exit ',show_to_exit, show_to_exit.current_player,show_to_exit.previous_player
        self.set_exited(index)
        if self.all_shows_exited() is True:
            ShowManager.all_shows_ended_callback(reason, message)
        return reason, message

    # common function to initilaise the show by type
    def init_show(
        self,
        show_id,
        selected_show,
        show_canvas,
    ):
        if selected_show['type'] == "mediashow":
            return MediaShow(show_id, selected_show, self.root, show_canvas,
                             self.showlist, self.pp_dir, self.pp_home,
                             self.pp_profile, ShowManager.command_callback)

        elif selected_show['type'] == "liveshow":
            return LiveShow(show_id, selected_show, self.root, show_canvas,
                            self.showlist, self.pp_dir, self.pp_home,
                            self.pp_profile, ShowManager.command_callback)

        elif selected_show['type'] == "radiobuttonshow":
            return RadioButtonShow(show_id, selected_show, self.root,
                                   show_canvas, self.showlist, self.pp_dir,
                                   self.pp_home, self.pp_profile,
                                   ShowManager.command_callback)

        elif selected_show['type'] == "hyperlinkshow":
            return HyperlinkShow(show_id, selected_show, self.root,
                                 show_canvas, self.showlist, self.pp_dir,
                                 self.pp_home, self.pp_profile,
                                 ShowManager.command_callback)

        elif selected_show['type'] == "menu":
            return MenuShow(show_id, selected_show, self.root, show_canvas,
                            self.showlist, self.pp_dir, self.pp_home,
                            self.pp_profile, ShowManager.command_callback)

        elif selected_show['type'] == "artmediashow":
            return ArtMediaShow(show_id, selected_show, self.root, show_canvas,
                                self.showlist, self.pp_dir, self.pp_home,
                                self.pp_profile, ShowManager.command_callback)

        elif selected_show['type'] == "artliveshow":
            return ArtLiveShow(show_id, selected_show, self.root, show_canvas,
                               self.showlist, self.pp_dir, self.pp_home,
                               self.pp_profile, ShowManager.command_callback)
        else:
            return None

    def compute_show_canvas(self, show_params):
        canvas = {}
        canvas['canvas-obj'] = ShowManager.canvas
        status, message, self.show_canvas_x1, self.show_canvas_y1, self.show_canvas_x2, self.show_canvas_y2 = self.parse_show_canvas(
            show_params['show-canvas'])
        if status == 'error':
            # self.mon.err(self,'show canvas error: ' + message + ' in ' + show_params['show-canvas'])
            return 'error', 'show canvas error: ' + message + ' in ' + show_params[
                'show-canvas'], canvas
        else:
            self.show_canvas_width = self.show_canvas_x2 - self.show_canvas_x1
            self.show_canvas_height = self.show_canvas_y2 - self.show_canvas_y1
            self.show_canvas_centre_x = self.show_canvas_width / 2
            self.show_canvas_centre_y = self.show_canvas_height / 2
            canvas['show-canvas-x1'] = self.show_canvas_x1
            canvas['show-canvas-y1'] = self.show_canvas_y1
            canvas['show-canvas-x2'] = self.show_canvas_x2
            canvas['show-canvas-y2'] = self.show_canvas_y2
            canvas['show-canvas-width'] = self.show_canvas_width
            canvas['show-canvas-height'] = self.show_canvas_height
            canvas['show-canvas-centre-x'] = self.show_canvas_centre_x
            canvas['show-canvas-centre-y'] = self.show_canvas_centre_y
            return 'normal', '', canvas

    def parse_show_canvas(self, text):
        fields = text.split()
        # blank so show canvas is the whole screen
        if len(fields) < 1:
            return 'normal', '', 0, 0, int(self.canvas['width']), int(
                self.canvas['height'])

        elif len(fields) == 4:
            # window is specified
            if not (fields[0].isdigit() and fields[1].isdigit()
                    and fields[2].isdigit() and fields[3].isdigit()):
                return 'error', 'coordinates are not positive integers', 0, 0, 0, 0
            return 'normal', '', int(fields[0]), int(fields[1]), int(
                fields[2]), int(fields[3])
        else:
            # error
            return 'error', 'illegal Show canvas dimensions ' + text, 0, 0, 0, 0
Esempio n. 59
0
    def __init__(self):
    
        self.editor_issue="1.3"

        # get command options
        self.command_options=ed_options()

        # get directory holding the code
        self.pp_dir=sys.path[0]
            
        if not os.path.exists(self.pp_dir+os.sep+"pp_editor.py"):
            tkMessageBox.showwarning("Pi Presents","Bad Application Directory")
            exit()
            
          
        # Initialise logging
        Monitor.log_path=self.pp_dir
        self.mon=Monitor()
        self.mon.init()
        
        Monitor.classes  = ['PPEditor','EditItem','Validator']

        Monitor.log_level = int(self.command_options['debug'])

        self.mon.log (self, "Pi Presents Editor is starting")
        self.mon.log (self," OS and separator " + os.name +'  ' + os.sep)
        self.mon.log(self,"sys.path[0] -  location of code: code "+sys.path[0])


        # set up the gui
 
        # root is the Tkinter root widget
        self.root = Tk()
        self.root.title("Editor for Pi Presents")

        # self.root.configure(background='grey')

        self.root.resizable(False,False)

        # define response to main window closing
        self.root.protocol ("WM_DELETE_WINDOW", self.app_exit)

        # bind some display fields
        self.filename = StringVar()
        self.display_selected_track_title = StringVar()
        self.display_show = StringVar()


        # define menu
        menubar = Menu(self.root)

        profilemenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        profilemenu.add_command(label='Open', command = self.open_existing_profile)
        profilemenu.add_command(label='Validate', command = self.validate_profile)
        menubar.add_cascade(label='Profile', menu = profilemenu)

        ptypemenu = Menu(profilemenu, tearoff=0, bg="grey", fg="black")
        ptypemenu.add_command(label='Exhibit', command = self.new_exhibit_profile)
        ptypemenu.add_command(label='Media Show', command = self.new_mediashow_profile)
        ptypemenu.add_command(label='Art Media Show', command = self.new_artmediashow_profile)
        ptypemenu.add_command(label='Menu', command = self.new_menu_profile)
        ptypemenu.add_command(label='Presentation', command = self.new_presentation_profile)
        ptypemenu.add_command(label='Interactive', command = self.new_interactive_profile)
        ptypemenu.add_command(label='Live Show', command = self.new_liveshow_profile)
        ptypemenu.add_command(label='Art Live Show', command = self.new_artliveshow_profile)
        ptypemenu.add_command(label='RadioButton Show', command = self.new_radiobuttonshow_profile)
        ptypemenu.add_command(label='Hyperlink Show', command = self.new_hyperlinkshow_profile)
        ptypemenu.add_command(label='Blank', command = self.new_blank_profile)
        profilemenu.add_cascade(label='New from Template', menu = ptypemenu)
        
        showmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        showmenu.add_command(label='Delete', command = self.remove_show)
        showmenu.add_command(label='Edit', command = self.m_edit_show)
        showmenu.add_command(label='Copy To', command = self.copy_show)
        menubar.add_cascade(label='Show', menu = showmenu)

        stypemenu = Menu(showmenu, tearoff=0, bg="grey", fg="black")
        stypemenu.add_command(label='Menu', command = self.add_menushow)
        stypemenu.add_command(label='MediaShow', command = self.add_mediashow)
        stypemenu.add_command(label='LiveShow', command = self.add_liveshow)
        stypemenu.add_command(label='HyperlinkShow', command = self.add_hyperlinkshow)
        stypemenu.add_command(label='RadioButtonShow', command = self.add_radiobuttonshow)
        stypemenu.add_command(label='ArtMediaShow', command = self.add_artmediashow)
        stypemenu.add_command(label='ArtLiveShow', command = self.add_artliveshow)
        showmenu.add_cascade(label='Add', menu = stypemenu)
        
        medialistmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='MediaList', menu = medialistmenu)
        medialistmenu.add_command(label='Add', command = self.add_medialist)
        medialistmenu.add_command(label='Delete', command = self.remove_medialist)
        medialistmenu.add_command(label='Copy To', command = self.copy_medialist)
      
        trackmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        trackmenu.add_command(label='Delete', command = self.remove_track)
        trackmenu.add_command(label='Edit', command = self.m_edit_track)
        trackmenu.add_command(label='Add from Dir', command = self.add_tracks_from_dir)
        trackmenu.add_command(label='Add from File', command = self.add_track_from_file)


        menubar.add_cascade(label='Track', menu = trackmenu)

        typemenu = Menu(trackmenu, tearoff=0, bg="grey", fg="black")
        typemenu.add_command(label='Video', command = self.new_video_track)
        typemenu.add_command(label='Audio', command = self.new_audio_track)
        typemenu.add_command(label='Image', command = self.new_image_track)
        typemenu.add_command(label='Web', command = self.new_web_track)
        typemenu.add_command(label='Message', command = self.new_message_track)
        typemenu.add_command(label='Show', command = self.new_show_track)
        typemenu.add_command(label='Menu Track', command = self.new_menu_track)
        trackmenu.add_cascade(label='New', menu = typemenu)

        oscmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='OSC', menu = oscmenu)
        oscmenu.add_command(label='Create OSC configuration', command = self.create_osc)
        oscmenu.add_command(label='Edit OSC Configuration', command = self.edit_osc)
        oscmenu.add_command(label='Delete OSC Configuration', command = self.delete_osc)


        toolsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Tools', menu = toolsmenu)
        toolsmenu.add_command(label='Update All', command = self.update_all)
        
        optionsmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Options', menu = optionsmenu)
        optionsmenu.add_command(label='Edit', command = self.edit_options)

        helpmenu = Menu(menubar, tearoff=0, bg="grey", fg="black")
        menubar.add_cascade(label='Help', menu = helpmenu)
        helpmenu.add_command(label='Help', command = self.show_help)
        helpmenu.add_command(label='About', command = self.about)
         
        self.root.config(menu=menubar)

        top_frame=Frame(self.root)
        top_frame.pack(side=TOP)
        bottom_frame=Frame(self.root)
        bottom_frame.pack(side=TOP, fill=BOTH, expand=1)        

        left_frame=Frame(bottom_frame, padx=5)
        left_frame.pack(side=LEFT)
        middle_frame=Frame(bottom_frame,padx=5)
        middle_frame.pack(side=LEFT)              
        right_frame=Frame(bottom_frame,padx=5,pady=10)
        right_frame.pack(side=LEFT)
        updown_frame=Frame(bottom_frame,padx=5)
        updown_frame.pack(side=LEFT)
        
        tracks_title_frame=Frame(right_frame)
        tracks_title_frame.pack(side=TOP)
        tracks_label = Label(tracks_title_frame, text="Tracks in Selected Medialist")
        tracks_label.pack()
        tracks_frame=Frame(right_frame)
        tracks_frame.pack(side=TOP)
        shows_title_frame=Frame(left_frame)
        shows_title_frame.pack(side=TOP)
        shows_label = Label(shows_title_frame, text="Shows")
        shows_label.pack()
        shows_frame=Frame(left_frame)
        shows_frame.pack(side=TOP)
        shows_title_frame=Frame(left_frame)
        shows_title_frame.pack(side=TOP)
        medialists_title_frame=Frame(left_frame)
        medialists_title_frame.pack(side=TOP)
        medialists_label = Label(medialists_title_frame, text="Medialists")
        medialists_label.pack()
        medialists_frame=Frame(left_frame)
        medialists_frame.pack(side=LEFT)
        
        # define buttons 

        add_button = Button(middle_frame, width = 5, height = 2, text='Edit\nShow',
                            fg='black', command = self.m_edit_show, bg="light grey")
        add_button.pack(side=RIGHT)
        
        add_button = Button(updown_frame, width = 5, height = 1, text='Add',
                            fg='black', command = self.add_track_from_file, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Edit',
                            fg='black', command = self.m_edit_track, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Up',
                            fg='black', command = self.move_track_up, bg="light grey")
        add_button.pack(side=TOP)
        add_button = Button(updown_frame, width = 5, height = 1, text='Down',
                            fg='black', command = self.move_track_down, bg="light grey")
        add_button.pack(side=TOP)


        # define display of showlist 
        scrollbar = Scrollbar(shows_frame, orient=VERTICAL)
        self.shows_display = Listbox(shows_frame, selectmode=SINGLE, height=12,
                                     width = 40, bg="white",activestyle=NONE,
                                     fg="black", yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.shows_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.shows_display.pack(side=LEFT, fill=BOTH, expand=1)
        self.shows_display.bind("<ButtonRelease-1>", self.e_select_show)

    
        # define display of medialists
        scrollbar = Scrollbar(medialists_frame, orient=VERTICAL)
        self.medialists_display = Listbox(medialists_frame, selectmode=SINGLE, height=12,
                                          width = 40, bg="white",activestyle=NONE,
                                          fg="black",yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.medialists_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.medialists_display.pack(side=LEFT,  fill=BOTH, expand=1)
        self.medialists_display.bind("<ButtonRelease-1>", self.select_medialist)


        # define display of tracks
        scrollbar = Scrollbar(tracks_frame, orient=VERTICAL)
        self.tracks_display = Listbox(tracks_frame, selectmode=SINGLE, height=25,
                                      width = 40, bg="white",activestyle=NONE,
                                      fg="black",yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.tracks_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.tracks_display.pack(side=LEFT,fill=BOTH, expand=1)
        self.tracks_display.bind("<ButtonRelease-1>", self.e_select_track)


        # initialise editor options class and OSC config class
        self.options=Options(self.pp_dir) # creates options file in code directory if necessary
        self.osc_config=OSCConfig()
        
        # initialise variables      
        self.init()
        
        # and enter Tkinter event loop
        self.root.mainloop()        
class OMXDriver(object):

    _LAUNCH_CMD = '/usr/bin/omxplayer --no-keys '  # needs changing if user has installed his own version of omxplayer elsewhere

    # add more keys here, see popcornmix/omxplayer github files readme.md and  KeyConfig.h
    KEY_MAP =   {'<':3,'>':4,'z':5,'j':6,'k':7,'i':8,'o':9,'n':10,'m':11,'s':12,
                 'x':30,'w':31}


    def __init__(self,widget,pp_dir):


        self.widget=widget
        self.pp_dir=pp_dir
        
        self.mon=Monitor()

        self.start_play_signal=False
        self.end_play_signal=False
        self.end_play_reason='nothing'
        self.duration=0
        self.video_position=0
        
        self.pause_at_end_required=False
        self.paused_at_end=False
        self.pause_at_end_time=0
        
        # self.pause_before_play_required='before-first-frame'  #no,before-first-frame, after-first-frame
        # self.pause_before_play_required='no'
        self.paused_at_start='False'

        self.paused=False      

        self.terminate_reason=''

        #  dbus and subprocess
        self._process=None
        self.__iface_root=None
        self.__iface_props = None
        self.__iface_player = None


    def load(self, track, freeze_at_start,options,caller,omx_volume,omx_max_volume):
        self.omx_volume=omx_volume
        self.omx_max_volume=omx_max_volume
        self.pause_before_play_required=freeze_at_start
        self.caller=caller
        track= "'"+ track.replace("'","'\\''") + "'"
        # self.mon.log(self,'TIME OF DAY: '+ strftime("%Y-%m-%d %H:%M"))
        self.dbus_user = os.environ["USER"]

        self.id=str(int(time()*1000000))

        self.dbus_name = "org.mpris.MediaPlayer2.omxplayer"+self.id
        # print ('DBUS NAME',self.dbus_name)
        self.omxplayer_cmd = OMXDriver._LAUNCH_CMD + options + " --dbus_name '"+ self.dbus_name + "' " + track
        # self.mon.log(self, 'dbus user ' + self.dbus_user)
        # self.mon.log(self, 'dbus name ' + self.dbus_name)

        # print self.omxplayer_cmd
        self.mon.log(self, "Send command to omxplayer: "+ self.omxplayer_cmd)
        # self._process=subprocess.Popen(self.omxplayer_cmd,shell=True,stdout=file('/home/pi/pipresents/pp_logs/stdout.txt','a'),stderr=file('/home/pi/pipresents/pp_logs/stderr.txt','a'))
        self._process=subprocess.Popen(self.omxplayer_cmd,shell=True,stdout=open('/dev/null','a'),stderr=open('/dev/null','a'))
        self.pid=self._process.pid

        # wait for omxplayer to start then start monitoring thread
        self.dbus_tries = 0
        self.omx_loaded = False
        self._wait_for_dbus()
        return
    
    def _wait_for_dbus(self):
        connect_success=self.__dbus_connect()
        if connect_success is True:
            # print 'SUCCESS'
            self.mon.log(self,'connected to omxplayer dbus after ' + str(self.dbus_tries) + ' centisecs')
                
            # get duration of the track in microsecs if fails return a very large duration
            # posibly faile because omxplayer is running but not omxplayer.bin
            duration_success,duration=self.get_duration()
            if duration_success is False:
                self.mon.warn(self,'get duration failed for n attempts using '+ str(duration/60000000)+ ' minutes')
            # calculate time to pause before last frame
            self.duration = duration
            self.pause_at_end_time = duration - 350000
            # start the thread that is going to monitor output from omxplayer.
            self._monitor_status()
        else:
            self.dbus_tries+=1
            self.widget.after(100,self._wait_for_dbus)

    

    def _monitor_status(self):
        # print '\n',self.id, '** STARTING ',self.duration
        self.start_play_signal=False
        self.end_play_signal=False
        self.end_play_reason='nothing'
        self.paused_at_end=False
        self.paused_at_start='False'
        self.delay = 5
        self.widget.after(0,self._status_loop)



    """
    freeze at start
    'no' - unpause in show - test !=0
    'before_first_frame' - don't unpause in show, test >-xx just large enough negative to stop first frame showing
    'after_first_frame' - don't unpause in show, test > -yy large enough so that first frame always shows
    """
    after_first_frame_position = -50000 #microseconds
    before_first_frame_position = -80000 #microseconds
    
    def _status_loop(self):
            if self.is_running() is False:
                # process is not running because quit or natural end - seems not to happen
                self.end_play_signal=True
                self.end_play_reason='nice_day'
                # print ' send nice day - process not running'
                return
            else:
                success, video_position = self.get_position()
                # print ('read',success,video_position)
                if success is False:
                    # print 'send nice day - exception when reading video position'
                    self.end_play_signal=True
                    self.end_play_reason='nice_day'
                    return
                else:
                    self.video_position=video_position
                    # if timestamp is near the end then pause
                    if self.pause_at_end_required is True and self.video_position>self.pause_at_end_time:    #microseconds
                        # print 'pausing at end, leeway ',self.duration - self.video_position
                        pause_end_success = self.pause(' at end of track')
                        if pause_end_success is True:
                            # print self.id,' pause for end success', self.video_position
                            self.paused_at_end=True
                            self.end_play_signal=True
                            self.end_play_reason='pause_at_end'
                            return
                        else:
                            print('pause at end failed, probably because of delay after detection, just run on')
                            self.widget.after(self.delay,self._status_loop)
                    else:
                        # need to do the pausing for preload after first timestamp is received 0 is default value before start
                        # print self.pause_before_play_required,self.paused_at_start,self.video_position,OMXDriver.after_first_frame_position
                        if (self.pause_before_play_required == 'after-first-frame' and self.paused_at_start == 'False'\
                         and self.video_position >OMXDriver.after_first_frame_position\
                          and self.video_position !=0)\
                        or(self.pause_before_play_required != 'after-first-frame' and self.paused_at_start == 'False'\
                         and self.video_position > OMXDriver.before_first_frame_position\
                         and self.video_position !=0):
                            pause_after_load_success=self.pause('after load')
                            if pause_after_load_success is True:
                                self.start_play_signal = True
                                self.paused_at_start='True'
                            else:
                                # should never fail, just warn at the moment
                                # print 'pause after load failed ' + str(self.video_position)
                                self.mon.warn(self, str(self.id)+ ' pause after load fail ' + str(self.video_position))                                   
                            self.widget.after(self.delay,self._status_loop)
                        else:
                            self.widget.after(self.delay,self._status_loop)


    
    def show(self,freeze_at_end_required):
        self.pause_at_end_required=freeze_at_end_required
        # unpause to start playing
        if self.pause_before_play_required =='no':
            unpause_show_success=self.unpause(' to start showing')
            # print 'unpause for show',self.paused
            if unpause_show_success is True:
                pass
                # print self.id,' unpause for show success', self.video_position
            else:
                # should never fail, just warn at the moment
                self.mon.warn(self, str(self.id)+ ' unpause for show fail ' + str(self.video_position))                                   

        
    def control(self,char):

        val = OMXDriver.KEY_MAP[char]
        self.mon.log(self,'>control received and sent to omxplayer ' + str(self.pid) + ' ' + str(val))
        if self.is_running():
            try:
                self.__iface_player.Action(dbus.Int32(val))
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to send control - dbus exception: {}'.format(ex.get_dbus_message()))
                return
        else:
            self.mon.warn(self,'Failed to send control - process not running')
            return

        
    # USE ONLY at end and after load
    # return succces of the operation, several tries if pause did not work and no error reported.
    def pause(self,reason):
        self.mon.log(self,'pause received '+reason)
        if self.paused is False:
            self.mon.log(self,'not paused so send pause '+reason)
            tries=1
            while True:
                if self.send_pause() is False:
                    # failed for good reason
                    return False
                status=self.omxplayer_is_paused() # test omxplayer after sending the command
                if status == 'Paused':
                    self.paused = True
                    return True
                if status == 'Failed':
                    # failed for good reason because of exception or process not running caused by end of track
                    return False
                else:
                    # failed for no good reason
                    self.mon.warn(self, '!!!!! repeat pause ' + str(tries))
                    # print self.id,' !!!!! repeat pause ',self.video_position, tries
                    tries +=1
                    if tries >5:
                        # print self.id, ' pause failed for n attempts'
                        self.mon.warn(self,'pause failed for n attempts')
                        return False
            # repeat

            
    # USE ONLY for show

    def unpause(self,reason):
        self.mon.log(self,'Unpause received '+ reason)
        if self.paused is True:
            self.mon.log(self,'Is paused so Track will be unpaused '+ reason)
            tries=1
            while True:
                if self.send_unpause() is False:
                    return False
                status = self.omxplayer_is_paused() # test omxplayer
                if status == 'Playing':
                    self.paused = False
                    self.paused_at_start='done'
                    self.set_volume()
                    return True

                if status == 'Failed':
                    # failed for good reason because of exception or process not running caused by end of track
                    return False
                else:
                    # self.mon.warn(self, '!!!!! repeat unpause ' + str(tries))
                    # print self.id,' !!!! repeat unpause ',self.video_position, tries
                    tries +=1
                    if tries >200:
                        # print self.id, ' unpause failed for n attempts'                       
                        self.mon.warn(self,'unpause failed for 200 attempts')
                        return False
                    

    def omxplayer_is_paused(self):
        if self.is_running():
            try:
                result=self.__iface_props.PlaybackStatus()
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to test paused - dbus exception: {}'.format(ex.get_dbus_message()))
                return 'Failed'
            return result
        else:
            self.mon.warn(self,'Failed to test paused - process not running')
            # print self.id,' test paused not successful - process'
            return 'Failed'

        
    def send_pause(self):
        if self.is_running():
            try:
                self.__iface_player.Pause()
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to send pause - dbus exception: {}'.format(ex.get_dbus_message()))
                return False
            return True
        else:
            self.mon.warn(self,'Failed to send pause - process not running')
            # print self.id,' send pause not successful - process'
            return False


    def send_unpause(self):
        # print 'unpause'
        if self.is_running():
            try:
                self.__iface_player.Action(16)
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to send unpause - dbus exception: {}'.format(ex.get_dbus_message()))
                return False
            return True
        else:
            self.mon.warn(self,'Failed to send unpause - process not running')
            # print self.id,' send unpause not successful - process'
            return False

    def pause_on(self):
        self.mon.log(self,'pause on received ')
        # print 'pause on',self.paused
        if self.paused is True:
            return
        if self.is_running():
            try:
                # self.__iface_player.Action(16)                
                self.__iface_player.Pause()  # - this should work but does not!!!
                self.paused=True
                # print 'paused OK'
                return
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to do pause on - dbus exception: {}'.format(ex.get_dbus_message()))
                return
        else:
            self.mon.warn(self,'Failed to do pause on - process not running')
            return
                    

    def pause_off(self):
        self.mon.log(self,'pause off received ')
        # print 'pause off',self.paused
        if self.paused is False:
            return
        if self.is_running():
            try:
                self.__iface_player.Action(16)
                self.paused=False
                # print 'not paused OK'
                return
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to do pause off - dbus exception: {}'.format(ex.get_dbus_message()))
                return
        else:
            self.mon.warn(self,'Failed to do pause off - process not running')
            return

    def toggle_pause(self,reason):
        self.mon.log(self,'toggle pause received '+ reason)
        # print 'toggle pause'
        if self.is_running():
            try:
                self.__iface_player.Action(16)
                if not self.paused:
                    self.paused = True
                else:
                    self.paused=False
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to toggle pause - dbus exception: {}'.format(ex.get_dbus_message()))
                return
        else:
            self.mon.warn(self,'Failed to toggle pause - process not running')
            return
        

    def go(self):
        self.mon.log(self,'go received ')
        self.unpause('for go')


    def mute(self):
            self.__iface_player.Mute()
            
    def unmute(self):
            self.__iface_player.Unmute()

    def set_volume(self):
        millibels=self.omx_volume*100
        out = pow(10, millibels / 2000.0)
        self.__iface_props.Volume(out)
    
    def inc_volume(self):
        self.omx_volume+=3
        self.omx_volume=min(self.omx_volume,self.omx_max_volume)
        self.set_volume()

    def dec_volume(self):
        self.omx_volume-=3
        self.set_volume() 

    def stop(self):
        self.mon.log(self,'>stop received and quit sent to omxplayer ' + str(self.pid))
        # need to send 'nice day'
        if self.paused_at_end is True:
            self.end_play_signal=True
            self.end_play_reason='nice_day'
            # print 'send nice day for close track'
        if self.is_running():
            try:
                self.__iface_root.Quit()
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed to quit - dbus exception: {}'.format(ex.get_dbus_message()))
                return
        else:
            self.mon.warn(self,'Failed to quit - process not running')
            return


    # kill the subprocess (omxplayer and omxplayer.bin). Used for tidy up on exit.
    def terminate(self,reason):
        self.terminate_reason=reason
        self.stop()
        
    def get_terminate_reason(self):
        return self.terminate_reason
    

   # test of whether _process is running
    def is_running(self):
        retcode=self._process.poll()
        # print 'is alive', retcode
        if retcode is None:
            return True
        else:
            return False



    # kill off omxplayer when it hasn't terminated at the end of a track.
    # send SIGINT (CTRL C) so it has a chance to tidy up daemons and omxplayer.bin
    def kill(self):
        if self.is_running()is True:
            self._process.send_signal(signal.SIGINT)


    def get_position(self):
        # don't test process as is done just before
        try:
            micros = self.__iface_props.Position()
            # print ('micros',micros)
            return True,micros
        except dbus.exceptions.DBusException as ex:
            # print 'Failed get_position - dbus exception: {}'.format(ex.get_dbus_message())
            return False,-1               


    def get_duration(self):
        tries=1
        while True:
            success,duration=self._try_duration()
            if success is True:
                return True,duration
            else:
                self.mon.warn(self, 'repeat get duration ' + str(tries))
                tries +=1
                if tries >5:                      
                    return False,sys.maxsize*100


    def _try_duration(self):
        """Return the total length of the playing media"""
        if self.is_running() is True:
            try:
                micros = self.__iface_props.Duration()
                return True,micros
            except dbus.exceptions.DBusException as ex:
                self.mon.warn(self,'Failed get duration - dbus exception: {}'.format(ex.get_dbus_message()))
                return False,-1
        else:
            return False,-1




    # *********************
    # connect to dbus
    # *********************
    def __dbus_connect(self):
        if self.omx_loaded is False:
            # read the omxplayer dbus data from files generated by omxplayer
            bus_address_filename = "/tmp/omxplayerdbus.{}".format(self.dbus_user)
            bus_pid_filename = "/tmp/omxplayerdbus.{}.pid".format(self.dbus_user)

            if not os.path.exists(bus_address_filename):
                self.mon.log(self, 'waiting for bus address file ' + bus_address_filename)
                self.omx_loaded=False
                return False
            else:
                f = open(bus_address_filename, "r")
                bus_address = f.read().rstrip()
                if bus_address == '':
                    self.mon.log(self, 'waiting for bus address in file ' + bus_address_filename)
                    self.omx_loaded=False
                    return False
                else:
                    # self.mon.log(self, 'bus address found ' + bus_address)
                    if not os.path.exists(bus_pid_filename):
                        self.mon.warn(self, 'bus pid file does not exist ' + bus_pid_filename)
                        self.omx_loaded=False
                        return False
                    else:
                        f= open(bus_pid_filename, "r")
                        bus_pid = f.read().rstrip()
                        if bus_pid == '':
                            self.omx_loaded=False
                            return False
                        else:
                            # self.mon.log(self, 'bus pid found ' + bus_pid)
                            os.environ["DBUS_SESSION_BUS_ADDRESS"] = bus_address
                            os.environ["DBUS_SESSION_BUS_PID"] = bus_pid
                            self.omx_loaded = True
       
        if self.omx_loaded is True:
            session_bus = dbus.SessionBus()
            try:
                omx_object = session_bus.get_object(self.dbus_name, "/org/mpris/MediaPlayer2", introspect=False)
                self.__iface_root = dbus.Interface(omx_object, "org.mpris.MediaPlayer2")
                self.__iface_props = dbus.Interface(omx_object, "org.freedesktop.DBus.Properties")
                self.__iface_player = dbus.Interface(omx_object, "org.mpris.MediaPlayer2.Player")
            except dbus.exceptions.DBusException as ex:
                # self.mon.log(self,"Waiting for dbus connection to omxplayer: {}".format(ex.get_dbus_message()))
                return False
        return True