Class: MPD

Inherits:
Object
  • Object
show all
Includes:
Parser, Plugins::Channels, Plugins::Controls, Plugins::Database, Plugins::Information, Plugins::Outputs, Plugins::PlaybackOptions, Plugins::Playlists, Plugins::Queue, Plugins::Reflection, Plugins::Stickers
Defined in:
lib/ruby-mpd.rb,
lib/ruby-mpd/song.rb,
lib/ruby-mpd/parser.rb,
lib/ruby-mpd/version.rb,
lib/ruby-mpd/playlist.rb,
lib/ruby-mpd/exceptions.rb,
lib/ruby-mpd/plugins/queue.rb,
lib/ruby-mpd/plugins/outputs.rb,
lib/ruby-mpd/plugins/channels.rb,
lib/ruby-mpd/plugins/controls.rb,
lib/ruby-mpd/plugins/database.rb,
lib/ruby-mpd/plugins/stickers.rb,
lib/ruby-mpd/plugins/playlists.rb,
lib/ruby-mpd/plugins/reflection.rb,
lib/ruby-mpd/plugins/information.rb,
lib/ruby-mpd/plugins/playback_options.rb

Overview

The main class/namespace of the MPD client.

Defined Under Namespace

Modules: Parser, Plugins Classes: AlreadyExists, AlreadyUpdating, ConnectionError, Error, IncorrectPassword, NotFound, NotListError, NotPlaying, PermissionError, Playlist, PlaylistLoadError, PlaylistMaxError, ServerArgumentError, ServerError, Song, SystemError

Constant Summary collapse

VERSION =
'0.3.3'

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Plugins::Channels

#channels, #readmessages, #sendmessage, #subscribe, #unsubscribe

Methods included from Plugins::Reflection

#commands, #config, #decoders, #notcommands, #tags, #url_handlers

Methods included from Plugins::Outputs

#disableoutput, #enableoutput, #outputs, #toggleoutput

Methods included from Plugins::Stickers

#delete_sticker, #find_sticker, #get_sticker, #list_stickers, #set_sticker

Methods included from Plugins::Database

#albums, #artists, #count, #directories, #files, #list, #rescan, #search, #songs, #songs_by_artist, #update, #where

Methods included from Plugins::Playlists

#playlists

Methods included from Plugins::Queue

#add, #addid, #clear, #delete, #move, #queue, #queue_changes, #queue_search, #queue_where, #save, #shuffle, #song_priority, #song_with_id, #swap, #swapid

Methods included from Plugins::Controls

#next, #pause=, #play, #previous, #seek, #stop

Methods included from Plugins::PlaybackOptions

#consume=, #crossfade=, #mixrampdb=, #mixrampdelay=, #random=, #repeat=, #replay_gain_mode=, #replay_gain_status, #single=, #volume=

Methods included from Plugins::Information

#clearerror, #consume?, #crossfade, #current_song, #paused?, #playing?, #playlist_version, #random?, #repeat?, #single?, #stats, #status, #stopped?, #volume

Constructor Details

#initialize(hostname = 'localhost', port = 6600, opts = {}) ⇒ MPD

Initialize an MPD object with the specified hostname and port. When called without arguments, ‘localhost’ and 6600 are used.

When called with callbacks: true as an optional argument, callbacks will be enabled by starting a separate polling thread.

Parameters:

  • hostname (String) (defaults to: 'localhost')

    Hostname of the daemon

  • port (Integer) (defaults to: 6600)

    Port of the daemon

  • opts (Hash) (defaults to: {})

    Optional parameters. Currently accepts callbacks



53
54
55
56
57
58
59
60
61
62
# File 'lib/ruby-mpd.rb', line 53

def initialize(hostname = 'localhost', port = 6600, opts = {})
  @hostname = hostname
  @port = port
  @options = {callbacks: false}.merge(opts)
  @password = opts.delete(:password) || nil
  reset_vars

  @mutex = Mutex.new
  @callbacks = {}
end

Instance Attribute Details

#hostnameObject (readonly)

Returns the value of attribute hostname.



42
43
44
# File 'lib/ruby-mpd.rb', line 42

def hostname
  @hostname
end

#portObject (readonly)

Returns the value of attribute port.



42
43
44
# File 'lib/ruby-mpd.rb', line 42

def port
  @port
end

#versionObject (readonly)

Returns the value of attribute version.



42
43
44
# File 'lib/ruby-mpd.rb', line 42

def version
  @version
end

Instance Method Details

#authenticateObject



169
170
171
# File 'lib/ruby-mpd.rb', line 169

def authenticate
  send_command(:password, @password) if @password
end

#connect(callbacks = nil) ⇒ true

Connect to the daemon.

