def run_from_apbridge(svc, host, test, size, iteration, verbose, apb): csv_path = 'apb_{}_{}_{}.csv'.format(test, size, iteration) # gbl is using a slightly different name apb_test_cmd = APB_CMD.format(test.replace('transfer', 'xfer'), size, iteration) info(csv_path, test, size, apb_test_cmd) svcfd = fdpexpect.fdspawn(svc.fd, timeout=5) f = fdpexpect.fdspawn(apb.fd, timeout=5) info('Create CSV file ({})'.format(csv_path)) with open(csv_path, "w") as fd: count = 1 try: for pwrm, cmds in PWRM_TO_CMDS: info('\nTest ({}) - {}\n'.format(count, pwrm)) for cmd in cmds: exec_svc_cmd(svcfd, cmd) if verbose: # insert the test name into the CSV file # TODO: add a new column into the CSV instead of new row call(['ssh', ssh_host, 'echo "{}" >> {}'.format(pwrm, csv_path)]) fd.write('{},{},{},{}\n'.format( strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('{},{},{},{}\n'.format( strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('{},{},{},{}\n'.format( strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) count += 1 except KeyboardInterrupt: info('\nKeyboardInterrupt')
def get_connection(timeout, init_dtr=None, *args, **kwargs): if init_dtr is not None: kwargs['dsrdtr'] = True try: conn = serial.Serial(*args, **kwargs) except serial.SerialException as e: raise HostError(e.message) if init_dtr is not None: conn.setDTR(init_dtr) conn.nonblocking() conn.flushOutput() target = fdpexpect.fdspawn(conn.fileno(), timeout=timeout) target.logfile_read = PexpectLogger('read') target.logfile_send = PexpectLogger('send') # Monkey-patching sendline to introduce a short delay after # chacters are sent to the serial. If two sendline s are issued # one after another the second one might start putting characters # into the serial device before the first one has finished, causing # corruption. The delay prevents that. tsln = target.sendline def sendline(x): tsln(x) time.sleep(0.1) target.sendline = sendline return target, conn
def __init_soc(self, nodeid): """ Initialize a System-on-a-chip node connected via UART. """ import fdpexpect serialPort = '/dev/ttyUSB%d' % ((nodeid - 1) * 2) self.pexpect = fdpexpect.fdspawn( os.open(serialPort, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY))
def autosync(self): '''use AT&UPDATE to put modem in update mode''' import fdpexpect, time ser = fdpexpect.fdspawn(self.port.fileno(), logfile=sys.stdout) self.port.setBaudrate(self.atbaudrate) print("Trying autosync") ser.send('\r\n') time.sleep(1.0) ser.send('+++') try: ser.expect('OK', timeout=1.1) except fdpexpect.TIMEOUT: # may already be in AT mode pass for i in range(5): ser.send('\r\nATI\r\n') try: ser.expect('SiK .* on', timeout=0.5) ser.send('\r\n') time.sleep(0.2) ser.send('AT&UPDATE\r\n') time.sleep(0.7) if self.atbaudrate != 115200: self.port.setBaudrate(115200) return True except fdpexpect.TIMEOUT: continue self.port.setBaudrate(115200) return False
def set_speed(device): '''set some registers''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiKening .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return for cmd in opts.cmd: ser.send('%s\r\n' % cmd) ser.expect('OK') if opts.write: ser.send('AT&W\r\n') ser.expect('OK') if opts.reset: ser.send('ATZ\r\n') else: ser.send('ATO\r\n') ser.expect('OK') time.sleep(1) ser.read_nonblocking(300) port.close()
def __init__(self, device, baudrate=57600, debug=False, dsrdtr=False, rtscts=False, xonxoff=False, parity=serial.PARITY_NONE): # Initialize object data members self.is_command = False # Track if we've entered command mode self.is_remote = False # Track if operating on remote radio self.read_timeout = 5 # Max time to wait for data logfile = None if debug: logfile = sys.stdout # Initialize the serial connection # Note: we pass the buck on raised exceptions self.port = serial.Serial(device, baudrate=baudrate, timeout=0, dsrdtr=dsrdtr, rtscts=rtscts, xonxoff=xonxoff, parity=parity) self.ser = fdpexpect.fdspawn(self.port.fileno(), logfile=logfile)
def getIpRouterMesh(port, baudrate): IpRouter = "" try: ser = serial.Serial(port, baudrate) except IOError: return IpRouter if ser.isOpen(): reader = fdpexpect.fdspawn(ser, 'wb', timeout=90) reader.send("\x03") reader.send("ifconfig\x0D") try: reader.expect("br-lan") reader.expect("inet addr:") contentLine = reader.readline() ipFound = contentLine.split("Bcast", 1)[0] ipFound = ipFound.replace(" ", "") IpRouter = ipFound # regex = re.compile(r"\d+.\d+.\d+.\d+") #Ne marcche pas en attendant j ai remplace par un split #print ("VALEUR DE REGEX ="),regex #ipFound = regex.match(contentLine) #listMeshIP.append(ipFound) # Add IP except pexpect.TIMEOUT: success = False except pexpect.EOF: print("Unexpected EOF reached. Aborting.") return False reader.close() # ser.close() # close port else: print("Serial port not open" + ser.name) return IpRouter
def __init__(self): self.hbc = None self.hbcsp = None self.pir_test_normal_count = 5 self.mag_test_normal_count = 3 self.water_test_normal_count = 4 self.test_alarm_count = 4 self.water_test_alarm_count = 3 self.test_disengage_count = 2 self.test_interrupt_count = 2 self.water_alarm_ack_count = 2 self.water_ack_count = 2 self.pir_test_normal_case = [] self.mag_test_normal_case = [] self.water_test_alarm_case = [] self.water_test_alarmack_case = [] self.water_test_ack_case = [] self.test_alarm_case = [] self.test_alarm_case = [] self.test_disengage_case = [] self.test_interrupt_case = [] self.fd = open("console.log", 'w') self.hbc = serial.Serial("/dev/hub_console", 19200) self.hbcsp = fdpexpect.fdspawn(self.hbc) self.hbcsp.logfile = self.fd self.initTestNormalCase() self.initTestAlarmCase() self.initTestAlarmAckCase() self.initTestDisengageCase() self.initTestInterruptCase() self.initTestAckCase()
def collect_data(self, machine): fh = machine.get_output() self.console = fdpexpect.fdspawn(fh, timeout=self.test_timeout) self.console.logfile = tempfile.NamedTemporaryFile() while self.boot_attempts < MAX_BOOT_ATTEMPTS: index = self.console.expect(["Barrelfish CPU driver starting", pexpect.TIMEOUT, pexpect.EOF], timeout=self.boot_timeout) if index == 0: self.boot_phase = False break if index == 1: self.console.logfile.write(BOOT_TIMEOUT_LINE_RETRY) self.reboot(machine) if index == 2: self.console.logfile.write(BOOT_TIMEOUT_LINE_FAIL) if not self.boot_phase: machine.force_write(self.console) try: self.interact() except OSError, e: self.console.logfile.seek(0) print self.console.logfile.readlines() raise e
def show_regs(device): '''show S registers''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiKening .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('ATI5\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATI6\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATI7\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATO\r\n') print("") time.sleep(1) port.close()
def autosync(self): '''use AT&UPDATE to put modem in update mode''' import fdpexpect, time, pexpect ser = fdpexpect.fdspawn(self.port.fileno(), logfile=sys.stdout) if self.atbaudrate != 115200: self.port.setBaudrate(self.atbaudrate) print("Trying autosync") ser.send('\r\n') time.sleep(1.0) ser.send('+++') try: ser.expect('OK', timeout=1.1) except pexpect.TIMEOUT: # may already be in AT mode pass for i in range(5): ser.send('\r\nATI\r\n') try: ser.expect('SiK .* on', timeout=0.5) ser.send('\r\n') time.sleep(0.2) ser.send('AT&UPDATE\r\n') time.sleep(0.7) if self.atbaudrate != 115200: self.port.setBaudrate(115200) return True except fdpexpect.TIMEOUT: continue if self.atbaudrate != 115200: self.port.setBaudrate(115200) return False
def set_speed(device): '''set air speed''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiKening .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('ATS2=%u\r\n' % opts.speed) ser.expect('OK') ser.send('AT&W\r\n') ser.expect('OK') ser.send('ATI5\r\n') time.sleep(0.2) ser.read_nonblocking(100) ser.send('ATZ\r\n') time.sleep(1) port.close()
def set_speed(device): '''set air speed''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK','SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('ATS2=%u\r\n' % opts.speed) ser.expect('OK') ser.send('AT&W\r\n') ser.expect('OK') ser.send('ATI5\r\n') time.sleep(0.2) ser.read_nonblocking(100) ser.send('ATZ\r\n') time.sleep(1) port.close()
def collect_data(self, machine): fh = machine.get_output() self.console = fdpexpect.fdspawn(fh, timeout=self.test_timeout) self.console.logfile = tempfile.NamedTemporaryFile() while self.boot_attempts < MAX_BOOT_ATTEMPTS: index = self.console.expect(["Barrelfish CPU driver starting", pexpect.TIMEOUT, pexpect.EOF], timeout=self.boot_timeout) if index == 0: self.boot_phase = False break if index == 1: self.console.logfile.write(BOOT_TIMEOUT_LINE_RETRY) self.reboot(machine) if index == 2: self.console.logfile.write(BOOT_TIMEOUT_LINE_FAIL) if not self.boot_phase: machine.force_write(self.console) try: self.interact() except (pexpect.TIMEOUT, OSError), e: self.console.logfile.seek(0) print "Interaction timed out:" print ''.join(self.console.logfile.readlines()) raise e
def load(device, baud, program): """ Load a bitlash program onto the Arduino. """ serialport = serial.Serial(device, baud, timeout=0) c = fdpexpect.fdspawn(serialport.fd) #c.logfile_read = sys.stdout # synch with the command prompt c.sendline('') waitprompt(c) # do stuff if(program.find('\n')>=0): #program is many lines text = program.split('\n') for line in text: line = line.strip() print(line) if (len(line) > 0) and (line[0] != '#'): c.sendline(line) waitprompt(c) print("waiting for prompt after twinkle") else: #program is one line if (len(program) > 0) and (program[0] != '#'): c.sendline(program) waitprompt(c) c.close() print("Done") return None
def show_regs(device): '''show S registers''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK','SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('ATI5\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATI6\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATI7\r\n') time.sleep(0.2) ser.read_nonblocking(300) ser.send('ATO\r\n') print("") time.sleep(1) port.close()
def run_from_apbridge(svc, host, test, size, iteration, verbose, apb): csv_path = 'apb_{}_{}_{}.csv'.format(test, size, iteration) # gbl is using a slightly different name apb_test_cmd = APB_CMD.format(test.replace('transfer', 'xfer'), size, iteration) info(csv_path, test, size, apb_test_cmd) svcfd = fdpexpect.fdspawn(svc.fd, timeout=5) f = fdpexpect.fdspawn(apb.fd, timeout=5) info('Create CSV file ({})'.format(csv_path)) with open(csv_path, "w") as fd: count = 1 try: for pwrm, cmds in PWRM_TO_CMDS: info('\nTest ({}) - {}\n'.format(count, pwrm)) for cmd in cmds: exec_svc_cmd(svcfd, cmd) if verbose: # insert the test name into the CSV file # TODO: add a new column into the CSV instead of new row call([ 'ssh', ssh_host, 'echo "{}" >> {}'.format(pwrm, csv_path) ]) fd.write('{},{},{},{}\n'.format(strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('{},{},{},{}\n'.format(strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('{},{},{},{}\n'.format(strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) count += 1 except KeyboardInterrupt: info('\nKeyboardInterrupt')
def do_open(self, s): """Open the serial port, e.g.:\nopen /dev/tty.usbserial-A3000PrP""" self.serial.port = s self.serial.baudrate = 9600 self.serial.open() print('Opening serial port %s' % s) # start pexpect self.ffd=fdpexpect.fdspawn(self.serial.fd)
def _kick_user(self, fd, cname): child = fdpexpect.fdspawn(fd) child.expect('>INFO:OpenVPN') child.sendline('kill %s' %cname) index = child.expect(['SUCCESS', 'ERROR']) child.sendline('exit') child.close() return index == 0
def test_maxread (self): fd = os.open ('TESTDATA.txt', os.O_RDONLY) s = fdpexpect.fdspawn (fd) s.maxread = 100 s.expect('2') s.expect ('This is the end of test data:') s.expect (pexpect.EOF) assert s.before == ' END\n'
def test_maxread(): fd = os.open(file, os.O_RDONLY) s = fdpexpect.fdspawn(fd) s.maxread = 100 s.expect('2') s.expect('This is the end of test data:') s.expect(pexpect.EOF) assert s.before == ' END\n'
def connect(self, unused_credential): timeout = self.timeouts.connect try: self._c = telnetlib.Telnet(str(self.address), self.port, timeout) self._expect = fdpexpect.fdspawn(self._c.fileno()) except socket.error, e: raise notch.agent.errors.ConnectError( 'Error connecting to %s. %s: %s' % (str(self.address), e.__class__.__name__, str(e)))
def _get_status_text(self, fd): child = fdpexpect.fdspawn(fd) child.expect('>INFO:OpenVPN') child.sendline('status') child.expect('END') data = child.before.strip() child.sendline('exit') child.close() return data
def initialize_serial_device(self, serial_device_port=None, file_log=None): """Initialize a serial console device with the device under test Args: serial_device_port: device file on the host computer under /dev/ that the serial device is attached to (i.e. ttyUSB1) file_log: file to log serial console messages Returns: nothing Raises: nothing """ self.serial_device = os.open(serial_device_port, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY) if file_log: self.child = fdpexpect.fdspawn(self.serial_device, logfile=file_log) else: self.child = fdpexpect.fdspawn(self.serial_device)
def __init__(self, port="/dev/ttyUSB0", baudrate=115200, prompt="[root@localhost]# "): self.serial = serial.Serial(port, baudrate, timeout=1) self.serial.flushInput() self.serial.flushOutput() self.ffd = fdpexpect.fdspawn(self.serial.fd, timeout=60) self.prompt = prompt # assume that because we flushed, we are at a bare prompt CommBase.__init__(self)
def Upload(image, device, burn) : print "Connecting to serial device...", fd = os.open(device, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY) print fd m = fdpexpect.fdspawn(fd) print "Waiting for device to be switched on...." # Wait for device to power up m.expect("ADM5120 Boot:") # Three spaces to interrupt the boot m.send(" ") m.expect("Please enter your key : ") # Download to sdram... if burn : print "Writing image to flash..." m.send("a") else : print "Writing image to SDRAM..." m.send("b") m.expect("Downloading........") # type some random garbage to make the transfer work. m.send("sdfgdshh") # Done with expect, close the device del m # Open the xmodem program to send the file. We don't use # 'sx' here, but instead 'lsz -X' because 'sx' doesn't work on # Slackware 11.0 os.system("lsz -X -vv %s > %s < %s" % (image, device, device) ) # re-connect to serial device fd = os.open(device, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY) m = fdpexpect.fdspawn(fd) # Connect to the terminal m.interact()
def __init__(self, port="/dev/ttyUSB0", baudrate=115200, prompt="[root@localhost]# "): self.serial = serial.Serial(port, baudrate, timeout=1) self.serial.flushInput() self.serial.flushOutput() self.ffd = fdpexpect.fdspawn(self.serial.fd) self.prompt = prompt # assume that because we flushed, we are at a bare prompt CommBase.__init__(self)
def _initalize_pexpect(self): # Initalize serial port self.serial = serial.Serial(self.config['serial']['port'], self.config['serial']['baud'], self.config['serial']['bits'], self.config['serial']['parity'], timeout=None) self.fd = self.serial.fileno() # Flush current contents of serial Input buffer self.serial.flushInput() # Pass file descriptor for open serial port to pexpect self.switch = fdpexpect.fdspawn(self.fd) # Debugging # self.switch.logfile = sys.stdout # Wait for switch to finish booting and try to get # us into enable mode timeout_tries = 0 sys.stdout.write("Waiting for switch") sys.stdout.flush() while True: self.switch.sendline("\r\n") res = self._do_expect_prompt(10) if res == 0: self.switch.sendline('no') elif res == 1: self.switch.sendline('enable') elif res == 2: # we're good to go break elif res == 3: self.switch.sendline('exit') elif res in [4, 5]: raise CIOSProvisionException('Auth prompt encountered. Switch already configured?') elif res == 6: raise CIOSProvisionException('Unexpected and unhandled prompt received from switch.\n{0}'.format(self.switch.before)) elif res == 7: sys.stdout.write('.') sys.stdout.flush() # Five minutes of trying (10 * 30) if timeout_tries > 30: raise CIOSProvisionException("Timeout after five minutes. Check switch and serial link.\n{0}".format(self.switch.before)) timeout_tries += 1 # Newline after waiting finishes print("") # Clean up the expect buffer on our way out or things will # get confused in future _do_line usage self.switch.expect(['$', fdpexpect.TIMEOUT], timeout=1)
def Open_serial(): global ser ser = serial.Serial(port,9600) ser.flushInput() time.sleep(1) global child fd = os.open(port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY) child = fdpexpect.fdspawn(fd) # Note integer fd is used instead of usual string. child.logfile_read = sys.stdout child.logfile_send = sys.stdout
def open_serial_connection(timeout, get_conn=False, init_dtr=None, *args, **kwargs): """ Opens a serial connection to a device. :param timeout: timeout for the fdpexpect spawn object. :param conn: ``bool`` that specfies whether the underlying connection object should be yielded as well. :param init_dtr: specifies the initial DTR state stat should be set. All arguments are passed into the __init__ of serial.Serial. See pyserial documentation for details: http://pyserial.sourceforge.net/pyserial_api.html#serial.Serial :returns: a pexpect spawn object connected to the device. See: http://pexpect.sourceforge.net/pexpect.html """ if init_dtr is not None: kwargs['dsrdtr'] = True try: conn = serial.Serial(*args, **kwargs) except serial.SerialException as e: raise HostError(e.message) if init_dtr is not None: conn.setDTR(init_dtr) conn.nonblocking() conn.flushOutput() target = fdpexpect.fdspawn(conn.fileno(), timeout=timeout) target.logfile_read = PexpectLogger('read') target.logfile_send = PexpectLogger('send') # Monkey-patching sendline to introduce a short delay after # chacters are sent to the serial. If two sendline s are issued # one after another the second one might start putting characters # into the serial device before the first one has finished, causing # corruption. The delay prevents that. tsln = target.sendline def sendline(x): tsln(x) time.sleep(0.1) target.sendline = sendline if get_conn: yield target, conn else: yield target target.close() # Closes the file descriptor used by the conn. del conn
def __enter__(self): self.lock.acquire() self.fd = os.open(self.serial_port, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY) attr_list = termios.tcgetattr(self.fd) attr_list[1] &= ~termios.ONLCR attr_list[3] &= ~termios.ECHO attr_list[3] &= ~termios.ICANON attr_list[4] = self.baud_rate attr_list[5] = self.baud_rate attr_list[6][termios.VTIME] = 5 termios.tcsetattr(self.fd, termios.TCSAFLUSH, attr_list) return fdpexpect.fdspawn(self.fd)
def _open(self): """Connect to serial device and create pexpect interface.""" assert self._fd is None self._fd = os.open(self._pty_path, os.O_RDWR | os.O_NONBLOCK) # Don't allow forked processes to access. fcntl.fcntl(self._fd, fcntl.F_SETFD, fcntl.fcntl(self._fd, fcntl.F_GETFD) | fcntl.FD_CLOEXEC) self._child = fdpexpect.fdspawn(self._fd) # pexpect defaults to a 100ms delay before sending characters, to # work around race conditions in ssh. We don't need this feature # so we'll change delaybeforesend from 0.1 to 0.001 to speed things up. if self._fast: self._child.delaybeforesend = 0.001
def load(device, baud, program): serialport = serial.Serial(device, baud, timeout=0) c = fdpexpect.fdspawn(serialport.fd) # c.logfile_read = sys.stdout # synch with the command prompt c.sendline("") waitprompt(c) # do stuff for line in program: line = line.strip() if (len(line) > 0) and (line[0] != "#"): c.sendline(line) waitprompt(c) c.close()
def load(device, baud, program): serialport = serial.Serial(device, baud, timeout=0) c = fdpexpect.fdspawn(serialport.fd) #c.logfile_read = sys.stdout # synch with the command prompt c.sendline('') waitprompt(c) # do stuff for line in program: line = line.strip() if (len(line) > 0) and (line[0] != '#'): c.sendline(line) waitprompt(c) c.close()
def run_python_module(context, module, target): logfile = None if hasattr(context, "stdout_capture"): logfile = context.stdout_capture fullname = "{}.{}".format(module, target) _io, pipeio = pty.openpty() def run_script(_pipe, _io, ctx): sys.stdout = os.fdopen(_pipe, "w") sys.stderr = os.fdopen(_pipe, "w") sys.stdin = os.fdopen(_pipe, "r") # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(_pipe), os.O_RDWR) os.close(tmp_fd) os.setsid() try: from features.steps import mp_setup mp_setup(ctx) except ImportError: pass try: from setproctitle import setproctitle setproctitle("python process: {}".format(fullname)) except ImportError: pass for name, value in ctx.environ.iteritems(): os.environ[name] = value os.chdir(ctx.cwd) sys.argv = ["-"] if ctx.args: sys.argv += shlex.split(ctx.args) else: sys.argv = ["me"] getattr(import_module(module), target)() proc = Process(target=run_script, args=(pipeio, _io, context)) proc.start() os.close(pipeio) context.child = fdpexpect.fdspawn(_io, logfile=logfile) context.child.__proc = proc context.child.__io = _io context.children[fullname] = context.child
def Initialize(device): "Set up the board to a known state and connect pexpect to it. Return the pexpect object." g_power.Off() SetupSerial(device) print "Connecting to serial device...", fd = os.open(device, os.O_RDWR | os.O_NONBLOCK | os.O_NOCTTY) print fd m = fdpexpect.fdspawn(fd) print "Waiting for embedded device to be switched on..." g_power.On() return m
def __init__(self, device, baudrate=57600, debug=False, dsrdtr=False, rtscts=False, xonxoff=False): # Initialize object data members self.is_command = False # Track if we've entered command mode self.is_remote = False # Track if operating on remote radio self.read_timeout = 5 # Max time to wait for data logfile=None if debug: logfile=sys.stdout # Initialize the serial connection # Note: we pass the buck on raised exceptions self.port = serial.Serial(device, baudrate=baudrate, timeout=0, dsrdtr=dsrdtr, rtscts=rtscts, xonxoff=xonxoff) self.ser = fdpexpect.fdspawn(self.port.fileno(), logfile=logfile)
def load(device, baud, program): """ Load a bitlash program onto the Arduino. """ serialport = serial.Serial(device, baud, timeout=0) c = fdpexpect.fdspawn(serialport.fd) #c.logfile_read = sys.stdout # synch with the command prompt c.sendline('') waitprompt(c) # do stuff for line in program: line = line.strip() if (len(line) > 0) and (line[0] != '#'): c.sendline(line) waitprompt(c) c.close() return None
def Initialize(device): "Set up the board to a known state and connect pexpect to it. Return the pexpect object." g_power.Off() SetupSerial(device) print "Connecting to serial device...", fd = os.open(device, os.O_RDWR|os.O_NONBLOCK|os.O_NOCTTY) print fd m = fdpexpect.fdspawn(fd) print "Waiting for embedded device to be switched on..." g_power.On() return m
def run_python_module(context, module, target): logfile = None if hasattr(context, 'stdout_capture'): logfile = context.stdout_capture fullname = "{}.{}".format(module, target) _io, pipeio = pty.openpty() def run_script(_pipe, _io, ctx): sys.stdout = os.fdopen(_pipe, "w") sys.stderr = os.fdopen(_pipe, "w") sys.stdin = os.fdopen(_pipe, "r") # Explicitly open the tty to make it become a controlling tty. tmp_fd = os.open(os.ttyname(_pipe), os.O_RDWR) os.close(tmp_fd) os.setsid() try: from features.steps import mp_setup mp_setup(ctx) except ImportError: pass try: from setproctitle import setproctitle setproctitle("python process: {}".format(fullname)) except ImportError: pass for name, value in ctx.environ.iteritems(): os.environ[name] = value os.chdir(ctx.cwd) sys.argv = ['-'] if ctx.args: sys.argv += shlex.split(ctx.args) else: sys.argv = ['me'] getattr(import_module(module), target)() proc = Process(target=run_script, args=(pipeio, _io, context)) proc.start() os.close(pipeio) context.child = fdpexpect.fdspawn(_io, logfile=logfile) context.child.__proc = proc context.child.__io = _io context.children[fullname] = context.child
def load(device, baud, setup, loop): serialport = serial.Serial(device, baud, timeout=0) c = fdpexpect.fdspawn(serialport.fd) c.sendline('') waitprompt(c) for line in setup.splitlines(): line = line.strip() if (len(line) > 0) and (line[0] != '#'): c.sendline(line) waitprompt(c) while True: for line in loop.splitlines(): line = line.strip() if (len(line) > 0) and (line[0] != '#'): c.sendline(line) waitprompt(c) c.close() # unreachable ...
def update_mode(device): '''put a HM-TRP into update mode''' port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK','SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&UPDATE\r\n') try: buf = ser.read_nonblocking(100, timeout=1) except pexpect.TIMEOUT: pass port.close()
def init_jsbsim(self): cmd = "JSBSim --realtime --suspend --nice --simulation-rate=1000 --logdirectivefile=data/flightgear.xml --script=%s" % self.script if self.options: cmd += ' %s' % self.options jsb = pexpect.spawn(cmd, logfile=sys.stdout, timeout=10) jsb.delaybeforesend = 0 util.pexpect_autoclose(jsb) i = jsb.expect([ "Successfully bound to socket for input on port (\d+)", "Could not bind to socket for input" ]) if i == 1: print("Failed to start JSBSim - is another copy running?") sys.exit(1) jsb_out_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Creating UDP socket on port (\d+)") jsb_in_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Successfully connected to socket for output") jsb.expect("JSBSim Execution beginning") # setup output to jsbsim print("JSBSim console on %s" % str(jsb_out_address)) jsb_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM) jsb_out.connect(jsb_out_address) jsb_console = fdpexpect.fdspawn(jsb_out.fileno(), logfile=sys.stdout) jsb_console.delaybeforesend = 0 jsb_console.logfile = None # setup input from jsbsim print("JSBSim FG FDM input on %s" % str(jsb_in_address)) jsb_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) jsb_in.bind(jsb_in_address) jsb_in.setblocking(0) # set class data self.jsb = jsb self.jsb_in = jsb_in self.jsb_out = jsb_out self.jsb_console = jsb_console self.fdm = fgFDM.fgFDM()
def rssi(device): port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK', 'SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&F\r\n') try: ser.expect(['OK'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&T=RSSI\r\n') ctr = 0 while ctr < 200: try: count = port.inWaiting() if count == 0: count = 1 buf = port.read(count) if len(buf) == 0: continue sys.stdout.write(buf) sys.stdout.flush() ctr = ctr + 1 except KeyboardInterrupt: sys.exit(0) port.close()
def init_jsbsim(self): cmd = ( "JSBSim --realtime --suspend --nice --simulation-rate=1000 --logdirectivefile=data/flightgear.xml --script=%s" % self.script ) if self.options: cmd += " %s" % self.options jsb = pexpect.spawn(cmd, logfile=sys.stdout, timeout=10) jsb.delaybeforesend = 0 util.pexpect_autoclose(jsb) i = jsb.expect(["Successfully bound to socket for input on port (\d+)", "Could not bind to socket for input"]) if i == 1: print ("Failed to start JSBSim - is another copy running?") sys.exit(1) jsb_out_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Creating UDP socket on port (\d+)") jsb_in_address = self.interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Successfully connected to socket for output") jsb.expect("JSBSim Execution beginning") # setup output to jsbsim print ("JSBSim console on %s" % str(jsb_out_address)) jsb_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM) jsb_out.connect(jsb_out_address) jsb_console = fdpexpect.fdspawn(jsb_out.fileno(), logfile=sys.stdout) jsb_console.delaybeforesend = 0 jsb_console.logfile = None # setup input from jsbsim print ("JSBSim FG FDM input on %s" % str(jsb_in_address)) jsb_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) jsb_in.bind(jsb_in_address) jsb_in.setblocking(0) # set class data self.jsb = jsb self.jsb_in = jsb_in self.jsb_out = jsb_out self.jsb_console = jsb_console self.fdm = fgFDM.fgFDM()
def rssi(device): port = serial.Serial(device, opts.baudrate, timeout=0, dsrdtr=opts.dsrdtr, rtscts=opts.rtscts, xonxoff=opts.xonxoff) ser = fdpexpect.fdspawn(port.fileno(), logfile=sys.stdout) ser.send('+++') time.sleep(1) ser.send('\r\nATI\r\n') try: ser.expect(['OK','SiK .* on HM-TRP'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&F\r\n') try: ser.expect(['OK'], timeout=2) except fdpexpect.TIMEOUT: print("timeout") return ser.send('AT&T=RSSI\r\n') ctr = 0 while ctr < 200: try: count = port.inWaiting() if count == 0: count = 1 buf = port.read(count) if len(buf) == 0: continue sys.stdout.write(buf) sys.stdout.flush() ctr = ctr + 1 except KeyboardInterrupt: sys.exit(0) port.close()
def run_from_apbridge(svc, host, test, size, verbose, apb): csv_path = 'apb_%s_%s_1000.csv' % (test, size) # gbl is using a slightly different name apb_test_cmd = APB_CMD % (test.replace('transfer', 'xfer'), size) info(csv_path, test, size, apb_test_cmd) f = fdpexpect.fdspawn(apb.fd, timeout=5) print('Create CSV file (%s)' % csv_path) with open(csv_path, "w") as fd: count = 1 try: for pwrm, cmds in PWRM_TO_CMDS: print('\nTest (%d) - ' % count + pwrm + '\n') for cmd in cmds: exec_cmd(svc, cmd) if verbose: # insert the test name into the CSV file # TODO: add a new column into the CSV instead of new row call(['ssh', ssh_host, 'echo "%s" >> %s' % (pwrm, csv_path)]) fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) fd.write('%s,%s,%s,%s\n' % (strftime("%c"), test, size, gbl_stats(f, apb_test_cmd))) count += 1 except KeyboardInterrupt: info('\nKeyboardInterrupt')
def __init__(self, port="/dev/ttyUSB0", ser=None): self.verbose = 0 if not ser: ser = serial.Serial(port, baudrate=115200, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, rtscts=False, dsrdtr=False, xonxoff=False, timeout=3.0, # Blocking writes writeTimeout=None) self.ser = ser self.ser.flushInput() self.ser.flushOutput() self.e = fdpexpect.fdspawn(self.ser.fileno()) self.e.timeout = 1.0 self.rst_sync() self.owire() self.ps_on() self.pu_on()
def start(self): self.report = [] main = None # Placeholder for the main test others = [] # Holds other tests for test in self.tree.xpath('./ar:Test', namespaces={ 'ar': 'http://moodlegradetool.com/advanced_regex'}): # Get all test nodes if (not 'file' in test.attrib) and not main: # See if this is the first test with out a filename main = test # Set it to be the main test else: others.append((test, test.get('file'))) # Append every other test to the others if not main: raise ValueError("Could not find the main test") java_cls = self.clsName if not hasattr(self, 'main') else self.main # Get the main java class self._out = StringIO.StringIO() # Make a stringIO to hold the output proc = pexpect.spawn('java', [java_cls], logfile=self._out, cwd=self.cwd) # Spawn the java program self.do_test(proc, main) # Do the main test for test, fname in others: # Do the other tests with open(self.cwd + '/' + fname, 'r') as f: # Open the associated file fexp = fdpexpect.fdspawn(f) # Spawn an expect instance for the file self.do_test(fexp, test) # Do the test
def get_target_type(tty, baudrate): ser = serial.Serial(port=tty, baudrate=baudrate) ser.flushInput() fdp = fdpexpect.fdspawn(ser.fd, timeout=10) try: fdp.sendline('help') fdp.expect(['nsh>', 'bash', 'Password', 'Login']) except pexpect.TIMEOUT: info('timeout {}'.format(fdp.before.strip())) return Target('UNK', tty) except pexpect.EOF: info('Cannot reach the console {}'.format(tty)) return Target('UNK', tty) if 'nsh>' in fdp.after: if 'svc' in fdp.before: return Target('SVC', tty) try: # Split the command otherwise nuttx is missing some # characters cmd = 'unipro r 0x3000 0' for c in cmd.split(): fdp.send(c + ' ') fdp.sendline() fdp.expect('nsh>') m = re.search('\[3000\]: (\d)', fdp.before) d = int(m.group(1)) return Target('UNK', tty, d) except pexpect.TIMEOUT: info('{} timeout {}'.format(tty, fdp.before.strip())) return Target('UNK', tty) else: return Target('BBB', tty)
i = jsb.expect(["Successfully bound to socket for input on port (\d+)", "Could not bind to socket for input"]) if i == 1: print("Failed to start JSBSim - is another copy running?") sys.exit(1) jsb_out_address = interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Creating UDP socket on port (\d+)") jsb_in_address = interpret_address("127.0.0.1:%u" % int(jsb.match.group(1))) jsb.expect("Successfully connected to socket for output") jsb.expect("JSBSim Execution beginning") # setup output to jsbsim print("JSBSim console on %s" % str(jsb_out_address)) jsb_out = socket.socket(socket.AF_INET, socket.SOCK_STREAM) jsb_out.connect(jsb_out_address) jsb_console = fdpexpect.fdspawn(jsb_out.fileno(), logfile=sys.stdout) jsb_console.delaybeforesend = 0 # setup input from jsbsim print("JSBSim FG FDM input on %s" % str(jsb_in_address)) jsb_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) jsb_in.bind(jsb_in_address) jsb_in.setblocking(0) # socket addresses sim_out_address = interpret_address(opts.simout) sim_in_address = interpret_address(opts.simin) # setup input from SITL sim sim_in = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sim_in.bind(sim_in_address)
def test_fd_isatty(): fd = os.open(file, os.O_RDONLY) s = fdpexpect.fdspawn(fd) assert not s.isatty() s.close()
def test_fd_isalive(): fd = os.open(file, os.O_RDONLY) s = fdpexpect.fdspawn(fd) assert s.isalive() os.close(fd) assert not s.isalive(), "Should not be alive after close()"