import usb
import time
import matplotlib.pyplot as plt
import numpy as np

dev = usb.core.find()   # get the device descriptor
#usb.util.dispose_resources(dev)
dev.reset()
#print dev.default_timeout
dev.timeout=100000
#reattach = False
#if dev.is_kernel_driver_active(0):
#   reattach = True
#   dev.detach_kernel_driver(0)

dev.set_configuration(1)
cfg = dev.get_active_configuration()            #returns active conf containing interface 0
interface_number = cfg[(0,0)].bInterfaceNumber          #returns 0
alternate_settting = usb.control.get_interface(dev, interface_number)         #returns 0
intf = usb.util.find_descriptor(cfg, bInterfaceNumber = interface_number, bAlternateSetting = alternate_settting)           #returns intf descriptor
ep_out = usb.util.find_descriptor(intf,custom_match = lambda e:usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_OUT)            #BULK OUT
ep_in = usb.util.find_descriptor(intf,custom_match = lambda e:usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)            #BULK IN

# first endpoint shortcut method of top
endpoint_in = dev[0][(0,0)][0]         #BULK IN 0x81
endpoint_out = dev[0][(0,0)][1]         #BULK OUT 0x2

#proper direction need to be followed in and out
ep_out.write('PM:DPower?\r\n')
time.sleep(1)
data=ep_in.read(0x81)  # always returns strings
print data
RxData=''.join([chr(x) for x in data])
print RxData

power=np.array([])

for i in range(31):
    ep_out.write('PM:DPower?\r\n')
    time.sleep(0.5)
    data=ep_in.read(0x81)
    print data
    RxData=''.join([chr(x) for x in data])
    print RxData
    d=float(RxData)

    power=np.append(power,d)

power=power*1e6 # convert power to uW
print (power)
x=np.arange(0,15.5,0.5)
plt.axis([0,15,0,30])
plt.plot(x,power)
plt.scatter(x,power)
plt.grid(True)
plt.xlabel('time(sec)')
plt.ylabel('optical power (uW)')
plt.title('optical power meter data')
plt.show()

# This is needed to release interface, otherwise attach_kernel_driver fails
# due to "Resource busy"
usb.util.dispose_resources(dev)

# It may raise USBError if there's e.g. no kernel driver loaded at all
#if reattach:
#   dev.attach_kernel_driver(0)