Example #1
0
class PS3SixaxisThread(StoppableThread):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Sixaxis",
                               icon_file=ICON_PATH + "/bluetooth.png",
                               ip=ipaddr)
        self.set_timeout(600)

    def run(self):
        six = sixaxis.sixaxis(self.xbmc, self.csock, self.isock)
        self.xbmc.connect()
        self.reset_timeout()
        try:
            while not self.stop():

                if self.timed_out():
                    raise Exception("PS3 Sixaxis powering off, timed out")
                if self.idle_time() > 50:
                    self.xbmc.connect()
                try:
                    if six.process_socket(self.isock):
                        self.reset_timeout()
                except Exception, e:
                    print e
                    break

        except Exception, e:
            printerr()
        six.close()
        self.close_sockets()
Example #2
0
class PS3SixaxisThread ( StoppableThread ):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Sixaxis", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
        self.set_timeout(600)

    def run(self):
        six = sixaxis.sixaxis(self.xbmc, self.csock, self.isock)
        self.xbmc.connect()
        self.reset_timeout()
        try:
            while not self.stop():

                if self.timed_out():
                    raise Exception("PS3 Sixaxis powering off, timed out")
                if self.idle_time() > 50:
                    self.xbmc.connect()
                try:
                    if six.process_socket(self.isock):
                        self.reset_timeout()
                except Exception, e:
                    print e
                    break

        except Exception, e:
            printerr()
        six.close()
        self.close_sockets()
Example #3
0
 def __init__(self, csock, isock, ipaddr="127.0.0.1"):
     StoppableThread.__init__(self)
     self.csock = csock
     self.isock = isock
     self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
     self.set_timeout(600)
     self.services = []
     self.current_xbmc = 0
Example #4
0
 def __init__(self, csock, isock, ipaddr="127.0.0.1"):
     StoppableThread.__init__(self)
     self.csock = csock
     self.isock = isock
     self.xbmc = XBMCClient(name="PS3 Sixaxis",
                            icon_file=ICON_PATH + "/bluetooth.png",
                            ip=ipaddr)
     self.set_timeout(600)
Example #5
0
 def __init__(self, ip, port):
     self.ip = ip
     self.port = port
     self.artistdict = {}
     self.albumdict = {}
     self.genredict = {}
     self.eventclient = XBMCClient('xbmcPD')
     self.eventclient.connect(ip, 9777)
Example #6
0
 def __init__(self, csock, isock, ipaddr="127.0.0.1"):
     StoppableThread.__init__(self)
     self.csock = csock
     self.isock = isock
     self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
     self.set_timeout(600)
     self.services = []
     self.current_xbmc = 0
Example #7
0
class PS3RemoteThread(StoppableThread):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote",
                               icon_file=ICON_PATH + "/bluetooth.png",
                               ip=ipaddr)
        self.set_timeout(600)
        self.services = []
        self.current_xbmc = 0

    def run(self):
        sixaxis.initialize(self.csock, self.isock)
        self.xbmc.connect()
        try:
            # start the zeroconf thread if possible
            try:
                self.zeroconf_thread = ZeroconfThread()
                self.zeroconf_thread.add_service('_xbmc-events._udp',
                                                 self.zeroconf_service_handler)
                self.zeroconf_thread.start()
            except Exception, e:
                print str(e)

            # main thread loop
            while not self.stop():
                status = process_remote(self.isock, self.xbmc)

                if status == 2:  # 2 = socket read timeout
                    if self.timed_out():
                        raise Exception("PS3 Blu-Ray Remote powering off, "\
                                            "timed out")
                elif status == 3:  # 3 = ps and skip +
                    self.next_xbmc()

                elif status == 4:  # 4 = ps and skip -
                    self.previous_xbmc()

                elif not status:  # 0 = keys are normally processed
                    self.reset_timeout()

        # process_remote() will raise an exception on read errors
        except Exception, e:
            print str(e)
Example #8
0
class PS3RemoteThread ( StoppableThread ):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
        self.set_timeout(600)
        self.services = []
        self.current_xbmc = 0

    def run(self):
        sixaxis.initialize(self.csock, self.isock)
        self.xbmc.connect()
        try:
            # start the zeroconf thread if possible
            try:
                self.zeroconf_thread = ZeroconfThread()
                self.zeroconf_thread.add_service('_xbmc-events._udp',
                                             self.zeroconf_service_handler)
                self.zeroconf_thread.start()
            except Exception, e:
                print str(e)

            # main thread loop
            while not self.stop():
                status = process_remote(self.isock, self.xbmc)

                if status == 2:   # 2 = socket read timeout
                    if self.timed_out():
                        raise Exception("PS3 Blu-Ray Remote powering off, "\
                                            "timed out")
                elif status == 3: # 3 = ps and skip +
                    self.next_xbmc()

                elif status == 4: # 4 = ps and skip -
                    self.previous_xbmc()

                elif not status:  # 0 = keys are normally processed
                    self.reset_timeout()

        # process_remote() will raise an exception on read errors
        except Exception, e:
            print str(e)