When called without any arguments, this will just connect to the server and wait for your commands.

Returns:

  • (true)

    Successfully connected.

Raises:

  • (MPDError)

    If connect is called on an already connected instance.



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/ruby-mpd.rb', line 99

def connect(callbacks = nil)
  raise ConnectionError, 'Already connected!' if connected?

  # by protocol, we need to get a 'OK MPD <version>' reply
  # should we fail to do so, the connection was unsuccessful
  unless response = socket.gets
    reset_vars
    raise ConnectionError, 'Unable to connect (possibly too many connections open)'
  end

  authenticate
  @version = response.chomp.gsub('OK MPD ', '') # Read the version

  if callbacks
    warn "Using 'true' or 'false' as an argument to MPD#connect has been deprecated, and will be removed in the future!"
    @options.merge!(callbacks: callbacks)
  end

  callback_thread if @options[:callbacks]
  return true
end

#connected?Boolean

Check if the client is connected.

Returns:

  • (Boolean)

    True only if the server responds otherwise false.



124
125
126
127
# File 'lib/ruby-mpd.rb', line 124

def connected?
  return false unless @socket
  send_command(:ping) rescue false
end

#disconnectBoolean

Disconnect from the MPD daemon. This has no effect if the client is not connected. Reconnect using the #connect method. This will also stop the callback thread, thus disabling callbacks.

Returns:

  • (Boolean)

    True if successfully disconnected, false otherwise.



133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
# File 'lib/ruby-mpd.rb', line 133

def disconnect
  @cb_thread[:stop] = true if @cb_thread

  return false unless @socket

  begin
    @socket.puts 'close'
    @socket.close
  rescue Errno::EPIPE
    # socket was forcefully closed
  end

  reset_vars
  return true
end

#emit(event, *args) ⇒ void

This method returns an undefined value.

Triggers an event, running it’s callbacks.

Parameters:

  • event (Symbol)

    The event that happened.



87
88
89
90
# File 'lib/ruby-mpd.rb', line 87

def emit(event, *args)
  return unless @callbacks[event]
  @callbacks[event].each { |handle| handle.call(*args) }
end

#killBoolean

Kills the MPD process.

Returns:

  • (Boolean)

    returns true if successful.

Raises:

  • (MPDError)

    if the command failed.



158
159
160
# File 'lib/ruby-mpd.rb', line 158

def kill
  send_command :kill
end

#on(event, &block) ⇒ void

This method returns an undefined value.

This will register a block callback that will trigger whenever that specific event happens.

mpd.on :volume do |volume|
  puts "Volume was set to #{volume}!"
end

One can also define separate methods or Procs and whatnot, just pass them in as a parameter.

method = Proc.new {|volume| puts "Volume was set to #{volume}!" }
mpd.on :volume, &method

Parameters:

  • event (Symbol)

    The event we wish to listen for.

  • block (Proc, Method)

    The actual callback.



80
81
82
# File 'lib/ruby-mpd.rb', line 80

def on(event, &block)
  (@callbacks[event] ||= []).push block
end

#password(pass) ⇒ Boolean

Used for authentication with the server.

Parameters:

  • pass (String)

    Plaintext password

Returns:

  • (Boolean)

    returns true if successful.

Raises:

  • (MPDError)

    if the command failed.



165
166
167
# File 'lib/ruby-mpd.rb', line 165

def password(pass)
  send_command :password, pass
end

#pingBoolean

Ping the server.

Returns:

  • (Boolean)

    returns true if successful.

Raises:

  • (MPDError)

    if the command failed.



175
176
177
# File 'lib/ruby-mpd.rb', line 175

def ping
  send_command :ping
end

#reconnectBoolean

Attempts to reconnect to the MPD daemon.

Returns:

  • (Boolean)

    True if successfully reconnected, false otherwise.



151
152
153
154
# File 'lib/ruby-mpd.rb', line 151

def reconnect
  disconnect
  connect
end

#send_command(command, *args) ⇒ true, ...

Used to send a command to the server, and to recieve the reply. Reply gets parsed. Synchronized on a mutex to be thread safe.

Can be used to get low level direct access to MPD daemon. Not recommended, should be just left for internal use by other methods.

Returns:

  • (true)

    If “OK” is returned.

  • (Array<Hash>, Array<String>, String, Integer)

    Parsed response.

Raises:

  • (MPDError)

    if the command failed.



188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/ruby-mpd.rb', line 188

def send_command(command, *args)
  raise ConnectionError, "Not connected to the server!" unless socket

  @mutex.synchronize do
    begin
      socket.puts convert_command(command, *args)
      response = handle_server_response
      return parse_response(command, response)
    rescue Errno::EPIPE
      reconnect
      retry
    end
  end
end