initialize the serial port with baudrate, timeout parameters
503903
def intialize(self):
        """"""
        print '%s call intialize' % self.port
        try:
            self.deviceConnected = False

            # init serial port
            self._connect()

            if self.firmwarePrefix in self.UIStatusMsg:
                self.deviceConnected = True
            else:
                self.UIStatusMsg = "Firmware Not Matching Expecting " + self.firmwarePrefix + " Now is " + self.UIStatusMsg
                ModuleHelper.WriteIntoDebugLogger("Err: OpenThread device Firmware not matching..")

        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("intialize() Error: " + str(e))
            self.deviceConnected = False
1167923
def write_port(self, port, value):
        
        if port == 'A':
            self.GPIOA = value
        elif port == 'B':
            self.GPIOB = value
        else:
            raise AttributeError('Port {} does not exist, use A or B'.format(port))
        self.sync()
1342451
def _initialize(cls, port, secret):
        
        cls._port = port
        cls._secret = secret
1020172
def serial_port(self, serial_port):
        
        char_size = get_char_size(serial_port.baudrate)

        # See docstring of get_char_size() for meaning of constants below.
        serial_port.inter_byte_timeout = 1.5 * char_size
        serial_port.timeout = 3.5 * char_size
        self._serial_port = serial_port
425548
def init_generic_serial_dut(contextlist, conf, index, args):
    
    port = conf['serial_port']
    baudrate = (args.baudrate if args.baudrate else conf.get(
        "application", {}).get("baudrate", 115200))
    serial_config = {}
    if args.serial_rtscts:
        serial_config["serial_rtscts"] = args.serial_rtscts
    elif args.serial_xonxoff:
        serial_config["serial_xonxoff"] = args.serial_xonxoff

    if args.serial_timeout:
        serial_config["serial_timeout"] = args.serial_timeout

    ch_mode_config = {}
    if args.serial_ch_size > 0:
        ch_mode_config["ch_mode"] = True
        ch_mode_config["ch_mode_chunk_size"] = args.serial_ch_size
    elif args.serial_ch_size is 0:
        ch_mode_config["ch_mode"] = False

    if args.ch_mode_ch_delay:
        ch_mode_config["ch_mode_ch_delay"] = args.ch_mode_ch_delay
    dut = DutSerial(name="D%d" % index, port=port, baudrate=baudrate,
                    config=conf, ch_mode_config=ch_mode_config,
                    serial_config=serial_config, params=args)
    dut.index = index

    dut.platform = conf.get("platform_name", "serial")

    msg = 'Use device in serial port {} as D{}'
    contextlist.logger.info(msg.format(port,
                                       index))

    contextlist.duts.append(dut)
    contextlist.dutinformations.append(dut.get_info())
1319365
def init(opts):
    '''
    
    '''
    opts['multiprocessing'] = False
    log.debug('Opening connection to junos')

    args = {"host": opts['proxy']['host']}
    optional_args = ['user',
                     'username',
                     'password',
                     'passwd',
                     'port',
                     'gather_facts',
                     'mode',
                     'baud',
                     'attempts',
                     'auto_probe',
                     'ssh_private_key_file',
                     'ssh_config',
                     'normalize'
                     ]

    if 'username' in opts['proxy'].keys():
        opts['proxy']['user'] = opts['proxy'].pop('username')
    proxy_keys = opts['proxy'].keys()
    for arg in optional_args:
        if arg in proxy_keys:
            args[arg] = opts['proxy'][arg]

    thisproxy['conn'] = jnpr.junos.Device(**args)
    try:
        thisproxy['conn'].open()
    except (ProbeError, ConnectAuthError, ConnectRefusedError, ConnectTimeoutError,
            ConnectError) as ex:
        log.error("{} : not able to initiate connection to the device".format(str(ex)))
        thisproxy['initialized'] = False
        return

    if 'timeout' in proxy_keys:
        timeout = int(opts['proxy']['timeout'])
        try:
            thisproxy['conn'].timeout = timeout
        except Exception as ex:
            log.error('Not able to set timeout due to: %s', str(ex))
        else:
            log.debug('RPC timeout set to %d seconds', timeout)

    try:
        thisproxy['conn'].bind(cu=jnpr.junos.utils.config.Config)
    except Exception as ex:
        log.error('Bind failed with Config class due to: {}'.format(str(ex)))

    try:
        thisproxy['conn'].bind(sw=jnpr.junos.utils.sw.SW)
    except Exception as ex:
        log.error('Bind failed with SW class due to: {}'.format(str(ex)))
    thisproxy['initialized'] = True