Example #9
0
def main():

    host = "localhost"
    port = 9777
    
    # Create an XBMCClient object and connect
    xbmc = XBMCClient("Example Remote", "../../icons/bluetooth.png")
    xbmc.connect()

    # send a up key press using the xbox gamepad map "XG" and button
    # name "dpadup" ( see PacketBUTTON doc for more details)
    try:
        xbmc.send_action(sys.argv[2], ACTION_BUTTON)
    except:
        try:
            xbmc.send_action(sys.argv[1], ACTION_EXECBUILTIN)
        except Exception, e:
            print str(e)
            xbmc.send_action("XBMC.ActivateWindow(ShutdownMenu)")
Example #10
0
def main():

    host = "localhost"
    port = 9777

    if sys.argv[1] == "LIRC.Start":
        # Create an XBMCClient object and connect
        xbmc = XBMCClient("Starting LIRC")
    if sys.argv[1] == "LIRC.Stop":
        xbmc = XBMCClient("Stopping LIRC")
    xbmc.connect()

    try:
        xbmc.send_action(sys.argv[1], ACTION_EXECBUILTIN)
    except Exception, e:
        print str(e)
        xbmc.send_action("XBMC.ActivateWindow(ShutdownMenu)")
Example #11
0
class XBMCControl(object):
    """
    Implements a simple way to control basic XBMC library functions.
    """

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.artistdict = {}
        self.albumdict = {}
        self.genredict = {}
        self.eventclient = XBMCClient('xbmcPD')
        self.eventclient.connect(ip, 9777)
    
    def send(self, command):
        """
        Send a command to xbmc.

        Returns a string
        """
        #print "http://%s:%s/xbmcCmds/xbmcHttp?command=%s" % (self.ip, self.port, urllib.quote(command))
        #print "http://%s:%s/xbmcCmds/xbmcHttp?command=%s" % (self.ip, self.port, urllib.quote(command.encode("utf-8")))
        xbmcconn = urllib2.urlopen('http://%s:%s/xbmcCmds/xbmcHttp?command=%s' \
                                    % (self.ip, self.port, urllib.quote(command)))
        rawtext = xbmcconn.read()
        return rawtext

    def get_np(self):
        """
        Get currently playing file.

        Returns a dictionary or None.
        """
        rawtext = self.send('GetCurrentlyPlaying()')
        infos = (point.rstrip() for point in (rawtext.split('<li>')[1:-1]))
        infodict = {}
        for info in infos:
            infokey, infovalue = info.split(':', 1)
            infodict[infokey] = infovalue
        if len(infodict) != 0:
            return infodict
        return None
        
    def get_volume(self):
        """
        Get the currently set volume.

        Returns an integer.
        """
        volume = self.send('GetVolume')
        volume = int(volume.replace('<html>\n','').replace('</html>\n', '') \
                                                  .replace('<li>', ''))
        return volume

    def get_directory(self, path):
        """
        Get directory informations.

        Returns a list of subdirectories and a list of musicfiles
        """
        subdirs = self.send('GetDirectory(%s;/)' % path)
        subdirs = subdirs.replace('<html>\n','').replace('</html>\n', '')
        subdirs = [dirtydir.strip() for dirtydir in [subdir.split(';')[0] \
                                    for subdir in subdirs.split('<li>')[1:]]]
        musicfiles = self.send('GetDirectory(%s;[music])' % path)
        musicfiles = musicfiles.replace('<html>\n','').replace('</html>\n', '')
        musicfiles = [self.get_tags_from_filename(tagfile) for tagfile in \
                      [dirtyfile.strip() for dirtyfile in [musicfile.split(';')[0] \
                      for musicfile in musicfiles.split('<li>')[1:]]]]
        return subdirs, musicfiles

    def get_tags_from_filename(self, filename):
        """
        Get tags by filename.

        Returns a dictionary
        """
        rawtext = self.send('GetTagFromFilename(%s)' % filename)
        if rawtext != None:
            infos =  (text.rstrip() for text in (rawtext.split('<li>')[1:-1]))
            infodict = {}
            for info in infos:
                infokey, infovalue = info.split(':', 1)
                infodict[infokey] = infovalue
            if len(infodict) != 0:
                infodict['Path'] = filename
                return infodict

    def get_library_stats(self):
        """
        Get library statistics.

        Returns artistcount, albumcount, songcount and total playtime
        """
        artistcount = int(self.send('querymusicdatabase(select count(*) from artist)')[22:-25])
        albumcount = int(self.send('querymusicdatabase(select count(*) from album)')[22:-25])
        songcount = int(self.send('querymusicdatabase(select count(*) from song)')[22:-25])
        totallength = int(self.send('querymusicdatabase(select sum(iDuration) from song)')[22:-25])
        return artistcount, albumcount, songcount, totallength

    def get_current_playlist(self):
        """
        Get the music playlist contents.

        Returns a list filled by each file's tags
        """
        rawtext = self.send('GetPlaylistContents(0)')
        playlist = [text.rstrip() for text in rawtext.replace('</html>', '') \
                                                     .split('<li>')[1:]]
        return [self.get_tags_from_filename(musicfile) for musicfile in \
                [text.rstrip() for text in rawtext.replace('</html>', '') \
                                                  .split('<li>')[1:]]]

    def next(self):
        """
        Skip to the next song.
        """
        self.eventclient.send_action('XBMC.PlayerControl(Next)')
        #self.send("PlayListNext")

    def prev(self):
        """
        Return to the previous song.
        """
        self.eventclient.send_action('XBMC.PlayerControl(Previous)')

    def stop(self):
        """
        Stop playing.
        """
        self.eventclient.send_action('XBMC.PlayerControl(Stop)')

    def set_volume(self, volume):
        """
        Set the volume.
        """
        self.eventclient.send_action('XBMC.SetVolume(%s)' % volume)

    def get_playlist_length(self):
        """
        Get the playlist length.
        """
        return int(self.send('GetPlaylistLength(0)')[11:-8])

    def search_album(self, albumname):
        """
        Search for a specified albumname.
        """
        self.list_albums()
        album_id = self.albumdict[albumname]
        song_ids = self.send('querymusicdatabase(select idPath,strFileName  from song where idAlbum = %s)' % album_id)
        song_ids = song_ids.replace('<html>\n','').replace('</html>\n', '') \
                                                  .replace('</record>', '') \
                                                  .replace('</field>', '')
        records = song_ids.split('<record>')
        paths = []
        for record in records: 
            fields = record.split('<field>')[1:]
            if len(fields) == 2:
                #INEFFICIENT!
                paths.append(self.send('querymusicdatabase(select strPath from path where idPath = %s)' % fields[0])[22:-25]+fields[1])
        return [self.get_tags_from_filename(path) for path in paths]

    def list_artists(self):
        """
        Returns a list of all artists.
        """
        if len(self.artistdict) < 1:
            artists = self.send('querymusicdatabase(select strArtist, idArtist from artist order by strArtist)')
            artists = artists.replace('<html>\n','').replace('</html>\n', '') \
                                                    .replace('</record>', '') \
                                                    .replace('</field>', '')
            records = artists.split('<record>')
            for record in records:
                fields = record.split('<field>')[1:]
                if len(fields) == 2:
                    self.artistdict[fields[0]] = fields[1]
        return self.artistdict.keys()

    def list_genres(self):
        """
        Returns a list of all genres.
        """
        if len(self.genredict) < 1:
            genres = self.send('querymusicdatabase(select strGenre, idGenre from genre order by strGenre)')
            genres = genres.replace('<html>\n','').replace('</html>\n', '') \
                                                  .replace('</record>', '') \
                                                  .replace('</field>', '')
            records = genres.split('<record>')
            for record in records:
                fields = record.split('<field>')[1:]
                if len(fields) == 2:
                    self.genredict[fields[0]] = fields[1]
        return self.genredict.keys()

    def count_artist(self, artist):
        """
        Get number of songs by the specified artist and the total duration.

        Returns number of songs, total duration
        """
        self.list_artists()
        artist_id = self.artistdict[artist]
        song_count = self.send('querymusicdatabase(select count(*) from song where idArtist =  %s)' % artist_id)[22:-25]
        duration = self.send('querymusicdatabase(select sum(iDuration) from song where idArtist = %s)' % artist_id)[22:-25]
        if song_count == '0':
            duration = 0
        return song_count, duration

    def seekto(self, percentage):
        self.send("SeekPercentage(%d)" %percentage)

    def playid(self, song_id):
        """
        Play song specified by it's id.
        
        Note that the play button will send -1 when playback is stopped (not paused)
        That's the reason for the first if block.
        Also it appears to not work if we omit calling (the undocumented) SetCurrentPlaylist before
        """
        self.send('SetPlaylistSong(%s)' %song_id)

        self.send('SetCurrentPlaylist(0)')
        if song_id == '-1' or song_id == '0':
          self.send('PlayListNext(0)')
        else:
          self.send('SetPlaylistSong(%s)' %song_id)

    def playpause(self):
        """
        Toggle play or pause.
        """
        self.eventclient.send_action('XBMC.PlayerControl(Play)')
        #self.send('pause')

    def remove_from_playlist(self, pos):
        """
        Remove a song (specified by it's position inside the playlist) from
        the playlist.
        """
        self.send('RemoveFromPlaylist(%s;0)' % pos)
    
    def list_artist_albums(self, artist):
        """
        Get all albums by a specified artist.

        Returns a list.
        """
        self.list_artists()
        albums = self.send('querymusicdatabase(select strAlbum from album where idArtist = %s)' % self.artistdict[artist])
        albums = albums.replace('<record><field>', '').replace('<html>','') \
                                                      .replace('</html>', '') \
                                                      .replace('\n', '')
        return albums.split('</field></record>')[:-1]

    def list_albums(self):
        """
        Get all albums inside the library.

        Returns a list
        """
        if len(self.albumdict) <1:
            albums = self.send('querymusicdatabase(select strAlbum, idAlbum from album order by strAlbum)')
            albums = albums.replace('<html>\n','').replace('</html>\n', '') \
                                                  .replace('</record>', '') \
                                                  .replace('</field>', '')
            records = albums.split('<record>')
            for record in records:
                fields = record.split('<field>')[1:]
                if len(fields) == 2:
                    self.albumdict[fields[0]] = fields[1]
        return self.albumdict.keys()

    def list_album_date(self, album):
        """
        Get the date of the specified album.

        Returns a string

        TODO: Return a nice datetime object?
        """
        self.list_albums()
        date = self.send('querymusicdatabase(select iYear from album where idAlbum =  %s)' % self.albumdict[album])[22:-25]
        return date

    def play_file(self, path):
        """
        Play the given path
        """
        self.send('PlayFile(%s)' % path)

    def add_to_playlist(self, path):
        """
        Add the given path to the playlist.
        """
        self.send('AddToPlayList(%s;0)' % path)

    def list_dates(self):
        """
        Get a list of dates for which albums are available.

        Returns a list.
        """
        dates = self.send('querymusicdatabase(select distinct iYear from album)')
        dates = dates.replace('<record><field>', '').replace('<html>','') \
                                                    .replace('</html>', '') \
                                                    .replace('\n', '')
        return dates.split('</field></record>')[:-1]
