本文整理汇总了Python中mpd.MPDClient.ping方法的典型用法代码示例。如果您正苦于以下问题:Python MPDClient.ping方法的具体用法?Python MPDClient.ping怎么用?Python MPDClient.ping使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mpd.MPDClient
的用法示例。
在下文中一共展示了MPDClient.ping方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
class Player:
def __init__(self, host="localhost", port=6600):
self._host = host
self._port = port
self._client = MPDClient()
def _connect(self):
self._client.connect(self._host, self._port)
def _disconnect(self):
try:
self._client.disconnect()
except:
pass
def _ensure__connection(self):
try:
self._client.ping()
except (MPDError, ConnectionError, IOError):
self._disconnect()
self._connect()
def play(self, stream):
self._ensure__connection()
songId = self._client.addid(stream, 0)
self._client.playid(songId)
def stop(self):
self._ensure__connection()
self._client.stop()
def status(self):
self._ensure__connection()
return self._client.status()
def currentsong(self):
self._ensure__connection()
return self._client.currentsong()
def is_playing(self):
status = self.status()
return status['state'] == 'play'
示例2: Mpd2
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
class Mpd2(base.ThreadPoolText):
"""A widget for Music Player Daemon (MPD) based on python-mpd2
This widget exists since python-mpd library is no more supported.
Parameters
==========
status_format :
format string to display status
Full list of values see in ``status`` and ``currentsong`` commands
https://musicpd.org/doc/protocol/command_reference.html#command_status
https://musicpd.org/doc/protocol/tags.html
Default::
{play_status} {artist}/{title} [{repeat}{random}{single}{consume}{updating_db}]
``play_status`` is string from ``play_states`` dict
Note that ``time`` property of song renamed to ``fulltime`` to prevent
conflicts with status information during formating.
prepare_status :
dict of functions for replace values in status with custom
``f(status, key, space_element) => str``
"""
orientations = base.ORIENTATION_HORIZONTAL
defaults = [
('update_interval', 1, 'Interval of update widget'),
('host', 'localhost', 'Host of mpd server'),
('port', 6600, 'Port of mpd server'),
('password', None, 'Password for auth on mpd server'),
('keys', keys, 'Shortcut keys'),
('play_states', play_states, 'Play state mapping'),
('command', None, 'Executable command by "command" shortcut'),
('timeout', 30, 'MPDClient timeout'),
('idletimeout', 5, 'MPDClient idle command timeout'),
('no_connection', 'No connection', 'Text when mpd is disconnected'),
('space', '-', 'Space keeper')
]
def __init__(self, status_format=default_format,
prepare_status=prepare_status, **config):
super().__init__(None, **config)
self.add_defaults(Mpd2.defaults)
self.status_format = status_format
self.prepare_status = prepare_status
self.connected = False
self.client = MPDClient()
self.client.timeout = self.timeout
self.client.idletimeout = self.idletimeout
self.try_reconnect()
def try_reconnect(self):
if not self.connected:
try:
self.client.ping()
except(socket_error, ConnectionError):
try:
self.client.connect(self.host, self.port)
if self.password:
self.client.password(self.password)
self.connected = True
except(socket_error, ConnectionError, CommandError):
self.connected = False
def poll(self):
self.try_reconnect()
if self.connected:
return self.update_status()
else:
return self.no_connection
def update_status(self):
self.client.command_list_ok_begin()
self.client.status()
self.client.currentsong()
status, current_song = self.client.command_list_end()
return self.formatter(status, current_song)
# TODO: Resolve timeouts on the method call
def button_press(self, x, y, button):
self.try_reconnect()
if self.connected:
self[button]
def __getitem__(self, key):
if key == self.keys["toggle"]:
status = self.client.status()
play_status = status['state']
if play_status == 'play':
self.client.pause()
else:
#.........这里部分代码省略.........
示例3: len
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
if button != "":
if button.isdigit():
print "Number pressed"
if len(camuma_id) == 6:
print "Reset ID"
camuma_id=""
camuma_id = camuma_id + button
print "New ID : " + camuma_id
if len(camuma_id) == 6:
subprocess.check_call(["/home/pi/camuma.sh", camuma_id])
else:
camuma_id=""
print "Reset ID"
try:
client.ping()
except:
try:
client.disconnect()
except:
pass
try:
client.connect("localhost", 6600)
client.ping()
print("connected to MPD")
except:
print("failed to connect to MPD" )
if "toggle" == button:
print "Toggle from " + client.status()['state']
if client.status()['state'] in ('play'):
示例4: MPDSwitch
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
class MPDSwitch(SwitchClass):
class_metadata = {"type":"music"}
metadata = {}
client = None
state = {}
broadcast_status = False
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.getMPDClient()
self.poll()
def getMPDClient(self):
if self.client == None:
self.client = MPDClient()
self.client.connect("localhost", 6600)
else:
try:
self.client.ping()
except ConnectionError as e:
self.client = None
self.getMPDClient()
def poll(self):
""" This function calls itself every second to check for config changes """
self.getMPDClient()
state = self.getState(status=self.broadcast_status)
if self.state != state:
self.state = state
state = self.getState()
metadata = self.getMetaData()
res = {"result":"state", "switch":self.name, "state":state, "metadata":metadata}
self.factory.broadcast(res)
self.factory.loop.call_later(1, self.poll)
def close(self):
self.client.close()
self.client.disconnect()
def getCurrentSong(self):
song = self.parseSong(self.client.currentsong())
return song
def parseSong(self, song):
if "artist" in song and "album" in song and "title" in song:
song_str = "{artist} - {album}: {title}".format(**song)
elif "title" in song:
song_str = "{title}".format(**song)
elif "file" in song:
song_str = "{file}".format(**song).rpartition("/")[-1]
else:
song_str = "No song selected"
return song_str
def getState(self, song=True, playlist=True, status=True):
self.getMPDClient()
state = {}
if song: state["song"] = self.getCurrentSong()
if playlist: state["playlist"] = self.getPlaylist()
if status: state["status"] = self.getStatus()
return state
def getPlaylist(self):
self.getMPDClient()
playlist = self.client.playlistid()
parsed_playlist = [self.parseSong(song) for song in playlist]
return parsed_playlist
def getStatus(self):
self.getMPDClient()
status = self.client.status()
return status
@publicMethod
def get_playlist(self):
return self.getPlaylist()
@publicMethod
def next(self):
self.getMPDClient()
self.client.next()
return True
@publicMethod
def stop(self):
self.getMPDClient()
self.client.stop()
return True
@publicMethod
def previous(self):
self.getMPDClient()
self.client.previous()
return True
@publicMethod
def pause(self):
self.getMPDClient()
#.........这里部分代码省略.........
示例5: Player
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
class Player(object):
UNKNOWN = 0 # state
PAUSE = 1 # state
PLAY = 2 # state
STOP = 3 # state
HOST = 'localhost'
PORT = '6600'
def __init__(self, green, red):
self.green = green
self.red = red
self.mpdClient = None
self.__ensureConnected()
def __ensureConnected(self):
while self.__isConnected() is False:
try:
print("Connecting to MPD ...")
self.mpdClient = MPDClient()
self.mpdClient.connect(
host=self.HOST, port=self.PORT)
print("Connected. ")
except (ConnectionError, ConnectionRefusedError):
print("Could not connect to MPD. Retrying ...")
self.red.flash(.2, 1)
sleep(.5)
def __isConnected(self):
if self.mpdClient is None:
return False
try:
self.mpdClient.ping()
except (ConnectionError, BrokenPipeError):
return False
return True
@property
def state(self):
self.__ensureConnected()
state = self.mpdClient.status()["state"]
if state == "pause":
return self.PAUSE
elif state == "play":
return self.PLAY
elif state == "stop":
return self.STOP
return self.UNKNOWN
def play(self):
self.__ensureConnected()
while self.state is not self.PLAY:
self.mpdClient.play()
sleep(.1)
self.green.on()
def pause(self):
self.__ensureConnected()
self.mpdClient.pause()
self.green.off()
def track_back(self):
self.__ensureConnected()
self.mpdClient.previous()
self.green.flash(.2, 3,
turnOn=True if self.state is self.PLAY else False)
示例6: __init__
# 需要导入模块: from mpd import MPDClient [as 别名]
# 或者: from mpd.MPDClient import ping [as 别名]
class mpd_client:
def __init__(self, con_id, password):
# Create First MPD client(for status)
self.client = MPDClient()
# Create Second MPD client (for commands)
self.cmd_client = MPDClient()
# Connect to the MPD daemon (first client)
if (self.mpdConnect(self.client, con_id) == False):
print('Connection to MPD daemon (for status) failed!')
sys.exit(1)
# Connect to the MPD daemon (second client)
if (self.mpdConnect(self.cmd_client, con_id) == False):
print('Connection to MPD daemon (for commands) failed!')
sys.exit(1)
# If password is set, we have to authenticate
if password:
# First client
if (self.mpdAuth(self.client, password) == False):
print('MPD authentication (for status) failed!')
sys.exit(1)
# Second client
if (self.mpdAuth(self.cmd_client, password) == False):
print('MPD authentication (for commands) failed!')
sys.exit(1)
# Initialize data container
self.data = {
'artist': '', # Contains artist name or radio station name
'title': '', # Contains song title or when radio playing, "artist - title" format
'type': 0, # 0 - file, 1 - radio
'state': 0, # 0 - stopped, 1 - playing, 2 - paused
'volume': '', # Volume value
'shuffle': False, # True - ON, False - OFF
'repeat_all': False, # True - ON, False - OFF
'repeat_single': False, # True - ON, False - OFF
'elapsed_time': 0, # Song elapsed time
'total_time': 0, # Total song duration
'bitrate': 0, # Song/station bitrate (for example 320)
'playtime': 0, # Total playing time from last reboot
'uptime': 0 # Total uptime from last reboot
}
# Initialize LCD listener for changes
self.LCD_client = False
# Get first data update
self.updateData()
# Function for connecting to MPD daemon
def mpdConnect(self, client, con_id):
try:
client.connect(**con_id)
except SocketError:
return False
return True
# Function for authenticating to MPD if password is set
def mpdAuth(client, pwd):
try:
client.password(pwd)
except CommandError:
return False
return True
# Function for pinging cmd_client, we have to ping it or it will close connection
def mpdPing(self):
while True:
time.sleep(50) # We will ping it every 50 seconds
self.cmd_client.ping() # Ping it!
# Register LCD client listener
def register(self, lcd):
self.LCD_client = lcd
# Start MPD threads
def start(self):
# MPD Ping Thread - we have to ping cmd_client to prevent closing connection
self.mpdping_t = threading.Thread(target=self.mpdPing, args = ()) # Create thread for pinging MPD
self.mpdping_t.daemon = True # Yep, it's a daemon, when main thread finish, this one will finish too
self.mpdping_t.start() # Start it!
# Main Thread - Start main thread which waits for changes
self.mpd_t = threading.Thread(target=self.mpdMain, args = ()) # Create thread
self.mpd_t.daemon = True # Yep, it's a daemon, when main thread finish, this one will finish too
self.mpd_t.start() # Start it!
# Counter Thread - we have to count elapsed time, playtime and uptime
self.counter_t = threading.Thread(target=self.timeCounter, args = ()) # Create thread
self.counter_t.daemon = True # Yep, it's a daemon, when main thread finish, this one will finish too
self.counter_t.start() # Start it!
# Wait for all threads to finish
def join(self):
# Wait for MPD ping thread to finish
self.mpdping_t.join()
#.........这里部分代码省略.........