1 -- Originally from https://awesomewm.org/recipes/mpc/
3 local lgi = require "lgi"
7 local trace_mpc = false
11 local function parse_password(host)
12 -- This function is based on mpd_parse_host_password() from libmpdclient
13 local position = string.find(host, "@")
17 return string.sub(host, position + 1), string.sub(host, 1, position - 1)
20 function mpc.new(host, port, password, error_handler, ...)
21 host = host or os.getenv("MPD_HOST") or "localhost"
22 port = port or os.getenv("MPD_PORT") or 6600
24 host, password = parse_password(host)
26 local self = setmetatable({
30 _error_handler = error_handler or function() end,
32 _try_reconnect = false,
33 _idle_subsystems = { ... }
39 function mpc:_write(command)
41 print("write: " .. command)
43 self._output:write(command .. "\n")
46 function mpc:_error(err)
47 self._connected = false
48 self._error_handler(err)
49 self._try_reconnect = not self._try_reconnect
50 if self._try_reconnect then
55 function mpc:_connect()
56 if self._connected then return end
57 -- Reset all of our state
58 self._reply_handlers = {}
59 self._pending_reply = {}
60 self._idle_commands_pending = false
62 self._connected = true
64 -- Set up a new connection
66 if string.sub(self._host, 1, 1) == "/" then
68 address = Gio.UnixSocketAddress.new(self._host)
70 -- Do a TCP connection
71 address = Gio.NetworkAddress.new(self._host, self._port)
73 local client = Gio.SocketClient()
74 local conn, err = client:connect(address)
81 local input, output = conn:get_input_stream(), conn:get_output_stream()
82 self._conn, self._output, self._input = conn, output, Gio.DataInputStream.new(input)
84 -- Read the welcome message
85 self._input:read_line()
87 if self._password and self._password ~= "" then
88 self:_send("password " .. self._password)
91 -- Set up the reading loop. This will asynchronously read lines by
95 self._input:read_line_async(GLib.PRIORITY_DEFAULT, nil, function(obj, res)
96 local line, err = obj:read_line_finish(res)
97 -- Ugly API. On success we get string, length-of-string
98 -- and on error we get nil, error. Other versions of lgi
99 -- behave differently.
100 if line == nil or tostring(line) == "" then
101 err = "Connection closed"
103 if type(err) ~= "number" then
104 self._output, self._input = nil, nil
107 line = tostring(line)
108 if line == "OK" or line:match("^ACK ") then
109 local success = line == "OK"
112 arg = self._pending_reply
116 local handler = self._reply_handlers[1]
117 table.remove(self._reply_handlers, 1)
118 self._pending_reply = {}
119 handler(success, arg)
121 if next(self._reply_handlers) == nil then
125 local _, _, key, value = string.find(line, "([^:]+):%s(.+)")
127 local k = string.lower(key)
128 if k == "binary" then
129 value = tonumber(value)
132 local b = assert(obj:read_bytes(value))
133 table.insert(data, b.data)
136 local w = obj:read_bytes(1) -- read newline at end of binary
137 self._pending_reply[k] = table.concat(data)
138 elseif k == "changed" then
139 if not self._pending_reply[k] then
140 self._pending_reply[k] = {}
143 self._pending_reply[k][value] = true
145 self._pending_reply[k] = value
155 -- To synchronize the state on startup, send the idle commands now.
156 for i = 1, #self._idle_subsystems, 2 do
157 self._idle_subsystems[i+1](self)
163 function mpc:_start_idle()
165 error("start_idle but already idle")
167 self:_send("idle", function(success, reply)
169 if reply.changed then
170 -- idle mode was disabled by mpd
171 for i = 1, #self._idle_subsystems, 2 do
172 local subsys = self._idle_subsystems[i]
173 if reply.changed[subsys] then
174 self._idle_subsystems[i+1](self)
182 function mpc:_stop_idle()
183 if not self._idle then
184 error("stop_idle but not idle")
186 self:_write("noidle")
190 function mpc:_send(command, callback)
192 error("Still idle in send()?!")
195 table.insert(self._reply_handlers, callback or function() end)
198 function mpc:send(...)
200 if not self._connected then
207 for i = 1, #args, 2 do
208 self:_send(args[i], args[i+1])
212 function mpc:toggle_play()
213 self:send("status", function(success, status)
214 if status.state == "stop" then
222 function clamp(x, min, max)
223 return math.min(math.max(x, min), max)
226 function mpc:change_volume(change)
227 self:send("status", function(_, status)
228 new_vol = clamp(tonumber(status.volume) + change, 0, 100)
229 self:send("setvol " .. new_vol)
233 function mpc:currentsong()
235 self:send("currentsong", function(err, song)
236 if err then error(err) end
242 local function escape(str)
243 return "\"" .. str .. "\""
246 function mpc:albumart(uri, handler)
247 local image_table = {}
249 get_art_at = function(off)
250 self:send("albumart " .. escape(uri) .. " " .. tostring(off), function(success, data)
252 handler(success, data)
254 table.insert(image_table, data.binary)
255 if data.binary and #data.binary > 0 then
256 get_art_at(off + #data.binary)
258 data.binary = table.concat(image_table)
259 handler(success, data)
268 -- Example on how to use this (standalone)
270 local host, port, password = nil, nil, nil
271 local m = mpc.new(host, port, password, error,
272 "status", function(success, status) print("status is", status.state) end)
274 GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1000, function()
275 -- Test command submission
276 m:send("status", function(_, s) print(s.state) end,
277 "currentsong", function(_, s) print(s.title) end)
278 m:send("status", function(_, s) print(s.state) end)
280 GLib.timeout_add(GLib.PRIORITY_DEFAULT, 1000, function()
285 GLib.MainLoop():run()