Example #12
0
class PS3RemoteThread ( StoppableThread ):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
        self.set_timeout(600)
        self.services = []
        self.current_xbmc = 0

    def run(self):
        self.xbmc.connect()
        try:
            # start the zeroconf thread if possible
            try:
                self.zeroconf_thread = ZeroconfThread()
                self.zeroconf_thread.add_service('_xbmc-events._udp',
                                             self.zeroconf_service_handler)
                self.zeroconf_thread.start()
            except Exception as e:
                print(str(e))

            # main thread loop
            while not self.stop():
                status = process_remote(self.isock, self.xbmc)

                if status == 2:   # 2 = socket read timeout
                    if self.timed_out():
                        raise Exception("PS3 Blu-Ray Remote powering off, "\
                                            "timed out")
                elif status == 3: # 3 = ps and skip +
                    self.next_xbmc()

                elif status == 4: # 4 = ps and skip -
                    self.previous_xbmc()

                elif not status:  # 0 = keys are normally processed
                    self.reset_timeout()

        # process_remote() will raise an exception on read errors
        except Exception as e:
            print(str(e))

        self.zeroconf_thread.stop()
        self.close_sockets()

    def next_xbmc(self):
        """
        Connect to the next XBMC instance
        """
        self.current_xbmc = (self.current_xbmc + 1) % len( self.services )
        self.reconnect()
        return

    def previous_xbmc(self):
        """
        Connect to the previous XBMC instance
        """
        self.current_xbmc -= 1
        if self.current_xbmc < 0 :
            self.current_xbmc = len( self.services ) - 1
        self.reconnect()
        return

    def reconnect(self):
        """
        Reconnect to an XBMC instance based on self.current_xbmc
        """
        try:
            service = self.services[ self.current_xbmc ]
            print("Connecting to %s" % service['name'])
            self.xbmc.connect( service['address'], service['port'] )
            self.xbmc.send_notification("PS3 Blu-Ray Remote", "New Connection", None)
        except Exception as e:
            print(str(e))

    def zeroconf_service_handler(self, event, service):
        """
        Zeroconf event handler
        """
        if event == zeroconf.SERVICE_FOUND:  # new xbmc service detected
            self.services.append( service )

        elif event == zeroconf.SERVICE_LOST: # xbmc service lost
            try:
                # search for the service by name, since IP+port isn't available
                for s in self.services:
                    # nuke it, if found
                    if service['name'] == s['name']:
                        self.services.remove(s)
                        break
            except:
                pass
        return
