from ctypes import *
import os
import time
import array as arr

class Vaunix_Attn:
    def __init__(self, name="VaunixAPI", port=''):
        self.vnx = cdll.LoadLibrary(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'libLDAhid.so'))
        self.vnx.fnLDA_Init()
        self.vnx.fnLDA_SetTestMode(False)
        devices_num = self.get_devices_number()

        DeviceIDArray = c_int * devices_num
        self.devices_list = DeviceIDArray()
        self.mdfctn_pool = []

        # fill the array with the ID's of connected attenuators
        self.vnx.fnLDA_GetDevInfo(self.devices_list)

    def get_devices_list(self):
        return self.devices_list

    def get_devices_number(self):
        return self.vnx.fnLDA_GetNumDevices()

    def get_serial_number(self, id):
        id = int(id)
        return self.vnx.fnLDA_GetSerialNumber(id)

    def set_attenuation(self, device_id, attenuation):
#        set_lock.acquire()
        try:
            device_id = int(device_id)
            if device_id > int(self.get_devices_number()):
                return False
            self.vnx.fnLDA_InitDevice(device_id)
            self.vnx.fnLDA_SetAttenuation(device_id, int(attenuation)*20)
            self.vnx.fnLDA_CloseDevice(device_id)
        finally:
#            set_lock.release()
            print("Release Set Lock")
        return True

    def get_attenuation(self, device_id):
#        set_lock.acquire()
        try:
            device_id = int(device_id)
            self.vnx.fnLDA_InitDevice(device_id)
            curr_attn = self.vnx.fnLDA_GetAttenuation(device_id)
            self.vnx.fnLDA_CloseDevice(device_id)
        finally:
#            set_lock.release()
            print("Release Get Lock")
        return curr_attn / 20
        
if __name__ == '__main__':
    import sys
    attobj = Vaunix_Attn()
    print ("LDA Devices #",attobj.get_devices_number)
    devicelist = arr.array('i', attobj.get_devices_list())
    print ("Device List:", devicelist)
    print ("Serial #:", attobj.get_serial_number(devicelist[0]))
    print ("Current Atteunation:", attobj.get_attenuation(devicelist[0]))
    for index in range(0,20):
        print ("Set Atteunation:", attobj.set_attenuation(devicelist[0], index))
        time.sleep(1)
        print ("Current Atteunation:", attobj.get_attenuation(devicelist[0]))
        time.sleep(6)
    