#!/usr/bin/env python

# Copyright (c) 2004, Technische Universitaet Berlin
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# - Redistributions of source code must retain the above copyright notice,
#   this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
#   notice, this list of conditions and the following disclaimer in the
#   documentation and/or other materials provided with the distribution.
# - Neither the name of the Technische Universitaet Berlin nor the names
#   of its contributors may be used to endorse or promote products derived
#   from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
# OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


### Vlado Handziski (handzisk@tkn.tu-berlin.de)

""" Proof-of-concept for the hub power control functions """


try:
    import native.usb as usb
except ImportError:
    usb=None

TIMEOUT= 1000
USB_REQUEST_TYPE=0x23
USB_PORT_FEAT_RESET=4
USB_PORT_FEAT_POWER=8
CLEAR_FEATURE=1
SET_FEATURE=3
DEBUG=False

def usbhub_control_msg( busid, deviceid, bRequestType, bRequest, wValue, wIndex, pBuffer, timeout ):
    """ Send a generic control message to the hub """
    buses, devices=usb.UpdateLists()
    for bus in usb.AllBusses():
        if int( bus.name() )==busid:
            for device in bus.devices():
                if int( device.name() )==deviceid:
                    if DEBUG:
                        device.usb.usb_set_debug( 9 )
                    return device.usb.usb_control_msg( device.handle, bRequestType, bRequest, wValue, wIndex, pBuffer, timeout )
                    device.close()
                    
def usbhub_power_off( busid, deviceid, portid ):
    """ Turn-off the power of the portid port of the hub with the given busid and vendorid """
    buses, devices=usb.UpdateLists()
    for bus in usb.AllBusses():
        if int( bus.name() )==busid:
            for device in bus.devices():
                if int( device.name() )==deviceid:
                    if DEBUG:
                        device.usb.usb_set_debug( 9 )
                    device.usb.usb_control_msg( device.handle, USB_REQUEST_TYPE, CLEAR_FEATURE, USB_PORT_FEAT_POWER, portid, "", TIMEOUT )
                    device.close()
                   
def usbhub_power_on( busid, deviceid, portid ):
    """ Turn-off the power of the portid port of the hub with the given busid and vendorid """
  
    buses, devices=usb.UpdateLists()
    for bus in usb.AllBusses():
        if int( bus.name() )==busid:
           for device in bus.devices():
               if int( device.name() )==deviceid:
                   if DEBUG:
                      device.usb.usb_set_debug( 9 )
                   device.usb.usb_control_msg( device.handle, USB_REQUEST_TYPE, SET_FEATURE, USB_PORT_FEAT_POWER, portid, "", TIMEOUT )
                   device.close()

def usbhub_vendor_power_off( vendorid, productid, portid ):
    """ Turn-off the power of the portid port of the hub with the given vendorid and productid """
  
    buses, devices=usb.UpdateLists()
    for bus in usb.AllBusses():
        for device in bus.devices():
            if device.vendor()==vendorid and device.product()==productid:
                if DEBUG:
                    device.usb.usb_set_debug( 9 )
                device.usb.usb_control_msg( device.handle, USB_REQUEST_TYPE, CLEAR_FEATURE, USB_PORT_FEAT_POWER, portid, "", TIMEOUT )
                device.close()

 
def usbhub_vendor_power_on( vendorid, productid, portid ):
    """ Turn-on the power of the portid port of the hub with the given vendorid and productid """
    buses, devices=usb.UpdateLists()
    for bus in usb.AllBusses():
        for device in bus.devices():
            if device.vendor()==vendorid and device.product()==productid:
                if DEBUG:
                    device.usb.usb_set_debug( 9 )
                device.usb.usb_control_msg( device.handle, USB_REQUEST_TYPE, SET_FEATURE, USB_PORT_FEAT_POWER, portid, "", TIMEOUT )
                device.close()
                