Example #13
0
class PS3SixaxisThread ( StoppableThread ):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Sixaxis", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
        self.set_timeout(600)

    def run(self):
        sixaxis.initialize(self.csock, self.isock)
        self.xbmc.connect()
        bflags = 0
        released = set()
        pressed  = set()
        pending  = set()
        held     = set()
        psflags = 0
        psdown = 0
        toggle_mouse = 0
        self.reset_timeout()
        try:
            while not self.stop():
                if self.timed_out():

                    for key in (held | pressed):
                        (mapname, action, amount, axis) = keymap_sixaxis[key]
                        self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                    raise Exception("PS3 Sixaxis powering off, timed out")
                if self.idle_time() > 50:
                    self.xbmc.connect()
                try:
                    data = sixaxis.read_input(self.isock)
                except Exception, e:
                    print str(e)
                    break
                if not data:
                    continue

                (bflags, psflags, pressure) = sixaxis.process_input(data, self.xbmc, toggle_mouse)

                if psflags:
                    self.reset_timeout()
                    if psdown:
                        if (time.time() - psdown) > 5:

                            for key in (held | pressed):
                                (mapname, action, amount, axis) = keymap_sixaxis[key]
                                self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                            raise Exception("PS3 Sixaxis powering off, user request")
                    else:
                        psdown = time.time()
                else:
                    if psdown:
                        toggle_mouse = 1 - toggle_mouse
                    psdown = 0

                keys = set(getkeys(bflags))
                released = (pressed | held) - keys
                held     = (pressed | held) - released
                pressed  = (keys - held) & pending
                pending  = (keys - held)

                for key in released:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                for key in held:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    if amount > 0:
                        amount = pressure[amount-1] * 256
                        self.xbmc.send_button_state(map=mapname, button=action, amount=amount, down=1, axis=axis)

                for key in pressed:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    if amount > 0:
                        amount = pressure[amount-1] * 256
                    self.xbmc.send_button_state(map=mapname, button=action, amount=amount, down=1, axis=axis)

                if keys:
                    self.reset_timeout()


        except Exception, e:
            printerr()
        self.close_sockets()
