* reorganized connection code

2009-08-23

author
Alexandre "kAworu" Perrin <kaworu(a)kaworu,ch>
date
Sun Aug 23 17:24:47 2009 +0200
changeset 8
f34ad3eb9b45
parent 7
504035ec7947
child 9
27bf43405389

* reorganized connection code
* ensure returning a table with the errormsg field on error

mpd.lua file | annotate | diff | revisions
     1.1 --- a/mpd.lua	Sun Aug 23 16:21:47 2009 +0200
     1.2 +++ b/mpd.lua	Sun Aug 23 17:24:47 2009 +0200
     1.3 @@ -91,6 +91,13 @@
     1.4  --              ...
     1.5  --      then the returned table is:
     1.6  --      { volume = 20, repeat = 0, random = 0, playlist = 599, ... }
     1.7 +--
     1.8 +-- if an error arise (bad password, connection failed etc.), a table with only
     1.9 +-- the errormsg field is returned.
    1.10 +--      Example: if there is no server running on host/port, then the returned
    1.11 +--      table is:
    1.12 +--              { errormsg = "could not connect" }
    1.13 +--
    1.14  function MPD:send(action)
    1.15      local command = string.format("%s\n", action)
    1.16      local values = {}
    1.17 @@ -102,25 +109,27 @@
    1.18              self.socket:settimeout(self.timeout, 't')
    1.19              self.last_try = os.time()
    1.20              self.connected = self.socket:connect(self.hostname, self.port)
    1.21 +            if not self.connected then
    1.22 +                return { errormsg = "could not connect" }
    1.23 +            end
    1.24  
    1.25              -- Read the server's hello message
    1.26 -            if self.connected then
    1.27 -                local line = self.socket:receive("*l")
    1.28 -                if not line:match("^OK") then
    1.29 -                    -- Invalid message?
    1.30 -                    self.connected = false
    1.31 +            local line = self.socket:receive("*l")
    1.32 +            if not line:match("^OK MPD") then -- Invalid hello message?
    1.33 +                self.connected = false
    1.34 +                return { errormsg = string.format("invalid hello message: %s", line) }
    1.35 +            end
    1.36 +
    1.37 +            -- send the password if needed
    1.38 +            if self.password then
    1.39 +                local rsp = self:send(string.format("password %s", self.password))
    1.40 +                if rsp.errormsg then
    1.41 +                    return rsp
    1.42                  end
    1.43              end
    1.44 -            if self.connected and self.password then
    1.45 -                self:send(string.format("password %s", self.password))
    1.46 -            end
    1.47          end
    1.48      end
    1.49  
    1.50 -    if not self.connected then
    1.51 -        return { errormsg = "could not connect" }
    1.52 -    end
    1.53 -
    1.54      self.socket:send(command)
    1.55  
    1.56      local line = ""

mercurial