890504
function initSerial(robot, port, callback) {
	serial = new Serial.SerialPort(port, {
		//Defaults for Roomba Open Interface:
		baudrate:115200, dataBits:8,
		parity:'none', stopBits:1,
		flowControl:false
	});
	serial.on('open', function() {
		//Send Start Command:
		serial.write(Buffer([128]));
		setSensorRead(true, robot);
		//Listen to Incoming Data:
		serial.on('data', function(data) {
			//Combine Previous Data:
			if(robot.inputBuffer) {
				robot.inputBuffer = Buffer.concat([robot.inputBuffer,
				data], robot.inputBuffer.length + data.length);
			} else robot.inputBuffer = data;
			//Data Parsing Timer:
			if(robot.inputTimer) clearTimeout(robot.inputTimer);
			robot.inputTimer = setTimeout(function() {
				if(robot.dataParser && robot.inputBuffer && robot.inputBuffer.length >= 80)
				{ robot.dataParser(robot.inputBuffer); robot.inputBuffer = robot.inputTimer = null; }
				if(exports.debug && robot.inputBuffer && robot.inputBuffer.length != 80)
				console.log(chalk.bold.green("Packet Miss ["+robot.inputBuffer.length+"]"));
			}, 5);
		});
		if(callback) callback(robot);
	});
	return serial;
}
1053731
def open
			@serial ||= SerialPort.new @port, @rate
			@serial_input = Enumerator.new { |y| loop do
				y.yield @serial.readbyte
			end }
			@connected = true
		end
1014858
def open_connection(self):
        
        if self.readthread is not None:
            raise DutConnectionError("Trying to open serial port which was already open")

        self.logger.info("Open Connection "
                         "for '%s' using '%s' baudrate: %d" % (self.dut_name,
                                                               self.comport,
                                                               self.serial_baudrate),
                         extra={'type': '<->'})
        if self.serial_xonxoff:
            self.logger.debug("Use software flow control for dut: %s" % self.dut_name)
        if self.serial_rtscts:
            self.logger.debug("Use hardware flow control for dut: %s" % self.dut_name)
        try:
            self.port = EnhancedSerial(self.comport)
            self.port.baudrate = self.serial_baudrate
            self.port.timeout = self.serial_timeout
            self.port.xonxoff = self.serial_xonxoff
            self.port.rtscts = self.serial_rtscts
            self.port.flushInput()
            self.port.flushOutput()
        except SerialException as err:
            self.logger.warning(err)
            raise DutConnectionError(str(err))
        except ValueError as err:
            self.logger.warning(err)
            raise ValueError(str(err))

        if self.ch_mode:
            self.logger.info("Use chunk-mode with size %d, delay: %.3f when write data" %
                             (self.ch_mode_chunk_size, self.ch_mode_ch_delay),
                             extra={'type': '<->'})
            time.sleep(self.ch_mode_start_delay)
        else:
            self.logger.info("Use normal serial write mode", extra={'type': '<->'})
        if self.params.reset:
            self.reset()
        # Start the serial reading thread
        self.readthread = Thread(name=self.name, target=self.run)
        self.readthread.start()
