examples/mpd.lua
author Myhailo Danylenko <isbear@ukrpost.net>
Mon, 23 Mar 2009 04:16:22 +0200
changeset 59 4660c4f10ef1
parent 58 aa3376776cf2
child 66 542f61e113cb
permissions -rw-r--r--
Pep splitting


-- MPD INTERATION

-- TODO password support

-- library

require 'socket'

-- public

local settings = {
	hostname     = "localhost",
	password     = nil,
	port         = 6600,
}

mpd = { }

-- separator allows split output into records, that are started by any of present in separator keys
-- returns table of field (lowercase) - value records
-- command status is returned in STATUS field
-- on unexpected errors returns just false, dropping any available data
function mpd.receive_message ( tcp, separator )
	local ret  = {}
	local line = tcp:receive ( '*l' )
	while line and not ( line:match ( '^OK' ) or line:match ( '^ACK' ) ) do
		local key, val = line:match ( '^(.-):%s*(.*)$' )
		if key then
			if separator then
				key = key:lower ()
				if separator[key] then
					table.insert ( ret, {} )
				end
				ret[#ret][key]   = val
			else
				ret[key:lower()] = val
			end
		end
		line = tcp:receive ( '*l' )
	end
	if not line then
		return false -- an error occured, ret, most likely, does not contains exact and complete info...
	else
		ret.STATUS = line:match ( '^%S+' )
		return ret
	end
end

-- use: mpd.call_command { 'status' }
--      mpd.call_command { 'lsinfo misc', list = { file = true, directory = true } }
--      mpd.call_command { 'next', noret = true }
--      mpd.call_command { 'status', 'currentsong' }
-- on one command returns just results of that command, on multi - array of results
-- on errors returns nil
-- noret can terminate socket too early, thus, do not use it with lists of commands
function mpd.call_command ( opts )
	local tcp = socket.tcp ()
	if not tcp then
		print ( 'mpd: cannot get master tcp object' )
		return nil
	elseif not tcp:connect ( settings.hostname, settings.port ) then
		tcp:close ()
		print ( 'mpd: cannot connect to server' )
		return nil
	end

	local ret = {}
	if not opts.noret then
		ret = mpd.receive_message ( tcp )
		if not ret then
			tcp:close ()
			print ( 'mpd: error getting greeting from server' )
			return nil
		elseif ret.STATUS ~= 'OK' then
			print ( 'mpd: server ack\'s in greeting' )
		end
	end

	for num, command in ipairs ( opts ) do
		if not tcp:send ( command .. "\n" ) then
			tcp:close ()
			print ( 'mpd: error sending command ' .. command )
			return nil
		end
		if not opts.noret then
			ret[num] = mpd.receive_message ( tcp, opts.list )
			if not ret[num] then
				print ( 'mpd: error getting result' )
			end
			if ret[num]['STATUS'] ~= 'OK' then
				print ( 'mpd: server acks our command ' .. command )
			end
		end
	end

	tcp:close ()
	if #ret > 1 then
		return ret
	else
		return ret[1]
	end
end

-- vim: se ts=4: --