def usage():
    print "Usage: hubcontrol.py [command] [--parameter=value]"
    print 
    print "Commands:"
    print 
    print "usbhub_power_on        'turn-on the power to the specified hub port'"
    print "usbhub_power_off       'turn-off the power to the specified hub port'"
    print   
    print "Parameters:"
    print
    print "--bus           'usb bus where the hub is attached (int)'"
    print "--dev           'usb device where the hub is attached (int)'"
    print "--port          'the port number of the port that needs to be controlled (int)'"
    print "  or:"
    print "--vendor_id     'vendor_id of the hub'"
    print "--product_id    'product_id of the hub'"
    print "--port          'the port number of the port that needs to be controlled (int)'"
    print
    print "Commands:"
    print
    print "usbhub_control_msg     'send generic control message to the hub'"
    print 
    print "Parameters:"
    print
    print "--bus           'usb bus where the hub is attached (int)'"
    print "--dev           'usb device where the hub is attached (int)'"
    print "--bRequestType  'control message request type (hex byte)'"
    print "--bRequest      'control message request (hex byte)'"
    print "--wValue        'control message value (hex word)'"
    print "--wIndex        'control message index (hex word)'"
    print "--sBuffer       'control message buffer size (hex word)'"
    print "--timeout       'control message timeout (int)'"
    print    
    print "Examples:"
    print
    print "Turn-off the power of port 1 on the hub attached to bus 002, device 003:"
    print "hubcontrol.py usbhub_power_off --bus=2 --dev=3 --port=1"
    print
    print "Turn-on the power of port 1 on the hub with vendor_id=0x0409, product_id=0x0058"
    print "hubcontrol.py usbhub_power_on --vendor_id=0x0409 --product_id=0x0058 --port=1"
    print
    print "Read the device descriptor of the hub attached to bus 001, device 002:"
    print "hubcontrol.py usbhub_control_msg --bus=1 --dev=2 --bRequestType=0xa0 --bRequest=0x06 --wValue=0x0000 \\"
    print "--wIndex=0x0000 --sBuffer=0x0009 --timeout=1000"
    sys.exit( 2 )

if __name__=="__main__":
  import sys
  import getopt
  try:
    opts, args = getopt.getopt( sys.argv[2:], "", ["bus=", "dev=", "port=", "vendor_id=", "product_id=", "bRequestType=", "bRequest=", "wValue=", "wIndex=", "sBuffer=", "timeout="] ) 
  except getopt.GetoptError:
       usage()
  nbus_set=ndev_set=nport_set=nvendor_id_set=nproduct_id_set=None
       
  for opt, value in opts:
   if opt=="--bus":
       nbus=int( value )
       nbus_set=True
   elif opt=="--dev":
       ndev=int( value )
       ndev_set=True
   elif opt=="--port":
       nport=int( value )
       nport_set=True
   elif opt=="--vendor_id":
       nvendor_id=int( value, 16 )
       nvendor_id_set=True
   elif opt=="--product_id":
       nproduct_id=int( value, 16 )
       nproduct_id_set=True
   elif opt=="--bRequestType":
       bRequestType=int( value, 16 )
       bRequestType_set=True    
   elif opt=="--bRequest":
       bRequest=int( value, 16 )
       bRequest_set=True
   elif opt=="--wValue":
       wValue=int( value, 16 )
       wValue_set=True
   elif opt=="--wIndex":
       wIndex=int( value, 16 )
       wIndex_set=True
   elif opt=="--sBuffer":
       sBuffer=int( value, 16 )
       pBuffer="".join( ["1"]*sBuffer )
       sBuffer_set=True
   elif opt=="--timeout":
       timeout=int( value )
       timeout_set=True
              

  if len( sys.argv )<2:
    usage()
    sys.exit( 2 )

  if sys.argv[1]=="usbhub_power_off":
    if nbus_set and ndev_set and nport_set:
        usbhub_power_off( nbus, ndev, nport )
    elif nvendor_id_set and nproduct_id_set and nport_set:
        usbhub_vendor_power_off( nvendor_id, nproduct_id, nport )
    else:
        usage() 
  elif sys.argv[1]=="usbhub_power_on":
    if nbus_set and ndev_set and nport_set:
        usbhub_power_on( nbus, ndev, nport )
    elif nvendor_id_set and nproduct_id_set and nport_set:
        usbhub_vendor_power_on( nvendor_id, nproduct_id, nport )
    else:
        usage()
  elif sys.argv[1]=="usbhub_control_msg":
    if nbus_set and ndev_set and bRequestType_set and bRequest_set and wValue_set and wIndex_set and sBuffer_set and timeout_set:
        result=usbhub_control_msg( nbus, ndev, bRequestType, bRequest, wValue, wIndex, pBuffer, timeout )
        print "result=%s   pBuffer=%s" %( result, ['%02x' % ord( x ) for x in pBuffer] )
    else:
        usage() 
  else:
    usage()
    