#!/usr/bin/python

# Script to control Sonos speapers from the command line.
# See https://github.com/SoCo/SoCo
# 2018-10-21 Initial release
# Issues: 
#    Better error message handling for unable to connect via IP

import sys, getopt
from soco import SoCo
from soco.discovery import by_name
import soco

import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)


def usage():
     print "Usage:", sys.argv[0], "[OPTION]..."
     print "Send commands to a Sonos speaker."
     print ""
     print "    -i, --ip-address=ADDRESS     Connect using IP address or hostname of Sonos speaker."
     print "    -n, --name=NAME              Connect using name of Sonos Speaker. CaSe counts."
     print "                                   Ignored if IP address option is specified."
     print "    -d, --discover               List Sonos speakers on the network."
     print "    --uri=URI                    Play a URI. URI example:"
     print "                                   \"x-rincon-mp3radio://http://server/mp3path\"."
     print "    --nowplaying                 Display current playback title."
     print "    --status                     Display current playback status."
     print "    --play                       Begin playback."
     print "    --pause                      Pause playback."
     print "    --previous                   Play previous item."
     print "    --next                       Play next item."
     return


def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "i:n:hd", ["help","play","pause","previous","next","ip-address=","name=","discover","nowplaying","uri=","status"])
    except getopt.GetoptError as err:
        # print help information and exit:
        print str(err)  # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    ipaddress = None
    playername = None
    verbose = False
    command = None
    uri = None
    for o, a in opts:
        if o == "-v":
            verbose = True
        elif o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-i", "--ip-address"):
            ipaddress = a
        elif o in ("-n", "--name"):
            playername = a
        elif o in ("--uri"):
            uri = a
        elif o in ("--play"):
            if command == None:
                command = "play"
        elif o in ("--pause"):
            if command == None:
                command = "pause"
        elif o in ("--previous"):
            if command == None:
                command = "previous"
        elif o in ("--next"):
            if command == None:
                command = "next"
        elif o in ("-d","--discover"):
            if command == None:
                command = "discover"
        elif o in ("--status"):
            if command == None:
                command = "status"
        elif o in ("--nowplaying"):
            if command == None:
                command = "nowplaying"
        else:
            assert False, "Unhandled Option"


# Discover command

    if command and command is "discover":
        for zone in soco.discover():
            print "Speakers found:"
            print(zone.player_name)
        sys.exit()



# Ready to connect

    if ipaddress or playername:
        #print "have address"
        if ipaddress:
            #print "doing via ip"
            sonos = SoCo(ipaddress)
        elif playername:
            #print "doing via name"
            sonos = by_name(playername)
    else:
       print "Speaker name or IP address must be supplied."
       print ""
       usage ();
#cant continue
       sys.exit()


    if  sonos:
        if uri:
            sonos.play_uri(uri)

        elif command:
            #print command
            if command is "play":
                sonos.play()
            elif command is "pause":
                sonos.pause()
            elif command is "previous":
                sonos.previous()
            elif command is "next":
                sonos.next()
            elif command is "nowplaying":
                track = sonos.get_current_track_info()
#                print track
                print track['title']
            elif command is "status":
                status = sonos.get_current_transport_info()
                print status['current_transport_state']
            else:
                print "Unsupported Command" 
        else:
            print "Nothing to do, please specify a command."
            print ""
            usage()

    else:
        print "Unable to connect. Check IP, hostname or speaker name."


if __name__ == "__main__":
    main()

