Your Digital Media Has Never Looked So Good

 
RiJo
Topic Author
Posts: 13
Joined: Fri Mar 23, 2007 7:54 am
Location: Göteborg, Sweden
Contact:

[python] Simple console script

Fri May 08, 2009 1:49 pm

I've started learning python and sockets and saw the oppertunity to create a simple console controller for my M1001. As I said, I'm not good at python so far, and if you have improvements of the code please post it in this thread.

My main usage of this script is Conky (http://conky.sourceforge.net/)

Examples of usage:
# ./soundbridge.py 'state'
Play
# ./soundbridge 'song' '[%k] %a - %t'
[Vapen och ammunition] Kent - Socker
# ./soundbridge.py 'key' 'pause'
OK


I will try to update this thread as the script improves:

soundbridge.py:
#!/usr/bin/python

import sys
import socket
import re

HOST =            'xxx.xxx.xxx.xxx'
PORT =            5555
TIMEOUT =         0.05

MSG_NO_CONNECTION =      'Not connected'
MSG_EARLY_TIMEOUT =      'Early timeout'
MSG_UNKNOWN_COMMAND =      'Unknown command'
MSG_MISSING_PARAMETER =      'Missing parameter'

SYMBOL_ARTIST =         '%a'
SYMBOL_TITLE =         '%t'
SYMBOL_ALBUM =         '%k'
SYMBOL_GENRE =         '%g'
SYMBOL_COMPOSER =      '%c'
SYMBOL_TOTAL_TIME =      '%x'
SYMBOL_ELAPSED_TIME =      '%z'
SYMBOL_ELAPSED_PERCENT =   '%p'
SYMBOL_LENGTH =         '%l'
SYMBOL_FORMAT =         '%f'
SYMBOL_STATUS =         '%s'
SYMBOL_SONGFORMAT =      '%u'

arguments = sys.argv
parameter = MSG_UNKNOWN_COMMAND
if len( arguments ) > 1:
   command = arguments[1]
   
   if command == 'key' or command == 'song':
      if len( arguments ) > 2:
         parameter = arguments[2]
      else:
         command = 'foo'
         parameter = MSG_MISSING_PARAMETER
else:
   command = 'song'
   parameter = '[%k] %a - %t'
   
def execute( command ):
   s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
   s.settimeout( TIMEOUT )   
   try:
      s.connect(( HOST, PORT ))
   except socket.error, e:
      return MSG_NO_CONNECTION

   data = ''
   try:
      s.send( command + chr(13) + chr(10) )

      while 1:
         temp = s.recv( 1024 )
         data += temp
         data = data.replace( command.split( ' ' )[0] + ': ', '' ).replace( 'roku: ready', '' )
   except socket.error ,e:
      # Timeout for reading data
      s.close()
      if len( data ) > 0:
         return data.strip()
      else:
         return MSG_EARLY_TIMEOUT

def containsErrors( text ):
   if text == MSG_NO_CONNECTION: return True
   if text == MSG_EARLY_TIMEOUT: return True
   return False

def songInfo( pattern ):
   ARTIST = 'artist: '
   TITLE = 'title: '
   ALBUM = 'album: '
   GENRE = 'genre: '
   COMPOSER = 'composer: '
   LENGTH = 'length: '
   FORMAT = 'format: '
   STATUS = 'status: '
   SONGFORMAT = 'songFormat: '

   result = pattern
   currentSong = execute( 'GetCurrentSongInfo' )
   if containsErrors( currentSong ): return currentSong
      
   transportState = execute( 'GetTransportState' )
   if not transportState == 'Play' and not transportState == 'Pause': return 'No song playing'
   
   if SYMBOL_TOTAL_TIME in pattern or SYMBOL_ELAPSED_PERCENT in pattern:
      totalTime = execute( 'GetTotalTime' )
      if containsErrors( totalTime ): return totalTime
      result = result.replace( SYMBOL_TOTAL_TIME, totalTime )
      
   if SYMBOL_ELAPSED_TIME in pattern or SYMBOL_ELAPSED_PERCENT in pattern:
      elapsedTime = execute( 'GetElapsedTime' )
      if containsErrors( elapsedTime ): return elapsedTime
      result = result.replace( SYMBOL_ELAPSED_TIME, elapsedTime )
      
   if SYMBOL_ELAPSED_PERCENT in pattern:
      elapsed  = float( toSeconds( elapsedTime ) )
      total = float( toSeconds( totalTime ) )
      if total > 0 and total > elapsed:
         elapsedPercent = round( ( elapsed / total ) * 100, 1 )
      else:
         elapsedPercent = 0
      result = result.replace( SYMBOL_ELAPSED_PERCENT, str(elapsedPercent) + '%' )
      
   for item in currentSong.split( '\r\n' ):
      if ARTIST in item:
         result = result.replace( SYMBOL_ARTIST, item.replace( ARTIST, '' ) )
      if TITLE in item:
         result = result.replace( SYMBOL_TITLE, item.replace( TITLE, '' ) )
      if ALBUM in item:
         result = result.replace( SYMBOL_ALBUM, item.replace( ALBUM, '' ) )
      if GENRE in item:
         result = result.replace( SYMBOL_GENRE, item.replace( GENRE, '' ) )
      if COMPOSER in item:
         result = result.replace( SYMBOL_COMPOSER, item.replace( COMPOSER, '' ) )
      if LENGTH in item:
         result = result.replace( SYMBOL_LENGTH, item.replace( LENGTH, '' ) )
      if FORMAT in item:
         result = result.replace( SYMBOL_FORMAT, item.replace( FORMAT, '' ) )
      if STATUS in item:
         result = result.replace( SYMBOL_STATUS, item.replace( STATUS, '' ) )
      if SONGFORMAT in item:
         result = result.replace( SYMBOL_SONGFORMAT, item.replace( SONGFORMAT, '' ) )
         
   result = re.sub( '%[a-z]', 'N/A', result ) # Remove unreplaced symbols
   return result
   
def toSeconds( time ):
   if re.match( '[0-9]{1}:[0-9]{2}:[0-9]{2}', time ) == None:
      return -1
   else:
      hours = int( time[0] )
      minutes = int( time[2:4] )
      seconds = int( time[5:7] )
      return (hours*3600) + (minutes*60) + seconds
      
def displayData():
   data = execute( 'GetDisplayData' )
   if containsErrors( data ): return data
   
   startBytes = data.find( 'bytes: ' ) + len( 'bytes: ' )
   endBytes = data.find( '\r\n' )
   
   startData = endBytes + 2
   endData = len( data )
   return data[startBytes:endBytes], data[startData:endData]
   

if command == 'state':
   print execute( 'GetTransportState' )
elif command == 'server':
   print execute( 'GetConnectedServer' )
elif command == 'language':
   print execute( 'GetLanguage' )
elif command == 'volume':
   print execute( 'GetVolume' )
elif command == 'display':
   print displayData()
elif command == 'key':
   print execute( "IrDispatchCommand CK_" + parameter.upper() )
elif command == 'song':
   print songInfo( parameter )
else:
   print 'Command error: ' + parameter
:: RiJo ::..
:: Roku M1001 ::..

Who is online

Users browsing this forum: No registered users and 2 guests