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.2.5'

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

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

Methods included from Plugins::Playlists

#playlists

Methods included from Plugins::Queue

#add, #addid, #clear, #delete, #move, #queue, #queue_changes, #queue_search, #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) ⇒ MPD

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



47
48
49
50
51
52
53
54
# File 'lib/ruby-mpd.rb', line 47

def initialize(hostname = 'localhost', port = 6600)
  @hostname = hostname
  @port = port
  reset_vars

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

Instance Attribute Details

#versionObject (readonly)

The version of the MPD protocol the server is using.



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

def version
  @version
end

Instance Method Details

#connect(opts = {callbacks: false}) ⇒ true

Connect to the daemon.

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

When called with callbacks: true as an argument, this will enable callbacks by starting a seperate polling thread, which will also automatically reconnect if disconnected for whatever reason.

Returns:

  • (true)

    Successfully connected.

Raises:

  • (MPDError)

    If connect is called on an already connected instance.



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/ruby-mpd.rb', line 145

def connect(opts = {callbacks: false})
  raise ConnectionError, 'Already connected!' if self.connected?

  @socket = File.exists?(@hostname) ? UNIXSocket.new(@hostname) : TCPSocket.new(@hostname, @port)

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

  if opts == true || opts == false
    warn "Using 'true' or 'false' as an argument to #connect has been deprecated, and will be removed in the future!"
    opts = {callbacks: opts}
  end

  callback_thread if opts[:callbacks]
  return true
end

#connected?Boolean

Check if the client is connected.

Returns:

  • (Boolean)

    True only if the server responds otherwise false.



171
172
173
174
175
176
# File 'lib/ruby-mpd.rb', line 171

def connected?
  return false if !@socket

  ret = send_command(:ping) rescue false
  return ret
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.



182
183
184
185
186
187
188
189
190
191
# File 'lib/ruby-mpd.rb', line 182

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

  return false if !@socket

  @socket.puts 'close'
  @socket.close
  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.



88
89
90
91
92
93
# File 'lib/ruby-mpd.rb', line 88

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

#killBoolean

Kills the MPD process.

Returns:

  • (Boolean)

    returns true if successful.

Raises:

  • (MPDError)

    if the command failed.



195
196
197
# File 'lib/ruby-mpd.rb', line 195

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
83
# File 'lib/ruby-mpd.rb', line 80

def on(event, &block)
  @callbacks[event] ||= []
  @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.



202
203
204
# File 'lib/ruby-mpd.rb', line 202

def password(pass)
  send_command :password, pass
end

#pingBoolean

Ping the server.

Returns:

  • (Boolean)

    returns true if successful.

Raises:

  • (MPDError)

    if the command failed.



208
209
210
# File 'lib/ruby-mpd.rb', line 208

def ping
  send_command :ping
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.



221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/ruby-mpd.rb', line 221

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

  @mutex.synchronize do
    begin
      @socket.puts convert_command(command, *args)
      response = handle_server_response
      return parse_response(command, response)
    rescue Errno::EPIPE
      reset_vars # kill the socket and reset
      raise ConnectionError, 'Broken pipe (got disconnected)'
    end
  end
end