Example #14
0
#! /usr/bin/python2.7

import gaugette.rotary_encoder
import gaugette.switch
from time import sleep
from time import clock

from xbmcclient import XBMCClient,ACTION_EXECBUILTIN,ACTION_BUTTON

host = "localhost"
port = 9777

xbmc = XBMCClient("Pi Remote", "")
xbmc.connect()

A_PIN  = 9
B_PIN  = 7
SW_PIN = 8
 
encoder = gaugette.rotary_encoder.RotaryEncoder(A_PIN, B_PIN)
switch = gaugette.switch.Switch(SW_PIN)
last_state = 0

stepcount=0
nullify=0
switch_last=clock()

volume = 50
 
while True:
Example #15
0
 def __init__(self, ip):
     super(Kodi, self).__init__()
     self.client = XBMCClient(name='remote-srv', ip=ip)
     self.ping_kodi()
     timer = threading.Timer(5.0, self.ping_kodi)
     timer.start()
Example #16
0
class PS3RemoteThread(StoppableThread):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Blu-Ray Remote",
                               icon_file=ICON_PATH + "/bluetooth.png",
                               ip=ipaddr)
        self.set_timeout(600)
        self.services = []
        self.current_xbmc = 0

    def run(self):
        self.xbmc.connect()
        try:
            # start the zeroconf thread if possible
            try:
                self.zeroconf_thread = ZeroconfThread()
                self.zeroconf_thread.add_service('_xbmc-events._udp',
                                                 self.zeroconf_service_handler)
                self.zeroconf_thread.start()
            except Exception as e:
                print(str(e))

            # main thread loop
            while not self.stop():
                status = process_remote(self.isock, self.xbmc)

                if status == 2:  # 2 = socket read timeout
                    if self.timed_out():
                        raise Exception("PS3 Blu-Ray Remote powering off, "\
                                            "timed out")
                elif status == 3:  # 3 = ps and skip +
                    self.next_xbmc()

                elif status == 4:  # 4 = ps and skip -
                    self.previous_xbmc()

                elif not status:  # 0 = keys are normally processed
                    self.reset_timeout()

        # process_remote() will raise an exception on read errors
        except Exception as e:
            print(str(e))

        self.zeroconf_thread.stop()
        self.close_sockets()

    def next_xbmc(self):
        """
        Connect to the next XBMC instance
        """
        self.current_xbmc = (self.current_xbmc + 1) % len(self.services)
        self.reconnect()
        return

    def previous_xbmc(self):
        """
        Connect to the previous XBMC instance
        """
        self.current_xbmc -= 1
        if self.current_xbmc < 0:
            self.current_xbmc = len(self.services) - 1
        self.reconnect()
        return

    def reconnect(self):
        """
        Reconnect to an XBMC instance based on self.current_xbmc
        """
        try:
            service = self.services[self.current_xbmc]
            print("Connecting to %s" % service['name'])
            self.xbmc.connect(service['address'], service['port'])
            self.xbmc.send_notification("PS3 Blu-Ray Remote", "New Connection",
                                        None)
        except Exception as e:
            print(str(e))

    def zeroconf_service_handler(self, event, service):
        """
        Zeroconf event handler
        """
        if event == zeroconf.SERVICE_FOUND:  # new xbmc service detected
            self.services.append(service)

        elif event == zeroconf.SERVICE_LOST:  # xbmc service lost
            try:
                # search for the service by name, since IP+port isn't available
                for s in self.services:
                    # nuke it, if found
                    if service['name'] == s['name']:
                        self.services.remove(s)
                        break
            except:
                pass
        return
