class SocketConnection(ConnectionType): def __init__(self, host, port, recvTimeout=50): self.logger = RamaLogger().getLogger() self.recvTimeout = recvTimeout self.host = host self.port = port '''OpenSocket''' self.Connect() @retry(Exception) def Connect(self): self.logger.info("Connecting to %s:%s" % (self.host,self.port)) self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.server.settimeout(self.recvTimeout) self.server.connect((self.host,self.port)) self.logger.info("Already connect to %s:%s" % (self.host,self.port)) def Send(self, cmd): self.logger.debug('Commnad: ' + str(cmd)) self.server.sendall(cmd) def Receive(self, response_length): response = self.server.recv(response_length) self.logger.info("Raw Data:") self.logger.info(response) return response def Disconnect(self): '''Disconnect to target device.''' self.server.close() self.server = None self.logger.info('Socket is Closed.')
class Keysight_34450A(DC_Client): def __init__(self, resource="USB0::10893::45848::MY58090059::0::INSTR", timeout=2): rm = visa.ResourceManager('@py') instr_list = rm.list_resources() resource = instr_list[0] super().__init__(resource, timeout) self.logger = RamaLogger().getLogger() self.logger.info("Keysight_34450A resoure = %s" % resource) def MeasureCurrent(self): return(self.instr.query("READ?"))
class BaseTestCase(metaclass=abc.ABCMeta): isConnectToDut = True def __init__(self): self.initParser() self.logger = RamaLogger().getLogger() def initParser(self): self.parser = ArgumentParser() self.loadCommonArgs() self.loadCriteria() self.args = self.parser.parse_args() def loadCommonArgs(self): self.parser.add_argument("-v", "--verbose", action='store_true', help="verbose mode") def loadCriteria(self): pass def setUp(self): # Create socket connection self.logger.info('------------------ Test Start ------------------') if self.isConnectToDut: self.connectToDut() def test(self): self.setUp() result = self._runTest() self.tearDown() return result def connectToDut(self): ip = Config.get("DUT", "IP").replace("'", "") port = Config.getint('DUT', 'PORT') conn = SocketConnection(ip, port) # conn = SerialConnection() self.stpClient = STPClient(conn) @abc.abstractmethod def _runTest(self): pass def tearDown(self): if hasattr(self, "stpClient") and self.stpClient is not None: self.stpClient.Disconnect() self.logger.info('----------------- Test Finish! -----------------')
class Keysight_E36103A(DC_Client): def __init__(self, resource="TCPIP0::192.168.10.2::inst0::INSTR", timeout=2): super().__init__(resource, timeout) self.logger = RamaLogger().getLogger() def SetVoltOutput(self, volt="3.6"): self.logger.info("Set power to DC %s" % volt) self.instr.write("SOUR:VOLT %s" % volt) self.instr.write("OUTP:STAT ON") def DisableStat(self): self.instr.write("OUTP:STAT OFF") def MeasureCurrent(self): return(self.instr.query("MEAS:CURR:DC?"))
class RF_Client: def __init__(self, host, port, timeout=2): self.logger = RamaLogger().getLogger() self.host = host self.port = port self.session = visa.ResourceManager('@py') self.Connect(timeout * 1000) # second to millisecond def Connect(self, timeout): '''Connect to target device.''' self.instr = self.session.open_resource("TCPIP::%s::%s::SOCKET" % (self.host, str(self.port)), read_termination='\n', write_termination='\n') self.instr.timeout = timeout self.logger.info("Already connect to %s:%s" % (self.host, self.port)) def Disconnect(self): '''Disconnect to target device.''' self.instr.close()
class SerialConnection(ConnectionType): def __init__(self, device='/dev/ttyACM0', baudRate=115200, recvTimeout=20): self.logger = RamaLogger().getLogger() self.device = device self.baudRate = baudRate self.recvTimeout = recvTimeout self.Connect() def Connect(self): self.logger.info("Connecting to %s" % self.device) self.server = serial.Serial(self.device, self.baudRate, timeout=self.recvTimeout) self.logger.info("Already connect to %s" % self.device) def Send(self, cmd): self.logger.debug('Commnad: ' + str(cmd)) self.server.write(cmd) def Receive(self, response_length): response = self.server.read(response_length) return response def Disconnect(self): '''Disconnect to target device.''' self.server.close() self.server = None self.logger.info('Serial connection is closed.')
class DC_Client: def __init__(self, resource, timeout=2): self.logger = RamaLogger().getLogger() self.resource = resource self.session = visa.ResourceManager('@py') self.Connect(timeout * 1000) # second to millisecond def Connect(self, timeout): '''Connect to target device.''' try: self.instr = self.session.open_resource(self.resource, read_termination='\n', write_termination='\n') self.instr.timeout = timeout self.logger.info("Already connect to %s" % (self.resource)) except Exception as e: self.logger.error_code('IN10') self.logger.error_msg("Connect to {0} failed".format( self.resource)) def Disconnect(self): '''Disconnect to target device.''' self.instr.close()
class Anritsu_MT8870A(RF_Client): def __init__(self, host='192.168.1.1', port=56001, timeout=2): super().__init__(host, port, timeout) self.logger = RamaLogger().getLogger() self.InitDevice() def InitDevice(self): self.instr.write("*CLS") self.instr.query("*ESR?") self.instr.write("SYST:LANG SCPI") self.instr.query("*OPC?") self.instr.query("*ESR?") self.instr.query("SYST:ERR:COUN?") self.instr.query("*ESR?") self.instr.query("SYST:ERR:ALL?") self.instr.query("*ESR?") self.instr.write("INST:SEL SRW") self.instr.query("*OPC?") self.instr.query("*ESR?") self.instr.query("SYST:VERS?") self.instr.query("SYST:INF:MAIN:DEV:ID?") # self.instr.write("CALC:CAL:BAND:STAR:TEMP 2") self.instr.query("*OPC?") self.instr.query("*ESR?") self.instr.query("*OPC?") self.instr.query("*IDN?") self.instr.write("CALC:EXTL:TABL:SETT 1") self.instr.write("CALC:EXTL:TABL:DEL") self.instr.write( "CALC:EXTL:TABL:VAL:ALL 880.03MHZ, 20, 20, 20, 20, 20, \ 20, 20, 20") self.instr.write("EXTL:TABL:SWIT ON") def DisableStat(self): self.instr.write("SOUR:GPRF:GEN:STAT OFF") def SendGPS(self): self.instr.write("SYST:LANG SCPI") self.instr.write("CALC:EXTL:TABL:SETT 1") self.instr.write("ROUT:PORT:CONN:DIR PORT1,PORT2") self.instr.write("SOUR:GPRF:GEN:MODE NORMAL") self.instr.query("SOUR:GPRF:GEN:ARB:FILE:LOAD? 'MV887100A_GPS_0002'") self.instr.write("SOUR:GPRF:GEN:ARB:FILE:LOAD 'MV887100A_GPS_0002'") while True: # need to polling until the response is 0 res = self.instr.query("SOUR:GPRF:GEN:ARB:FILE:LOAD:STAT?") if int(res) == 0: break # Set RF output frequency self.instr.write("SOUR:GPRF:GEN:RFS:FREQ 1575.42MHZ") # Set RF output level self.instr.write("SOUR:GPRF:GEN:RFS:LEV -100") self.instr.write("SOUR:GPRF:GEN:BBM ARB") self.instr.write("SOUR:GPRF:GEN:ARB:NOIS:STAT OFF") self.instr.write("SOUR:GPRF:GEN:RFS:DM:POL NORMAL") self.instr.write("SOUR:GPRF:GEN:ARB:WAV:SSW FIXED,0") self.instr.write("SOUR:GPRF:GEN:ARB:WAV:SYNC:STAR:CANC") self.instr.write( "SOUR:GPRF:GEN:ARB:WAV:PATT:SEL 'MV887100A_GPS_0002', \ 1, 1") self.instr.write("SOUR:GPRF:GEN:STAT ON") self.logger.info('Send GPS signal.') def ReadRadioTx(self): self.instr.write("SYST:LANG NAT") self.instr.write("LOSSTBL 1") self.instr.write("SYSSEL Cellular") self.instr.write("STDSEL COMMON") self.instr.write("PORT PORT1,PORT3") self.instr.write("ULFREQ 840MHZ") self.instr.write("ILVL 22") self.instr.write("SPMSPAN 1MHZ") self.instr.write("SPMRBW 10KHZ") self.instr.write("SPMDETECT RMS") self.instr.write("SPMSTORAGEMODE AVG") self.instr.write("SPMSTORAGECOUNT 10") self.instr.write("SPMTIME 1MS") self.instr.write("SPMPMBW 1MHZ") self.instr.write("SPMTGSRC FREERUN") # Start auto level measurement and query status self.instr.write("SNGLS") while True: # need to polling until response is 0 res = self.instr.query("MSTAT?", time.sleep(10)) if int(res) == 0: break # Query measurement results return float(self.instr.query("SPMPWR?")) def EnableRadioRx(self): self.instr.write("SYST:LANG SCPI") self.instr.write( "ROUT:PORT:CONN:DIR PORT%d,PORT%d" % (MT8870A_Config.getint('RX_Measurement', 'Input_Port'), MT8870A_Config.getint('RX_Measurement', 'Output_Port'))) self.instr.write("SOUR:GPRF:GEN:MODE NORMAL") self.instr.write("SOUR:GPRF:GEN:BBM CW") self.instr.write("SOUR:GPRF:GEN:RFS:FREQ %s" % MT8870A_Config.get('RX_Measurement', 'Frequency')) self.instr.write("SOUR:GPRF:GEN:RFS:LEV %d" % MT8870A_Config.getint('RX_Measurement', 'Level')) self.instr.write("SOUR:GPRF:GEN:STAT ON")
class ParentCommand: def __init__(self): self.logger = RamaLogger().getLogger() # SendCommand---------------------------------------------------------- # Command Header # Unused (32 bits) Internal use only, set to zeroes self.SendUnused = 0 # The Version is 1 self.SendVersion = 1 # Default self.SendGroupid = 2 self.SendCmdid = 3 self.SendPaylen = 4 # Command pack format, depend on Command Payload self.SendCmdHeaderFormat = "<5I" self.SendCmdPayloadFormat = "" self.SendCommand = "" # ReceiveResponse---------------------------------------------------------- # Response unpack format, depend on command-specific response payload self.ResponsePayloadFormat = "" self.ResponseHeaderFormat = "<5II1024s" # Default self.RecvUnused = 0 self.RecvGroupid = 0 self.RecvCmdid = 0 self.RecvVersion = 0 self.RecvPaylen = 0 self.ResultCode = 0 self.ResultMsg = "" ####################################################### def PackCommand(self): # Pack Command Header to SendCommand. self.SendCommand = pack(self.SendCmdHeaderFormat, self.SendUnused, self.SendCmdid, self.SendGroupid, self.SendVersion, self.SendPaylen) return self.SendCommand def UnpackResponse(self, Response): # Unpack Response Header and store in every field. self.RecvUnused, self.RecvCmdid,\ self.RecvGroupid, self.RecvVersion,\ self.RecvPaylen, self.ResultCode,\ self.ResultMsg = unpack_from( self.ResponseHeaderFormat, Response, offset=0) self.ResultMsg = self.ResultMsg.decode().rstrip('\x00') return self.RecvUnused, self.RecvCmdid, self.RecvGroupid, self.RecvVersion,\ self.RecvPaylen def ReturnCheck(self): return self.ResultCode, self.ResultMsg def STDOut(self): # Print out every fields individually. # Note: Need to decode content, if the type of field is char as ResultMsg. self.logger.debug("UNUSED: " + str(self.RecvUnused)) self.logger.debug("CMDID: " + str(self.RecvCmdid)) self.logger.debug("GRPID: " + str(self.RecvGroupid)) self.logger.debug("VSION: " + str(self.RecvVersion)) self.logger.debug("GRPID: " + str(self.RecvGroupid)) self.logger.debug("PAYLEN: " + str(self.RecvPaylen)) self.logger.info("ResultCode: " + str(self.ResultCode)) self.logger.info("ResultMsg: " + repr(self.ResultMsg))
class SSHConnection(ConnectionType): def __init__(self, host, username, password): self.logger = RamaLogger().getLogger() self.host_stingray = host self.username_stingray = username self.password_stingray = password self.timeout = Config.get('SSHClient', 'timeout') '''Connect SSH''' self.Connect() @retry(Exception) def Connect(self): "Login to the remote server" self.logger.info('Connectingt to %s:%s' % (self.host, self.port)) try: self.client = paramiko.SSHClient() self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.host_stringray, port=22, username=self.username_stingray, password=self.password_stingray, timeout=self.timeout, allow_agent=False, look_for_keys=False) self.logger.info("Connected to the server", self.host) except paramiko.AuthenticationException: self.logger.warning( "Authentication failed, please verify your credentials") except paramiko.SSHException as sshException: self.logger.error("Could not establish SSH connection: %s" % sshException) except socket.timeout as e: self.logger.error("Connection timed out: %s" % e) except Exception as e: self.logger.error("Exception in connecting to the server: %s" % e) def Send(self, command): """Execute a command on the remote host.Return a tuple containing an integer status and a two strings, the first containing stdout and the second containing stderr from the command.""" self.logger.info("Executing command --> {}".format(command)) try: stdin, stdout, stderr = self.client.exec_command(command, timeout=10) self.ssh_output = stdout.read() self.ssh_error = stderr.read() except paramiko.SSHException: self.logger.debug("Failed to execute the command!", command) def Receive(self): '''Receive result from remote server''' self.logger.info(self.ssh_output) self.logger.info(self.ssh_error) return self.ssh_output, self.ssh_error def Disconnect(self): '''Close SSH client''' self.client.close() self.client = None self.logger.info('SSH is Closed.')