163489
def tick(self):
        """"""
        try:
            s, addr = self.socket.accept()
            if self.stats['Enabled']:
                self.stats['Accepts'] += 1
            if not self.ready:
                return

            prevent_socket_inheritance(s)
            if hasattr(s, 'settimeout'):
                s.settimeout(self.timeout)

            mf = MakeFile
            ssl_env = {}
            # if ssl cert and key are set, we try to be a secure HTTP server
            if self.ssl_adapter is not None:
                try:
                    s, ssl_env = self.ssl_adapter.wrap(s)
                except errors.NoSSLError:
                    msg = (
                        'The client sent a plain HTTP request, but '
                        'this server only speaks HTTPS on this port.'
                    )
                    buf = [
                        '%s 400 Bad Request\r\n' % self.protocol,
                        'Content-Length: %s\r\n' % len(msg),
                        'Content-Type: text/plain\r\n\r\n',
                        msg,
                    ]

                    sock_to_make = s if six.PY3 else s._sock
                    wfile = mf(sock_to_make, 'wb', io.DEFAULT_BUFFER_SIZE)
                    try:
                        wfile.write(''.join(buf).encode('ISO-8859-1'))
                    except socket.error as ex:
                        if ex.args[0] not in errors.socket_errors_to_ignore:
                            raise
                    return
                if not s:
                    return
                mf = self.ssl_adapter.makefile
                # Re-apply our timeout since we may have a new socket object
                if hasattr(s, 'settimeout'):
                    s.settimeout(self.timeout)

            conn = self.ConnectionClass(self, s, mf)

            if not isinstance(self.bind_addr, six.string_types):
                # optional values
                # Until we do DNS lookups, omit REMOTE_HOST
                if addr is None:  # sometimes this can happen
                    # figure out if AF_INET or AF_INET6.
                    if len(s.getsockname()) == 2:
                        # AF_INET
                        addr = ('0.0.0.0', 0)
                    else:
                        # AF_INET6
                        addr = ('::', 0)
                conn.remote_addr = addr[0]
                conn.remote_port = addr[1]

            conn.ssl_env = ssl_env

            try:
                self.requests.put(conn)
            except queue.Full:
                # Just drop the conn. TODO: write 503 back?
                conn.close()
                return
        except socket.timeout:
            # The only reason for the timeout in start() is so we can
            # notice keyboard interrupts on Win32, which don't interrupt
            # accept() by default
            return
        except socket.error as ex:
            if self.stats['Enabled']:
                self.stats['Socket Errors'] += 1
            if ex.args[0] in errors.socket_error_eintr:
                # I *think* this is right. EINTR should occur when a signal
                # is received during the accept() call; all docs say retry
                # the call, and I *think* I'm reading it right that Python
                # will then go ahead and poll for and handle the signal
                # elsewhere. See
                # https://github.com/cherrypy/cherrypy/issues/707.
                return
            if ex.args[0] in errors.socket_errors_nonblocking:
                # Just try again. See
                # https://github.com/cherrypy/cherrypy/issues/479.
                return
            if ex.args[0] in errors.socket_errors_to_ignore:
                # Our socket was closed.
                # See https://github.com/cherrypy/cherrypy/issues/686.
                return
            raise
1051962
def initialize(self, timeouts):
        

        # Bind or connect to address
        if self.bind is True:
            self.socket.bind(self.address)
        else:
            self.socket.connect(self.address)

        # Set send and recv timeouts
        self._set_timeouts(timeouts)
1145509
def _connect(self):
        """"""
        try:
            while True:
                _LOGGER.info('Trying to connect to %s', self.port)
                try:
                    yield from serial_asyncio.create_serial_connection(
                        self.loop, lambda: self.protocol, self.port, self.baud)
                    return
                except serial.SerialException:
                    _LOGGER.error('Unable to connect to %s', self.port)
                    _LOGGER.info(
                        'Waiting %s secs before trying to connect again',
                        self.reconnect_timeout)
                    yield from asyncio.sleep(
                        self.reconnect_timeout, loop=self.loop)
        except asyncio.CancelledError:
            _LOGGER.debug('Connect attempt to %s cancelled', self.port)
939791
def raw_on(serial):
    

    def flush_to_msg(serial, msg):
        """Read the rx serial data until we reach an expected message."""
        data = serial.read_until(msg)
        if not data.endswith(msg):
            if COMMAND_LINE_FLAG:
                print(data)
            raise IOError('Could not enter raw REPL.')

    def flush(serial):
        """Flush all rx input without relying on serial.flushInput()."""
        n = serial.inWaiting()
        while n > 0:
            serial.read(n)
            n = serial.inWaiting()

    raw_repl_msg = b'raw REPL; CTRL-B to exit\r\n>'
    # Send CTRL-B to end raw mode if required.
    serial.write(b'\x02')
    # Send CTRL-C three times between pauses to break out of loop.
    for i in range(3):
        serial.write(b'\r\x03')
        time.sleep(0.01)
    flush(serial)
    # Go into raw mode with CTRL-A.
    serial.write(b'\r\x01')
    flush_to_msg(serial, raw_repl_msg)
    # Soft Reset with CTRL-D
    serial.write(b'\x04')
    flush_to_msg(serial, b'soft reboot\r\n')
    # Some MicroPython versions/ports/forks provide a different message after
    # a Soft Reset, check if we are in raw REPL, if not send a CTRL-A again
    data = serial.read_until(raw_repl_msg)
    if not data.endswith(raw_repl_msg):
        serial.write(b'\r\x01')
        flush_to_msg(serial, raw_repl_msg)
    flush(serial)
