I feel you should await and read responses from the server, instead of
just flooding it with messages (note your sleep is 5 secs, your display
time is 10, and show blocks!).

Use this with Python 2.5...

Code:
--------------------
    
  import sys, time, telnetlib, urllib
  
  MIDDOT = u"\u00B7"
  MDASH = u'\u2013'
  
  class Bag(object):
  """ Bag of attributes.
  """
  
  def __init__(self, **kw):
  """ Populate a bag with given keyword arguments.
  """
  self.__dict__.update(kw)
  
  def __getitem__(self, name):
  """ Get value by name.
  
  @param name: Name of property.
  @return: None
  """
  return self.__dict__[name]
  
  def get(self, name, default):
  """ Get value by name.
  
  @param name: Name of property.
  @param default: Default value.
  @return: Value or given default value.
  """
  return self.__dict__.get(name, default)
  
  def keys(self):
  """ Return list of properties.
  
  @return: Defined properties.
  @rtype: list
  """
  return self.__dict__.keys()
  
  def __repr__(self):
  """ Return object creation code.
  """
  return "Bag(%s)" % ', '.join(
  ["%s=%r" % i for i in self.__dict__.iteritems()]
  )
  
  
  class SqueezeConnection(object):
  
  host = "localhost"
  port = 9090
  timeout = 10
  debug_level = 0
  
  def __init__(self):
  self._session = None
  self.player_id = None
  
  def open(self, host=None, port=None):
  if self._session is not None:
  raise IOError("Already connected to %s:%d" % (self.host, self.port))
  
  self.host = host or self.host
  self.port = port or self.port
  
  self._session = telnetlib.Telnet(self.host, self.port)
  if self.debug_level:
  self._session.set_debuglevel(self.debug_level)
  
  def doPlayer(self, cmd, *args, **tags):
  assert self.player_id is not None, "Player ID not set!"
  return self.do(*((self.player_id, cmd) + args), **tags)
  
  def do(self, cmd, *args, **tags):
  if self._session is None:
  self.open()
  
  cmdargs = [str(a) for a in args]
  cmdtags = ["%s:%s" % i for i in tags.items()]
  cmdline = ' '.join(urllib.quote(p) for p in [cmd] + cmdargs + cmdtags)
  
  if self.debug_level:
  print ">>>", cmdline
  self._session.write(cmdline + '\n')
  
  resp = self._session.read_until('\n', self.timeout)
  resp = resp.strip().split()
  
  data = {
  "_player_id": None,
  "_cmd": None,
  "_argv": [],
  }
  
  def typed(val):
  if isinstance(val, basestring):
  if val.isdigit():
  val = int(val, 10)
  else:
  fp = val.split('.')
  if len(fp) == 2 and fp[0].isdigit() and fp[1].isdigit():
  val = float(val)
  else:
  try:
  val = val.decode("UTF8")
  except UnicodeError:
  pass
  return val
  
  if resp and "%3A" in resp[0].upper():
  data["_player_id"] = urllib.unquote(resp[0])
  resp = resp[1:]
  
  if resp:
  data["_cmd"] = typed(urllib.unquote(resp[0]))
  resp = resp[1:]
  
  while resp and not(resp[0][0].isalpha() and "%3A" in resp[0].upper()):
  val = urllib.unquote(resp[0])
  data["_argv"].append(typed(val))
  resp = resp[1:]
  
  if resp:
  data.update(dict(urllib.unquote(p).split(':', 1) for p in resp))
  for key, val in list(data.items()):
  data[key] = typed(val)
  if ' ' in key:
  data[key.replace(' ', '_')] = data[key]
  del data[key]
  
  if self.debug_level:
  print "RESPONSE\n    %s" % "\n    ".join(
  "%20s %r" % i for i in sorted(data.items())
  )
  return Bag(**data)
  
  def close(self):
  """ Close the connection.
  """
  try:
  self.do("exit")
  #time.sleep(.05)
  self._session.close()
  finally:
  self._session = None
  
  def nowPlaying():
  sqc = SqueezeConnection()
  try:
  # speak with first player, in case several are available
  sqc.player_id = sqc.do("player", "id", 0, "?")._argv[-1]
  
  #sqc.doPlayer("show", line2="Hello, World!", font="huge", centered=1, 
duration=1)
  #sqc.doPlayer("displaynow", "?", "?")
  
  status = sqc.doPlayer("status", "-", 1, tags="glartyd")
  if status.mode == "play":
  #status.trackno = status.playlist_cur_index + 1
  status.duration_min = status.duration // 60
  status.duration_sec = status.duration %  60
  
  prefix = ''
  status.bold = ''
  if sys.argv[1:]:
  prefix = "/me %s %s" % (
  sys.argv[1], ' '.join(sys.argv[2:] or ["squeezes"])
  )
  status.bold = '\\b'
  
  now_playing = (prefix +
  " %(tracknum)02d - %(bold)s%(title)s%(bold)s"
  " [%(duration_min)02d:%(duration_sec)02d] " + MIDDOT +
  " %(artist)s (%(year)d) %(album)s @ %(bitrate)s"
  ) % status
  print now_playing.encode("iso-8859-1")
  finally:
  sqc.close()
  
  if __name__ == "__main__":
  nowPlaying()
  
--------------------


-- 
jhermann
------------------------------------------------------------------------
jhermann's Profile: http://forums.slimdevices.com/member.php?userid=15936
View this thread: http://forums.slimdevices.com/showthread.php?t=44293

_______________________________________________
plugins mailing list
[email protected]
http://lists.slimdevices.com/lists/listinfo/plugins

Reply via email to