Example #17
0
        if message.rstrip() != "":
            self.logger.log(self.level, message.rstrip())


# Replace stdout with logging to file at INFO level
sys.stdout = MyLogger(logger, logging.INFO)
# Replace stderr with logging to file at ERROR level
sys.stderr = MyLogger(logger, logging.ERROR)

dev = InputDevice(rfidreader)
PROGRAM = "RFID Music"
RUNDIR = os.path.dirname(os.path.realpath(__file__))
ICON = RUNDIR + "/rfid-music.png"

# create an XBMCClient object and connect
xbmc = XBMCClient(PROGRAM, ICON)
try:
    xbmc.connect()
except:
    print >> sys.stderr, "Could not connect to XBMC"
    sys.exit(1)

# grab the rfid reader device
try:
    dev.grab()
except:
    print >> sys.stderr, "Unable to grab RFID reader"
    sys.exit(1)

# create an empty list for the card number
cardnumber = []
Example #18
0
File: ps3d.py Project: tmgh/xbmc
class PS3SixaxisThread ( StoppableThread ):
    def __init__(self, csock, isock, ipaddr="127.0.0.1"):
        StoppableThread.__init__(self)
        self.csock = csock
        self.isock = isock
        self.xbmc = XBMCClient(name="PS3 Sixaxis", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
        self.set_timeout(600)

    def run(self):
        sixaxis.initialize(self.csock, self.isock)
        self.xbmc.connect()
        bflags = 0
        released = set()
        pressed  = set()
        pending  = set()
        held     = set()
        psflags = 0
        psdown = 0
        toggle_mouse = 0
        self.reset_timeout()
        try:
            while not self.stop():
                if self.timed_out():

                    for key in (held | pressed):
                        (mapname, action, amount, axis) = keymap_sixaxis[key]
                        self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                    raise Exception("PS3 Sixaxis powering off, timed out")
                if self.idle_time() > 50:
                    self.xbmc.connect()
                try:
                    data = sixaxis.read_input(self.isock)
                except Exception, e:
                    print str(e)
                    break
                if not data:
                    continue

                (bflags, psflags, pressure, analog) = sixaxis.process_input(data, self.xbmc, toggle_mouse)

                if analog:
                    self.reset_timeout()

                if psflags:
                    self.reset_timeout()
                    if psdown:
                        if (time.time() - psdown) > 5:

                            for key in (held | pressed):
                                (mapname, action, amount, axis) = keymap_sixaxis[key]
                                self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                            raise Exception("PS3 Sixaxis powering off, user request")
                    else:
                        psdown = time.time()
                else:
                    if psdown:
                        toggle_mouse = 1 - toggle_mouse
                    psdown = 0

                keys = set(getkeys(bflags))
                released = (pressed | held) - keys
                held     = (pressed | held) - released
                pressed  = (keys - held) & pending
                pending  = (keys - held)

                for key in released:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    self.xbmc.send_button_state(map=mapname, button=action, amount=0, down=0, axis=axis)

                for key in held:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    if amount > 0:
                        amount = pressure[amount-1] * 256
                        self.xbmc.send_button_state(map=mapname, button=action, amount=amount, down=1, axis=axis)

                for key in pressed:
                    (mapname, action, amount, axis) = keymap_sixaxis[key]
                    if amount > 0:
                        amount = pressure[amount-1] * 256
                    self.xbmc.send_button_state(map=mapname, button=action, amount=amount, down=1, axis=axis)

                if keys:
                    self.reset_timeout()


        except Exception, e:
            printerr()
        self.close_sockets()
Example #19
0
 def __init__(self, csock, isock, ipaddr="127.0.0.1"):
     StoppableThread.__init__(self)
     self.csock = csock
     self.isock = isock
     self.xbmc = XBMCClient(name="PS3 Sixaxis", icon_file=ICON_PATH + "/bluetooth.png", ip=ipaddr)
     self.set_timeout(600)
Example #20
0
def main():

    host = "localhost"
    port = 9777

    # Create an XBMCClient object and connect
    xbmc = XBMCClient("Example Remote", "../../icons/bluetooth.png")
    xbmc.connect()

    # wait for notification window to close (in XBMC) (optional)
    time.sleep(5)

    # send a up key press using the xbox gamepad map "XG" and button
    # name "dpadup" ( see PacketBUTTON doc for more details)
    xbmc.send_button(map="XG", button="dpadup")

    # wait for a few seconds to see its effect
    time.sleep(5)

    # send a right key press using the keyboard map "KB" and button
    # name "right"
    xbmc.send_keyboard_button("right")

    # wait for a few seconds to see its effect
    time.sleep(5)

    # that's enough, release the button.
    xbmc.release_button()

    # ok we're done, close the connection
    # Note that closing the connection clears any repeat key that is
    # active. So in this example, the actual release button event above
    # need not have been sent.
    xbmc.close()
Example #21
0
#! /usr/bin/python2.7

import gaugette.rotary_encoder
import gaugette.switch
from time import sleep
from time import clock

from xbmcclient import XBMCClient,ACTION_EXECBUILTIN,ACTION_BUTTON

host = "localhost"
port = 9777

xbmc = XBMCClient("Pi Remote", "")
xbmc.connect()

A_PIN  = 9
B_PIN  = 7
SW_PIN = 8
 
encoder = gaugette.rotary_encoder.RotaryEncoder(A_PIN, B_PIN)
switch = gaugette.switch.Switch(SW_PIN)
last_state = 0

stepcount=0
nullify=0
switch_last=clock()

 
while True:

    delta = encoder.get_delta()
Example #22
0
def main():

    host = "localhost"
    port = 9777

    # Create an XBMCClient object and connect
    xbmc = XBMCClient("Example Remote", "../../icons/bluetooth.png")
    xbmc.connect()

    # send a up key press using the xbox gamepad map "XG" and button
    # name "dpadup" ( see PacketBUTTON doc for more details)
    try:
        xbmc.send_action(sys.argv[2], ACTION_BUTTON)
    except:
        try:
            xbmc.send_action(sys.argv[1], ACTION_EXECBUILTIN)
        except Exception as e:
            print(str(e))
            xbmc.send_action("ActivateWindow(ShutdownMenu)")

    # ok we're done, close the connection
    # Note that closing the connection clears any repeat key that is
    # active. So in this example, the actual release button event above
    # need not have been sent.
    xbmc.close()
Example #23
0
def main():

    host = "localhost"
    port = 9777

    # Create an XBMCClient object and connect
    xbmc = XBMCClient("Example Remote", "../../icons/bluetooth.png")
    xbmc.connect()

    # wait for notification window to close (in XBMC) (optional)
    time.sleep(5)

    # send a up key press using the xbox gamepad map "XG" and button
    # name "dpadup" ( see PacketBUTTON doc for more details)
    xbmc.send_button(map="XG", button="dpadup")

    # wait for a few seconds to see its effect
    time.sleep(5)

    # send a right key press using the keyboard map "KB" and button
    # name "right"
    xbmc.send_keyboard_button("right")

    # wait for a few seconds to see its effect
    time.sleep(5)

    # that's enough, release the button.
    xbmc.release_button()

    # ok we're done, close the connection
    # Note that closing the connection clears any repeat key that is
    # active. So in this example, the actual release button event above
    # need not have been sent.
    xbmc.close()
Example #24
0
		# Only log if there is a message (not just a new line)
		if message.rstrip() != "":
			self.logger.log(self.level, message.rstrip())
 
# Replace stdout with logging to file at INFO level
sys.stdout = MyLogger(logger, logging.INFO)
# Replace stderr with logging to file at ERROR level
sys.stderr = MyLogger(logger, logging.ERROR)

dev = InputDevice(rfidreader)
PROGRAM = "RFID Music"
RUNDIR = os.path.dirname(os.path.realpath(__file__))
ICON = RUNDIR + "/rfid-music.png"

# create an XBMCClient object and connect
xbmc = XBMCClient(PROGRAM, ICON)
try:
  xbmc.connect()
except:
   print >> sys.stderr, "Could not connect to XBMC"
   sys.exit( 1 )  

# grab the rfid reader device
try:
  dev.grab()
except:
   print >> sys.stderr, "Unable to grab RFID reader"
   sys.exit( 1 )  

# create an empty list for the card number
cardnumber = []
Example #25
0
class Kodi(DeviceHandler):
    _logger = logging.getLogger('Kodi')

    codes = {
        'RED':      'red',
        'GREEN':    'green',
        'YELLOW':   'yellow',
        'BLUE':     'blue',
        'KEY_1':    'one',
        'KEY_2':    'two',
        'KEY_3':    'three',
        'KEY_4':    'four',
        'KEY_5':    'five',
        'KEY_6':    'six',
        'KEY_7':    'seven',
        'KEY_8':    'eight',
        'KEY_9':    'nine',
        'KEY_0':    'zero',
        'P+':       'pageplus',
        'P-':       'pageminus',
        'CH_LIST':  'playlist',
        'MENU':     'menu',
        'UP':       'up',
        'DOWN':     'down',
        'LEFT':     'left',
        'RIGHT':    'right',
        'OK':       'select',
        'RETURN':   'back',
        'INFO':     'info',
        'TOOLS':    'title',
        'EXIT':     'rootmenu',
        'PLAY':     'play',
        'PAUSE':    'pause',
        'SUPPORT':  'skipminus',
        '3D':       'skipplus',
        'STOP':     'stop',
        'REW':      'reverse',
        'FFWD':     'forward',
        'D':        'language',
        'REC':      'record'
    }

    def __init__(self, ip):
        super(Kodi, self).__init__()
        self.client = XBMCClient(name='remote-srv', ip=ip)
        self.ping_kodi()
        timer = threading.Timer(5.0, self.ping_kodi)
        timer.start()

    def ping_kodi(self):
        try:
            self.client.ping()
        except:
            self.logger.debug('connection lost. reconnecting')
            self.client.connect()

    @property
    def logger(self):
        return self._logger

    def _handle(self, keystroke_name):
        if keystroke_name in Kodi.codes.keys():
            code = Kodi.codes[keystroke_name]
            self.logger.debug('requesting code: [%s]' % code)
            self.client.send_button(map="R1", button=code)
            time.sleep(.1)
            self.client.release_button()
        else:
            self.logger.debug('no mapping found for %s' % keystroke_name)

    def switch_on(self):
        pass

    def switch_off(self):
        pass
Example #26
0
def main():

    host = "localhost"
    port = 9777
    
    # Create an XBMCClient object and connect
    xbmc = XBMCClient("Example Remote", "../../icons/bluetooth.png")
    xbmc.connect()

    # send a up key press using the xbox gamepad map "XG" and button
    # name "dpadup" ( see PacketBUTTON doc for more details)
    try:
        xbmc.send_action(sys.argv[2], ACTION_BUTTON)
    except:
        try:
            xbmc.send_action(sys.argv[1], ACTION_EXECBUILTIN)
        except Exception as e:
            print(str(e))
            xbmc.send_action("ActivateWindow(ShutdownMenu)")
    

    # ok we're done, close the connection
    # Note that closing the connection clears any repeat key that is
    # active. So in this example, the actual release button event above
    # need not have been sent.
    xbmc.close()
Example #27
0
addondir = str.strip(sys.argv[1])

try:
    imp.find_module('picamera')
    import picamera
    from picamera import PiCamera
except ImportError:
    print >> sys.stderr, 'PiCamera-Modul muss noch installiert werden !'
    quit()

# load external xbmcclient and open connection
sys.path.append(os.path.abspath(addondir))
from xbmcclient import XBMCClient, ACTION_EXECBUILTIN
host = "127.0.0.1"
port = 9777
xbmc = XBMCClient("Dashcam-Server", "")
xbmc.connect()


def xbmc_SendCommand(command):
    xbmc.send_action(command)


# Create a TCP/IP socket
sockdc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# get display resolution
rescheck = str.strip(os.popen("fbset | grep geometry").read())
resarray = rescheck.split(' ')
resx = int(resarray[1])
resy = int(resarray[2])