197732
def setNetworkIDTimeout(self, iNwkIDTimeOut):
        
        print '%s call setNetworkIDTimeout' % self.port
        print iNwkIDTimeOut
        iNwkIDTimeOut /= 1000
        try:
            cmd = 'networkidtimeout %s' % str(iNwkIDTimeOut)
            print cmd
            return self.__sendCommand(cmd)[0] == 'Done'
        except Exception, e:
            ModuleHelper.WriteIntoDebugLogger("setNetworkIDTimeout() Error: " + str(e))
880017
def set_ports(self, port0 = 0x00, port1 = 0x00):
        ''
        self.bus.write_byte_data(self.address, self.OUTPUT_PORT0, port0)
        self.bus.write_byte_data(self.address, self.OUTPUT_PORT1, port1)
        return True
1334777
private void init(int port, File commandFileTmp) throws IOException {
        if (port != -1) {
            serverSocketChannel = SelectorProvider.provider().openServerSocketChannel();

            // Open the socket for loopback only..
            InetSocketAddress address = new InetSocketAddress(InetAddress.getByName(null), port);

            IOException bindError = null;

            boolean isWindows = System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows");

            try {
                //Attempt bind with reuseAddress set to false.
                serverSocketChannel.socket().setReuseAddress(false);
                serverSocketChannel.socket().bind(address);

                //If we are not on Windows and the bind succeeded, we should set reuseAddr=true
                //for future binds.
                if (!isWindows) {
                    serverSocketChannel.socket().setReuseAddress(true);
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "ServerSocket reuse set to true to allow for later override");
                    }
                }
            } catch (IOException ioe) {
                // see if we got the error because port is in waiting to be cleaned up.
                // If so, no one should be accepting connections on it, and open should fail.
                // If that's the case, we can set ReuseAddr to expedite the bind process.
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "ServerSocket bind failed on first attempt with IOException: " + ioe.getMessage());
                }
                bindError = ioe;
                try {
                    InetSocketAddress testAddr = new InetSocketAddress(InetAddress.getByName(null), port);
                    if (!testAddr.isUnresolved()) {
                        SocketChannel testChannel = SocketChannel.open(testAddr);
                        // if we get here, socket opened successfully, which means someone is really listening
                        // so close connection and don't bother trying to bind again
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "attempt to connect to command port to check listen status worked, someone else is using the port!");
                        }
                        testChannel.close();
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Test connection addr is unresolvable; " + testAddr);
                        }
                    }
                } catch (IOException testioe) {
                    if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                        Tr.debug(tc, "attempt to connect to command port to check listen status failed with IOException: " + testioe.getMessage());
                    }
                    try {
                        // open (or close) got IOException, retry with reuseAddress set to true
                        serverSocketChannel.socket().setReuseAddress(true);
                        serverSocketChannel.socket().bind(address);
                        bindError = null;

                    } catch (IOException newioe) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "ServerSocket bind failed on second attempt with IOException: " + newioe.getMessage());
                        }
                        bindError = newioe;
                    }
                }
            }

            if (bindError == null) {
                // if we requested an ephemeral port, find out what port we ended up with
                if (port == 0) {
                    port = serverSocketChannel.socket().getLocalPort();
                }
                listenForCommands = true;
            } else {
                throw bindError;
            }
        }

        ServerCommandID sci = new ServerCommandID(port, serverUUID);

        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(commandFileTmp);
            fos.write(sci.getIDString().getBytes());
            fos.close();
        } finally {
            Utils.tryToClose(fos);
        }
    }
554372
def send(self, enc, load, tries=1, timeout=60):
        '''
        
        '''
        payload = {'enc': enc}
        payload['load'] = load
        pkg = self.serial.dumps(payload)
        self.socket.send(pkg)
        self.poller.register(self.socket, zmq.POLLIN)
        tried = 0
        while True:
            polled = self.poller.poll(timeout * 1000)
            tried += 1
            if polled:
                break
            if tries > 1:
                log.info(
                    'SaltReqTimeoutError: after %s seconds. (Try %s of %s)',
                    timeout, tried, tries
                )
            if tried >= tries:
                self.clear_socket()
                raise SaltReqTimeoutError(
                    'SaltReqTimeoutError: after {0} seconds, ran {1} '
                    'tries'.format(timeout * tried, tried)
                )
        return self.serial.loads(self.socket.recv())