public BasicInformation(string portName, int baudRate, Parity parity, StopBits stopBits, int dataBits, Handshake handShake, string serviceCenter, bool pduMode) { this.Connector = new ATController(portName, baudRate, parity, stopBits, dataBits, handShake); ServiceCenter = serviceCenter; PDUMode = pduMode; this.PortName = portName; }
private async void SaveSettingss(string port, int baud, Parity parity, Handshake handshake, int dataBits, StopBits stopBits) { writing = true; XmlWriterSettings settings = new XmlWriterSettings { Indent = true, NewLineOnAttributes = true }; XmlWriter writer = XmlWriter.Create("Settings.xml", settings); writer.WriteStartDocument(); writer.WriteStartElement("Settings"); writer.WriteElementString("Port", port); writer.WriteElementString("Baudrate", baud.ToString()); writer.WriteElementString("Parity", parity.ToString()); writer.WriteElementString("Handshake", handshake.ToString()); writer.WriteElementString("Data_Bits", dataBits.ToString()); writer.WriteElementString("Stop_Bits", stopBits.ToString()); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Close(); writing = false; if(!initialization) { MessageDialogResult result = await MessageService.ShowMessage("Gespeichert!", "Settings wurden gespeichert!", MessageDialogStyle.Affirmative).ConfigureAwait(false); } }
public FrostedSerialPortStream(string portName, int baudRate, int dataBits, Parity parity, StopBits stopBits, bool dtrEnable, bool rtsEnable, Handshake handshake, int readTimeout, int writeTimeout, int readBufferSize, int writeBufferSize) { fd = open_serial(portName); if (fd == -1) { ThrowIOException (); } TryBaudRate(baudRate); int canSetAttributes = set_attributes (fd, baudRate, parity, dataBits, stopBits, handshake); if (canSetAttributes != 0) { throw new IOException(canSetAttributes.ToString()); // Probably Win32Exc for compatibility } read_timeout = readTimeout; write_timeout = writeTimeout; SetSignal(SerialSignal.Dtr, dtrEnable); if (handshake != Handshake.RequestToSend && handshake != Handshake.RequestToSendXOnXOff) SetSignal(SerialSignal.Rts, rtsEnable); }
public RS232Config(int baudrate, int dataBits, Parity p, StopBits s, Handshake h, string t) { Baudrate = baudrate; DataBits = dataBits; Parity = p; StopBits = s; Handshake = h; Terminator = t; }
public ConnectionParameters(string portName, int baudRate, int dataBitsCount, Parity parity, Handshake handshakeType, StopBits stopBitsType, EndMarker endMarker) { PortName = portName; BaudRate = baudRate; DataBits = dataBitsCount; Parity = parity; Handshake = handshakeType; StopBits = stopBitsType; EndMarker = endMarker; }
public XSerialParameter(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handShake) { PortName = portName; Baudrate = baudRate; Parity = parity; DataBits = DataBits; StopBits = stopBits; Handshake = handShake; }
public WinSerialStream (string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb, bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout, int read_buffer_size, int write_buffer_size) { handle = CreateFile (port_name != null && !port_name.StartsWith(@"\\.\") ? @"\\.\" + port_name : port_name, GenericRead | GenericWrite, 0, 0, OpenExisting, FileFlagOverlapped, 0); if (handle == -1) ReportIOError (port_name); // Set port low level attributes SetAttributes (baud_rate, parity, data_bits, sb, hs); // Clean buffers and set sizes if (!PurgeComm (handle, PurgeRxClear | PurgeTxClear) || !SetupComm (handle, read_buffer_size, write_buffer_size)) ReportIOError (null); // Set timeouts this.read_timeout = read_timeout; this.write_timeout = write_timeout; timeouts = new Timeouts (read_timeout, write_timeout); if (!SetCommTimeouts(handle, timeouts)) ReportIOError (null); /// Set DTR and RTS SetSignal(SerialSignal.Dtr, dtr_enable); if (hs != Handshake.RequestToSend && hs != Handshake.RequestToSendXOnXOff) SetSignal(SerialSignal.Rts, rts_enable); // Init overlapped structures NativeOverlapped wo = new NativeOverlapped (); write_event = new ManualResetEvent (false); #if NET_2_0 wo.EventHandle = write_event.Handle; #else wo.EventHandle = (int) write_event.Handle; #endif write_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped))); Marshal.StructureToPtr (wo, write_overlapped, true); NativeOverlapped ro = new NativeOverlapped (); read_event = new ManualResetEvent (false); #if NET_2_0 ro.EventHandle = read_event.Handle; #else ro.EventHandle = (int) read_event.Handle; #endif read_overlapped = Marshal.AllocHGlobal (Marshal.SizeOf (typeof (NativeOverlapped))); Marshal.StructureToPtr (ro, read_overlapped, true); }
public static int ToInt(Handshake hs) { switch (hs) { case Handshake.None: return 0; case Handshake.XOnXOff: return 1; case Handshake.RequestToSend: return 2; case Handshake.RequestToSendXOnXOff: return 3; } return 0; }
/// <summary> /// Initializes a new instance of the SerialCommunication class using the specified serial port name. /// A connection is not established until Open() or StartMonitoring() is called. /// </summary> /// <param name="serialPortName">The serial port to use (for example, COM1).</param> /// <param name="baudRate">The baud rate.</param> /// <param name="parity">One of the Parity values.</param> /// <param name="dataBits">The data bits value. Usually 8.</param> /// <param name="stopBits">One of the StopBits values. Usually 1.</param> /// <param name="handShake">The handshake protocol. Usually none.</param> public SerialCommunication(string serialPortName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handShake, bool dtrEnable, bool rtsEnable) { _serialPortName = serialPortName; _baudRate = baudRate; _parity = parity; _dataBits = dataBits; _stopBits = stopBits; _handShake = handShake; _dtrEnable = dtrEnable; _rtsEnable = rtsEnable; }
internal Configuration(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits) { PortIndex = System.IO.Ports.SerialPortName.ConvertNameToIndex(portName); Speed = baudRate; Parity = parity; DataBits = dataBits; StopBits = stopBits; Handshake = Handshake.None; ReadTimeout = Timeout.Infinite; WriteTimeout = Timeout.Infinite; }
public static string ToString(Handshake hs) { switch (hs) { case Handshake.None: return "None"; case Handshake.XOnXOff: return "XOnXOff"; case Handshake.RequestToSend: return "RequestToSend"; case Handshake.RequestToSendXOnXOff: return "RequestToSendXOnXOff"; } return "None"; }
public bool Load(XmlHelper xh, XmlNode parent) // use new xml system -SHS { XmlNode cps = xh.FindSection(parent, "ComPortSettings"); comname = xh.GetString(cps, "PortName", "Com1"); speed = xh.GetInt(cps, "Speed", 115200); databits = xh.GetInt(cps, "Databits", 8); parity = (Parity)xh.GetEnum(cps, "Parity", typeof(Parity), Parity.None); stopbits = (StopBits)xh.GetEnum(cps, "Stopbits", typeof(StopBits), StopBits.One); handshake = (Handshake)xh.GetEnum(cps, "Handshake", typeof(Handshake), Handshake.None); return true; }
public SerialPortDriver(int baudRate , int dataBits ,StopBits stopBits, Parity parity , Handshake handShake) { BaudRate = baudRate; DataBits = dataBits; StopBits = stopBits; Parity = parity; Handshake = handShake; sleepOnWrite = int.Parse(ConfigurationSettings.AppSettings["SleepOnWrite"]); ReadTimeout = 10000; WriteTimeout = 10000; }
private void InitPortProperties(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake, int readTimeout, int writeTimeout){ _serialPort.Encoding = Encoding.ASCII; _serialPort.DataReceived += _serialPort_DataReceived; _serialPort.PortName = portName; _serialPort.BaudRate = baudRate; _serialPort.Parity = parity; _serialPort.DataBits = dataBits; _serialPort.StopBits = stopBits; _serialPort.Handshake = handshake; _serialPort.ReadTimeout = readTimeout; _serialPort.WriteTimeout = writeTimeout; }
static SerialPortConfig() { config = new ConfigUtil("Base", @"Ini\serial_port.ini"); servicePort = config.Get("ServicePort"); zigBeeId = config.Get("ZigBeeId"); portName = config.Get("PortName"); portBaudRate = int.Parse(config.Get("BaudRate")); portParity = (Parity)int.Parse(config.Get("Parity")); dataBits = int.Parse(config.Get("DataBits")); portStopBits = (StopBits)int.Parse(config.Get("StopBits")); portHandshake = (Handshake)int.Parse(config.Get("Handshake")); readTimeout = int.Parse(config.Get("ReadTimeout")); writeTimeout = int.Parse(config.Get("WriteTimeout")); }
private void Init(string portName, int baudRate, Parity parity, StopBits stopBits, int dataBits, Handshake handShake) { base.driver.ReadTimeout = 500; base.driver.WriteTimeout = 500; base.driver.ErrorReceived += driver_ErrorReceived; //receiveResponse = true; encode = new System.Text.UTF8Encoding(); response = new StringBuilder(); dataReceived = new StringBuilder(); waitResponse = new AutoResetEvent(false); }
public MyCOMPortClass(String name, int baud, Parity parity, int bits, StopBits stop, Handshake hand) { comport = new SerialPort(); val = new Queue<Int32>(); log = new List<String>(); // Set port parameters comport.PortName = name; //SetPortName (comport.PortName); comport.BaudRate = (int)SetPortBaudRate(baud); comport.Parity = SetPortParity(parity); comport.DataBits = SetPortDataBit(bits); comport.StopBits = SetPortStopBits(stop); comport.Handshake = SetPortHandshake(hand); // Set up timeouts comport.ReadTimeout = 500; comport.WriteTimeout = 500; }
public SerialStream(GenThreadManagement.GenThreadManager genThreadManager, SystemServices systemServices, String portName, int baudRate = 57600, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, Handshake handshake = Handshake.None, int readTimeout = 3000, int writeTimeout = 20000) : base(genThreadManager, systemServices) { SerialPort = new SerialPort(); PortName = portName; BaudRate = baudRate; DataBits = dataBits; StopBits = stopBits; Parity = parity; Handshake = handshake; ReadTimeout = readTimeout; WriteTimeout = writeTimeout; IsOpen = false; ConfigurePort(); }
public AccessCardReader(string comport, int baudrate = 9600, Parity parity = Parity.None, StopBits stopbits = StopBits.One, int databits = 8, Handshake handshake = Handshake.None) { _sPort = new SerialPort(comport); _sPort.BaudRate = baudrate; _sPort.Parity = parity; _sPort.StopBits = stopbits; _sPort.DataBits = databits; _sPort.Handshake = handshake; _sPort.DataReceived += new SerialDataReceivedEventHandler(DataReceviedHandler); }
/// <summary> /// Initializes a new instance of the <see cref="COM_Device" /> class. /// </summary> /// <param name="name">The serial port name.</param> /// <param name="baudrate">The serial port baudrate.</param> /// <param name="databits">The serial port databits.</param> /// <param name="parity">The serial port parity.</param> /// <param name="stopbits">The serial port stopbits.</param> /// <param name="handshake">The serial port handshake.</param> /// <param name="isArduino">if set to <c>true</c> [is arduino] configures the Serial port accordingly.</param> public COM_Device(string name, int baudrate, int databits, Parity parity, StopBits stopbits, Handshake handshake, bool isArduino) { try { // Create the serial port object _com = new SerialPort(name, baudrate, parity, databits, stopbits); // Set-up the serial port parameters passed to the function _name = name; _databits = databits; _baudrate = baudrate; _stopbits = stopbits; _parity = parity; _com.Handshake = handshake; _handshake = handshake; // // If it is an Arduino micro-controller, the USB driver needs to control DTS/RTS if (isArduino) { _com.DtrEnable = true; _com.RtsEnable = true; } // Set-up the Read/Write timeouts _com.ReadTimeout = 5000; _com.WriteTimeout = 500; // Defines the Serial Port received data Handler _com.DataReceived += new SerialDataReceivedEventHandler(RXHandler); // Opens the Serial port _com.Open(); // Set-up a timer used as Timeout when connecting the device timeOut = new Timer(); timeOut.Interval = 5000; timeOut.AutoReset = false; timeOut.Elapsed += new ElapsedEventHandler(timeOut_Elapsed); // Initialize the Queue storing the data received from the Serial Port datain = new Queue<string>(); } catch (Exception ex) { // throw the exception throw ex; } }
public bool Load(XmlReader xr) { try { xr.ReadStartElement("ComPortSettings"); comname = xr.ReadElementString("PortName"); speed = int.Parse(xr.ReadElementString("Speed")); parity = (Parity)Enum.Parse(typeof(Parity), xr.ReadElementString("Parity")); stopbits = (StopBits)Enum.Parse(typeof(StopBits), xr.ReadElementString("Stopbits")); handshake = (Handshake)Enum.Parse(typeof(Handshake), xr.ReadElementString("Handshake")); xr.ReadEndElement(); return true; } catch (Exception ex) { DebugLogger.Instance().LogRecord(ex.Message); return false; } }
public static Handshake SetPortHandshake(Handshake defaultPortHandshake) { string handshake; Console.WriteLine("Available Handshake options:"); foreach (string s in Enum.GetNames(typeof(Handshake))) { Console.WriteLine(" {0}", s); } Console.Write("End Handshake value (Default: {0}):", defaultPortHandshake.ToString()); handshake = Console.ReadLine(); if (handshake == "") { handshake = defaultPortHandshake.ToString(); } return (Handshake)Enum.Parse(typeof(Handshake), handshake, true); }
public autoDetectBaudRate(string _portName, Parity _parity = Parity.None, int _dataBits = 8, StopBits _stopBits = StopBits.None, Handshake _handshake = Handshake.None, int _bytesToEvaluate = 10, int _timeout = 2000) { InitializeComponent(); portName = _portName; //update counter for first round bytesToEvaluate = _bytesToEvaluate; textBlock_sumASCII.Text = "0/" + bytesToEvaluate.ToString(); //set serial port settings _serialPort.PortName = _portName; _serialPort.Parity = _parity; _serialPort.DataBits = 8; _serialPort.StopBits = StopBits.One; _serialPort.Handshake = Handshake.None; _serialPort.ReadTimeout = _timeout; _serialPort.DtrEnable = true; Dispatcher.BeginInvoke(new testBaudDelegate(testBaud)); }
internal WinStream( int baudRate, int dataBits, bool discardNull, bool dtrEnable, Handshake handshake, Parity parity, byte parityReplace, string portName, int readBufferSize, int readTimeout, int receivedBytesThreshold, bool rtsEnable, StopBits stopBits, int writeBufferSize, int writeTimeout) { _port = new OpenNETCF.IO.Serial.Port( portName, readBufferSize, writeBufferSize ); BaudRate = baudRate; DataBits = dataBits; DiscardNull = discardNull; DtrEnable = dtrEnable; Handshake = handshake; Parity = parity; ParityReplace = parityReplace; // TODO: ReadTimeout = readTimeout; ReceivedBytesThreshold = receivedBytesThreshold; RtsEnable = rtsEnable; StopBits = stopBits; // TODO: WriteTimeout = writeTimeout; _port.DataReceived += new OpenNETCF.IO.Serial.Port.CommEvent(_port_DataReceived); _port.OnError += new OpenNETCF.IO.Serial.Port.CommErrorEvent(_port_OnError); _port.RingChange += new OpenNETCF.IO.Serial.Port.CommChangeEvent(_port_RingChange); _port.RLSDChange += new OpenNETCF.IO.Serial.Port.CommChangeEvent(_port_RLSDChange); if( !_port.Open() ) throw new UnauthorizedAccessException(); }
/// <summary> /// Initializes a new instance of the <see cref="COM_Device"/> class. /// </summary> /// <param name="name">Serial Port name</param> public COM_Device(string name) { try { // Create the serial port object _com = new SerialPort(name); // Set-up the parameters of the port _name = name; _baudrate = 9600; _databits = 8; _stopbits = StopBits.One; _parity = Parity.None; _handshake = Handshake.None; // Initialize the connection flag _isConnected = true; // Initialize the Read/Write timeouts _com.ReadTimeout = 5000; _com.WriteTimeout = 500; //_isConnected = true; // Define the handler for the received data from the serial port _com.DataReceived += new SerialDataReceivedEventHandler(RXHandler); // Open the Serial port _com.Open(); // Set-up a timer used for timeout when connecting the device timeOut = new Timer(); timeOut.Interval = 5000; timeOut.AutoReset = false; timeOut.Elapsed += new ElapsedEventHandler(timeOut_Elapsed); // Initialize the Queue of the received data datain = new Queue<string>(); } catch (Exception ex) { // Throw the caught exception throw ex; } }
public DUTCOMPortClass(String name, int baud, Parity parity, int bits, StopBits stop, Handshake hand) : base(name, baud, parity, bits, stop, hand) { //NewAcquisition = false; try { message = string.Empty; comport.Open(); readThread = new Thread (new ThreadStart (this.Read)); isConnected = true; timeout = new System.Windows.Threading.DispatcherTimer(); timeout.Interval = new TimeSpan(0, 0, 10); timeout.Tick+=new EventHandler(timeout_Tick); readThread.Start(); send("\n"); // To initialize Minishell } catch (UnauthorizedAccessException) { throw new UnauthorizedAccessException ("Access denied on this port, COM Port already open"); } catch (ArgumentOutOfRangeException ) { throw new ArgumentOutOfRangeException ("Parity, DataBits, StopBits or Handshake are not valid values\n" + "BaudRate, TimeOuts are less than or equal to zero"); } catch (ArgumentException e) { throw new ArgumentException ("Port name does not begin with COM"); } catch (IOException ) { throw new IOException ("Port is in invalid state"); } catch (InvalidOperationException) { throw new InvalidOperationException ("Specified Port in current instance is already open"); } }
public Communicator(string which, int baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake hand, string newline,bool custom) { port = new SerialPort(which, baudRate, parity, dataBits, stopBits) { Handshake = hand, NewLine = newline }; port.ReadTimeout = 500; port.WriteTimeout = 500; port.Open(); port.DataReceived += port_DataReceived; if (!newline.Equals("None") && !newline.Equals("No Auto")) { parser = new Parser(newline,custom); } else { if (newline.Equals("None")) parser = new Parser("",false); if (newline.Equals("No Auto")) parser = new Parser(new string(new char[]{'\\','r'}),true); } parser.CommandRecognized += CommandRecognized; }
public HamLibWrapperInternal(string rigName, string port, BaudRate baudRate, Handshake handshake, int dataBits, int stopBits) { rig = new CapabilityFakingHamLibRig(new TimeoutRetryingHamLibRig(new HamlibRigLockingFacade(rigName))); rig.Open(port, baudRate, handshake, dataBits, stopBits); }
/// <summary> /// use serial port, set the port name,baud rate,data bits,stopbits,parity /// </summary> /// <param name="portName">serial port name</param> /// <param name="baudRate">serial port baud rate</param> /// <param name="dataBits">serial port data bits</param> /// <param name="StopBits">serial port stopbits</param> /// <param name="Parity">serial port parity</param> /// <param name="handshake">handshake type(hardware )</param> public void InitializeDevice(string portName, int baudRate, int dataBits, StopBits stopBits, Parity parity, Handshake handshake) { ResetDevice(); if (null != _connectedSerialPort) { _connectedSerialPort.PortName = portName; _connectedSerialPort.BaudRate = baudRate; _connectedSerialPort.DataBits = dataBits; _connectedSerialPort.StopBits = stopBits; _connectedSerialPort.Parity = parity; _connectedSerialPort.Handshake = handshake; } }
public void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { AsyncWriteRndStr asyncWriteRndStr = new AsyncWriteRndStr(com1, STRING_SIZE_HANDSHAKE); Thread t = new Thread(asyncWriteRndStr.WriteRndStr); byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; int numNewLineBytes; int waitTime; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); //Setup to ensure write will bock with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } //Write a random string asynchronously so we can verify some things while the write call is blocking t.Start(); waitTime = 0; while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start Thread.Sleep(50); waitTime += 50; } waitTime = 0; while (STRING_SIZE_HANDSHAKE + numNewLineBytes > com1.BytesToWrite && waitTime < 500) { Thread.Sleep(50); waitTime += 50; } //Verify that the correct number of bytes are in the buffer if (STRING_SIZE_HANDSHAKE + numNewLineBytes != com1.BytesToWrite) { Fail("ERROR!!! Expcted BytesToWrite={0} actual {1}", STRING_SIZE_HANDSHAKE, com1.BytesToWrite); } //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); } //Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.Write(XOnBuffer, 0, 1); } //Wait till write finishes while (t.IsAlive) { Thread.Sleep(100); } Assert.Equal(0, com1.BytesToWrite); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); } } }
/** * Class constructor. Instantiates a new {@code Raw802Device} object in the * given serial port name and settings. * * @param port Serial port name where 802.15.4 device is attached to. * @param baudRate Serial port baud rate to communicate with the device. * @param dataBits Serial port data bits. * @param stopBits Serial port data bits. * @param parity Serial port data bits. * @param flowControl Serial port data bits. * * @throws ArgumentException if {@code baudRate < 0} or * if {@code dataBits < 0} or * if {@code stopBits < 0} or * if {@code parity < 0} or * if {@code flowControl < 0}. * @throws ArgumentNullException if {@code port == null}. */ public Raw802Device(string port, int baudRate, int dataBits, StopBits stopBits, Parity parity, Handshake flowControl) : this(port, new SerialPortParameters(baudRate, dataBits, stopBits, parity, flowControl)) { }
/// <summary> /// RecvMessage事件,并存入消息处理队列_revBSSMsg /// </summary> /// <param name="sender"></param> /// <param name="e"></param> #region private void tsh_RecvMessage(object sender, NetEventArgs e) { //<LoginMsg> // <RoutID>3201</RoutID> // <TLX>PDEP</TLX> // <TName>江苏省交换服务器</TName> //</LoginMsg> try { int msgno = e.msgEntity.msgH.msgID; string body = Encoding.Default.GetString(e.msgEntity.msgB); dtLastRecieveMsgTime = DateTime.Now; LogHelper.WriteSevNetMsgLog(body); switch (msgno) { case 1000: //Handshake Handshake hk = new Handshake(); hk = (Handshake)JSON.JsonToObject(body,hk); if (hk != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.Handshake, hk, body)); break; case 1002: //LoginReponse LoginResponse lr = new LoginResponse(); lr = (LoginResponse)JSON.JsonToObject(body,lr); if (lr != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.LoginResponse, lr, body)); break; case 1004: //LoginoffReponse LogoffResponse lfr = new LogoffResponse(); lfr = (LogoffResponse)JSON.JsonToObject(body,lfr); if (lfr != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.LogoffResponse, lfr, body)); break; case 7001: //DispatchCarNotice DispatchCarNotice pc = new DispatchCarNotice(); pc=(DispatchCarNotice)JSON.JsonToObject(body,pc); if (pc != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.DispatchCarNotice, pc, body)); break; case 7002: //VehicleStatusResponse VehicleStatusResponse vs = new VehicleStatusResponse(); vs = (VehicleStatusResponse)JSON.JsonToObject(body, vs); if (vs != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.VehicleStatusResponse, vs, body)); break; case 7004: //VehiclePointResponse VehiclePointResponse vp = new VehiclePointResponse(); vp = (VehiclePointResponse)JSON.JsonToObject(body, vp); if (vp != null) _revBSSMsg.Enqueue(new DesMsg(DesMsgType.VehiclePointResponse, vp, body)); break; default: break; } } catch (Exception ex) { LOG.LogHelper.WriteLog("", ex); } }
public void SetAttributes(int baud_rate, Parity parity, int data_bits, StopBits sb, Handshake hs) { if (!set_attributes(fd, baud_rate, parity, data_bits, sb, hs)) { ThrowIOException(); } }
private void Verify_Handshake(Handshake handshake) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { var asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1, s_BYTE_SIZE_HANDSHAKE); var t = new Task(asyncWriteRndByteArray.WriteRndByteArray); var XOffBuffer = new byte[1]; var XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); // Setup to ensure write will bock with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } // Write a random byte asynchronously so we can verify some things while the write call is blocking t.Start(); TCSupport.WaitForTaskToStart(t); TCSupport.WaitForWriteBufferToLoad(com1, s_BYTE_SIZE_HANDSHAKE); // Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", false, com1.CtsHolding); } // Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.Write(XOnBuffer, 0, 1); } TCSupport.WaitForTaskCompletion(t); // Verify that the correct number of bytes are in the buffer Assert.Equal(0, com1.BytesToWrite); // Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { Fail("ERROR!!! Expected CtsHolding={0} actual {1}", true, com1.CtsHolding); } } #endregion }
public void SetAttributes(int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs) { DCB dcb = new DCB(); if (!GetCommState(handle, dcb)) { ReportIOError(null); } dcb.SetValues(baud_rate, parity, data_bits, bits, hs); if (!SetCommState(handle, dcb)) { ReportIOError(null); } }
public void OnHandshake(NetworkConnection negotiated, Handshake handshake) { }
// this method is used by SerialPort upon SerialStream's creation internal SerialStream(string portName, int baudRate, Parity parity, int dataBits, StopBits stopBits, int readTimeout, int writeTimeout, Handshake handshake, bool dtrEnable, bool rtsEnable, bool discardNull, byte parityReplace) { if (portName == null) { throw new ArgumentNullException(nameof(portName)); } CheckBaudRate(baudRate); // Error checking done in SerialPort. SafeSerialDeviceHandle tempHandle = SafeSerialDeviceHandle.Open(portName); try { _handle = tempHandle; // set properties of the stream that exist as members in SerialStream _portName = portName; _handshake = handshake; _parity = parity; _readTimeout = readTimeout; _writeTimeout = writeTimeout; _baudRate = baudRate; _stopBits = stopBits; _dataBits = dataBits; if (Interop.Termios.TermiosReset(_handle, _baudRate, _dataBits, _stopBits, _parity, _handshake) != 0) { throw new ArgumentException(); } DtrEnable = dtrEnable; BaudRate = baudRate; // now set this.RtsEnable to the specified value. // Handshake takes precedence, this will be a nop if // handshake is either RequestToSend or RequestToSendXOnXOff if ((handshake != Handshake.RequestToSend && handshake != Handshake.RequestToSendXOnXOff)) { // query and cache the initial RtsEnable value // so that set_RtsEnable can do the (value != rtsEnable) optimization _rtsEnable = RtsEnabledNative(); RtsEnable = rtsEnable; } } catch { // if there are any exceptions after the call to CreateFile, we need to be sure to close the // handle before we let them continue up. tempHandle.Dispose(); _handle = null; throw; } _processReadDelegate = ProcessRead; _processWriteDelegate = ProcessWrite; _lastTotalBytesAvailable = TotalBytesAvailable; }
/// <summary> /// Saves the passed port parameters. /// Called when the user clicks OK on PortSettingsDialog. /// </summary> private void SetPortParameters(string userPort, int userBitRate, Handshake userHandshake) { try { // Don't do anything if the system has no COM ports. if (ComPorts.comPortExists) { if (MyPortSettingsDialog.ParameterChanged()) { // One or more port parameters has changed. if ((string.Compare(MyPortSettingsDialog.oldPortName, userPort, true) != 0)) { // The port has changed. // Close the previously selected port. UserPort1.PreviousPort = UserPort1.SelectedPort; UserPort1.CloseComPort(UserPort1.SelectedPort); // Set SelectedPort to the current port. UserPort1.SelectedPort.PortName = userPort; UserPort1.PortChanged = true; } // Set other port parameters. UserPort1.SelectedPort.BaudRate = userBitRate; UserPort1.SelectedPort.Handshake = userHandshake; MyPortSettingsDialog.SavePortParameters(); UserPort1.ParameterChanged = true; } else { UserPort1.ParameterChanged = false; } } } catch (InvalidOperationException ex) { UserPort1.ParameterChanged = true; DisplayException(ModuleName, ex); } catch (UnauthorizedAccessException ex) { UserPort1.ParameterChanged = true; DisplayException(ModuleName, ex); // This exception can occur if the port was removed. // If the port was open, close it. UserPort1.CloseComPort(UserPort1.SelectedPort); } catch (System.IO.IOException ex) { UserPort1.ParameterChanged = true; DisplayException(ModuleName, ex); } }
//const int fAbortOnError = 0x4000; public void SetValues (int baud_rate, Parity parity, int byte_size, StopBits sb, Handshake hs) { switch (sb) { case StopBits.One: stop_bits = 0; break; case StopBits.OnePointFive: stop_bits = 1; break; case StopBits.Two: stop_bits = 2; break; default: // Shouldn't happen break; } this.baud_rate = baud_rate; this.parity = (byte)parity; this.byte_size = (byte)byte_size; // Clear Handshake flags flags &= ~(fOutxCtsFlow | fOutX | fInX | fRtsControl2); // Set Handshake flags switch (hs) { case Handshake.None: break; case Handshake.XOnXOff: flags |= fOutX | fInX; break; case Handshake.RequestToSend: flags |= fOutxCtsFlow | fRtsControl2; break; case Handshake.RequestToSendXOnXOff: flags |= fOutxCtsFlow | fOutX | fInX | fRtsControl2; break; default: // Shouldn't happen break; } }
public bool Verify_Handshake(Handshake handshake) { SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); AsyncWriteRndByteArray asyncWriteRndByteArray = new AsyncWriteRndByteArray(com1); System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(asyncWriteRndByteArray.WriteRndByteArray)); bool retValue = true; int waitTime = 0; Console.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); //Setup to ensure write will bock with type of handshake method being used if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = false; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte((byte)19); System.Threading.Thread.Sleep(250); } //Write a random byte asynchronously so we can verify some things while the write call is blocking t.Start(); waitTime = 0; while (t.ThreadState == System.Threading.ThreadState.Unstarted && waitTime < 2000) { //Wait for the thread to start System.Threading.Thread.Sleep(50); waitTime += 50; } waitTime = 0; while (com1.BytesToWrite < 1 && waitTime < 250) { System.Threading.Thread.Sleep(50); waitTime += 50; } //Verify that the correct number of bytes are in the buffer if (1 != com1.BytesToWrite) { retValue = false; Console.WriteLine("ERROR!!! Expcted BytesToWrite={0} actual {1}", 1, com1.BytesToWrite); } //Verify that CtsHolding is false if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && com1.CtsHolding) { retValue = false; Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", false, com1.CtsHolding); } //Setup to ensure write will succeed if (Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.RtsEnable = true; } if (Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake) { com2.BaseStream.WriteByte((byte)17); } //Wait till write finishes while (t.IsAlive) { System.Threading.Thread.Sleep(100); } //Verify that the correct number of bytes are in the buffer if (0 != com1.BytesToWrite) { retValue = false; Console.WriteLine("ERROR!!! Expcted BytesToWrite=0 actual {0}", com1.BytesToWrite); } //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if ((Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake) && !com1.CtsHolding) { retValue = false; Console.WriteLine("ERROR!!! Expcted CtsHolding={0} actual {1}", true, com1.CtsHolding); } if (com1.IsOpen) { com1.Close(); } if (com2.IsOpen) { com2.Close(); } return(retValue); }
/// <summary> /// /// </summary> /// <param name="portName"></param> /// <param name="baudRate"></param> /// <param name="parity"></param> /// <param name="dataBits"></param> /// <param name="stopBits"></param> /// <param name="handshake"></param> /// <param name="readTimeout"></param> /// <param name="writeTimeout"></param> /// <param name="readBufferSize"></param> /// <param name="writeBufferSize"></param> public modemSettings(string portName, long baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake , int readTimeout, int writeTimeout, int readBufferSize, int writeBufferSize , bool dtrEnable, bool rtsEnable , comm.consts.modemDirection modemDirection) { this.portName = portName; this.baudRate = baudRate; this.parity = parity; this.stopBits = stopBits; this.dataBits = dataBits; this.handshake = handshake; this.readTimeOut = readTimeout; this.writeTimeOut = writeTimeout; this.dtrEnable = dtrEnable; this.rtsEnable = rtsEnable; this.modemDirection = (comm.consts.modemDirection)modemDirection; }
//const int fAbortOnError = 0x4000; public void SetValues(int baud_rate, Parity parity, int byte_size, StopBits sb, Handshake hs) { switch (sb) { case StopBits.One: stop_bits = 0; break; case StopBits.OnePointFive: stop_bits = 1; break; case StopBits.Two: stop_bits = 2; break; default: // Shouldn't happen break; } this.baud_rate = baud_rate; this.parity = (byte)parity; this.byte_size = (byte)byte_size; // Clear Handshake flags flags &= ~(fOutxCtsFlow | fOutX | fInX | fRtsControl2); // Set Handshake flags switch (hs) { case Handshake.None: break; case Handshake.XOnXOff: flags |= fOutX | fInX; break; case Handshake.RequestToSend: flags |= fOutxCtsFlow | fRtsControl2; break; case Handshake.RequestToSendXOnXOff: flags |= fOutxCtsFlow | fOutX | fInX | fRtsControl2; break; default: // Shouldn't happen break; } }
public async Task ConnectAsync() { if (hasConnected) { return; } var client = CreateTcpClient(); client.NoDelay = NoDelay; client.ReceiveTimeout = ReceiveTimeout; client.SendTimeout = SendTimeout; client.ExclusiveAddressUse = ExclusiveAddressUse; await client.ConnectAsync(uri.Host, uri.Port); var stream = await GetRtmpStreamAsync(client); var random = new Random(); var randomBytes = new byte[1528]; random.NextBytes(randomBytes); // write c0+c1 var c01 = new Handshake() { Version = 3, Time = (uint)Environment.TickCount, Time2 = 0, Random = randomBytes }; await Handshake.WriteAsync(stream, c01, true); // read s0+s1 var s01 = await Handshake.ReadAsync(stream, true); // write c2 var c2 = s01.Clone(); c2.Time2 = (uint)Environment.TickCount; await Handshake.WriteAsync(stream, c2, false); // read s2 var s2 = await Handshake.ReadAsync(stream, false); // handshake check if (!c01.Random.SequenceEqual(s2.Random) || c01.Time != s2.Time) { throw new ProtocolViolationException(); } writer = new RtmpPacketWriter(new AmfWriter(stream, context), ObjectEncoding.Amf3); reader = new RtmpPacketReader(new AmfReader(stream, context)); reader.EventReceived += EventReceivedCallback; reader.Disconnected += OnPacketProcessorDisconnected; writer.Disconnected += OnPacketProcessorDisconnected; writerThread = new Thread(reader.ReadLoop) { IsBackground = true }; readerThread = new Thread(writer.WriteLoop) { IsBackground = true }; writerThread.Start(); readerThread.Start(); // call `connect` var connectResult = await ConnectInvokeAsync(null, null, uri.ToString()); object cId; if (connectResult.TryGetValue("clientId", out cId)) { ClientId = cId as string; } hasConnected = true; }
public CommSettings(int bitrate, int databits, Parity parity, StopBits stopbits, Handshake handshake) { _bitrate = bitrate; _databits = databits; _parity = parity; _stopbits = stopbits; _handshake = handshake; }
/// <summary> /// This method handles the asynchronous message pump. It waits for messages to show up on the queue /// and calls FireDataAvailable for each such packet. It will terminate when the terminate event is /// set. /// </summary> private void PacketPumpProc() { NamedPipeServerStream localPipeServer = _pipeServer; AutoResetEvent localPacketAvailable = _packetAvailable; AutoResetEvent localTerminatePacketPump = _terminatePacketPump; ConcurrentQueue <INodePacket> localPacketQueue = _packetQueue; DateTime originalWaitStartTime = DateTime.UtcNow; bool gotValidConnection = false; while (!gotValidConnection) { gotValidConnection = true; DateTime restartWaitTime = DateTime.UtcNow; // We only wait to wait the difference between now and the last original start time, in case we have multiple hosts attempting // to attach. This prevents each attempt from resetting the timer. TimeSpan usedWaitTime = restartWaitTime - originalWaitStartTime; int waitTimeRemaining = Math.Max(0, CommunicationsUtilities.NodeConnectionTimeout - (int)usedWaitTime.TotalMilliseconds); try { // Wait for a connection #if FEATURE_APM IAsyncResult resultForConnection = localPipeServer.BeginWaitForConnection(null, null); CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining); bool connected = resultForConnection.AsyncWaitHandle.WaitOne(waitTimeRemaining, false); #else Task connectionTask = localPipeServer.WaitForConnectionAsync(); CommunicationsUtilities.Trace("Waiting for connection {0} ms...", waitTimeRemaining); bool connected = connectionTask.Wait(waitTimeRemaining); #endif if (!connected) { CommunicationsUtilities.Trace("Connection timed out waiting a host to contact us. Exiting comm thread."); ChangeLinkStatus(LinkStatus.ConnectionFailed); return; } CommunicationsUtilities.Trace("Parent started connecting. Reading handshake from parent"); #if FEATURE_APM localPipeServer.EndWaitForConnection(resultForConnection); #endif // The handshake protocol is a series of int exchanges. The host sends us a each component, and we // verify it. Afterwards, the host sends an "End of Handshake" signal, to which we respond in kind. // Once the handshake is complete, both sides can be assured the other is ready to accept data. Handshake handshake = GetHandshake(); try { int[] handshakeComponents = handshake.RetrieveHandshakeComponents(); for (int i = 0; i < handshakeComponents.Length; i++) { int handshakePart = _pipeServer.ReadIntForHandshake(i == 0 ? (byte?)CommunicationsUtilities.handshakeVersion : null /* this will disconnect a < 16.8 host; it expects leading 00 or F5 or 06. 0x00 is a wildcard */ #if NETCOREAPP2_1_OR_GREATER || MONO , ClientConnectTimeout /* wait a long time for the handshake from this side */ #endif ); if (handshakePart != handshakeComponents[i]) { CommunicationsUtilities.Trace("Handshake failed. Received {0} from host not {1}. Probably the host is a different MSBuild build.", handshakePart, handshakeComponents[i]); _pipeServer.WriteIntForHandshake(i + 1); gotValidConnection = false; break; } } if (gotValidConnection) { // To ensure that our handshake and theirs have the same number of bytes, receive and send a magic number indicating EOS. #if NETCOREAPP2_1_OR_GREATER || MONO _pipeServer.ReadEndOfHandshakeSignal(false, ClientConnectTimeout); /* wait a long time for the handshake from this side */ #else _pipeServer.ReadEndOfHandshakeSignal(false); #endif CommunicationsUtilities.Trace("Successfully connected to parent."); _pipeServer.WriteEndOfHandshakeSignal(); #if FEATURE_SECURITY_PERMISSIONS // We will only talk to a host that was started by the same user as us. Even though the pipe access is set to only allow this user, we want to ensure they // haven't attempted to change those permissions out from under us. This ensures that the only way they can truly gain access is to be impersonating the // user we were started by. WindowsIdentity currentIdentity = WindowsIdentity.GetCurrent(); WindowsIdentity clientIdentity = null; localPipeServer.RunAsClient(delegate() { clientIdentity = WindowsIdentity.GetCurrent(true); }); if (clientIdentity == null || !String.Equals(clientIdentity.Name, currentIdentity.Name, StringComparison.OrdinalIgnoreCase)) { CommunicationsUtilities.Trace("Handshake failed. Host user is {0} but we were created by {1}.", (clientIdentity == null) ? "<unknown>" : clientIdentity.Name, currentIdentity.Name); gotValidConnection = false; continue; } #endif } } catch (IOException e) { // We will get here when: // 1. The host (OOP main node) connects to us, it immediately checks for user privileges // and if they don't match it disconnects immediately leaving us still trying to read the blank handshake // 2. The host is too old sending us bits we automatically reject in the handshake // 3. We expected to read the EndOfHandshake signal, but we received something else CommunicationsUtilities.Trace("Client connection failed but we will wait for another connection. Exception: {0}", e.Message); gotValidConnection = false; } catch (InvalidOperationException) { gotValidConnection = false; } if (!gotValidConnection) { if (localPipeServer.IsConnected) { localPipeServer.Disconnect(); } continue; } ChangeLinkStatus(LinkStatus.Active); } catch (Exception e) { if (ExceptionHandling.IsCriticalException(e)) { throw; } CommunicationsUtilities.Trace("Client connection failed. Exiting comm thread. {0}", e); if (localPipeServer.IsConnected) { localPipeServer.Disconnect(); } ExceptionHandling.DumpExceptionToFile(e); ChangeLinkStatus(LinkStatus.Failed); return; } } RunReadLoop( new BufferedReadStream(_pipeServer), _pipeServer, localPacketQueue, localPacketAvailable, localTerminatePacketPump); CommunicationsUtilities.Trace("Ending read loop"); try { if (localPipeServer.IsConnected) { #if NETCOREAPP // OperatingSystem.IsWindows() is new in .NET 5.0 if (OperatingSystem.IsWindows()) #endif { localPipeServer.WaitForPipeDrain(); } localPipeServer.Disconnect(); } } catch (Exception) { // We don't really care if Disconnect somehow fails, but it gives us a chance to do the right thing. } }
/// <summary> /// Attempts to connect to the specified process. /// </summary> private Stream TryConnectToProcess(int nodeProcessId, int timeout, Handshake handshake) { // Try and connect to the process. string pipeName = NamedPipeUtil.GetPipeNameOrPath("MSBuild" + nodeProcessId); NamedPipeClientStream nodeStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, PipeOptions.Asynchronous #if FEATURE_PIPEOPTIONS_CURRENTUSERONLY | PipeOptions.CurrentUserOnly #endif ); CommunicationsUtilities.Trace("Attempting connect to PID {0} with pipe {1} with timeout {2} ms", nodeProcessId, pipeName, timeout); try { nodeStream.Connect(timeout); #if !FEATURE_PIPEOPTIONS_CURRENTUSERONLY if (NativeMethodsShared.IsWindows && !NativeMethodsShared.IsMono) { // Verify that the owner of the pipe is us. This prevents a security hole where a remote node has // been faked up with ACLs that would let us attach to it. It could then issue fake build requests back to // us, potentially causing us to execute builds that do harmful or unexpected things. The pipe owner can // only be set to the user's own SID by a normal, unprivileged process. The conditions where a faked up // remote node could set the owner to something else would also let it change owners on other objects, so // this would be a security flaw upstream of us. ValidateRemotePipeSecurityOnWindows(nodeStream); } #endif int[] handshakeComponents = handshake.RetrieveHandshakeComponents(); for (int i = 0; i < handshakeComponents.Length; i++) { CommunicationsUtilities.Trace("Writing handshake part {0} to pipe {1}", i, pipeName); nodeStream.WriteIntForHandshake(handshakeComponents[i]); } // This indicates that we have finished all the parts of our handshake; hopefully the endpoint has as well. nodeStream.WriteEndOfHandshakeSignal(); CommunicationsUtilities.Trace("Reading handshake from pipe {0}", pipeName); #if NETCOREAPP2_1 || MONO nodeStream.ReadEndOfHandshakeSignal(true, timeout); #else nodeStream.ReadEndOfHandshakeSignal(true); #endif // We got a connection. CommunicationsUtilities.Trace("Successfully connected to pipe {0}...!", pipeName); return(nodeStream); } catch (Exception e) when(!ExceptionHandling.IsCriticalException(e)) { // Can be: // UnauthorizedAccessException -- Couldn't connect, might not be a node. // IOException -- Couldn't connect, already in use. // TimeoutException -- Couldn't connect, might not be a node. // InvalidOperationException – Couldn’t connect, probably a different build CommunicationsUtilities.Trace("Failed to connect to pipe {0}. {1}", pipeName, e.Message.TrimEnd()); // If we don't close any stream, we might hang up the child nodeStream?.Dispose(); } return(null); }
public async Task <int> HandshakeAsync(Socket client_socket) { Stream stream; if (cert != null) { var temp_stream = new SslStream(new NetworkStream(client_socket)); try { await temp_stream.AuthenticateAsServerAsync(cert); } catch (AuthenticationException) { temp_stream.Close(); throw; } stream = temp_stream; } else { stream = new NetworkStream(client_socket); } var randomBytes = new byte[1528]; random.NextBytes(randomBytes); client_socket.NoDelay = true; var s01 = new Handshake() { Version = 3, Time = (uint)Environment.TickCount, Time2 = 0, Random = randomBytes }; CancellationTokenSource cts = new CancellationTokenSource(); Timer timer = new Timer((s) => { cts.Cancel(); throw new TimeoutException(); }, null, ReceiveTimeout, Timeout.Infinite); var c01 = await Handshake.ReadAsync(stream, true, cts.Token); timer.Change(Timeout.Infinite, Timeout.Infinite); timer.Change(ReceiveTimeout, Timeout.Infinite); await Handshake.WriteAsync(stream, s01, true, cts.Token); timer.Change(Timeout.Infinite, Timeout.Infinite); // read c2 timer.Change(SendTimeout, Timeout.Infinite); var c2 = await Handshake.ReadAsync(stream, false, cts.Token); timer.Change(Timeout.Infinite, Timeout.Infinite); // write s2 var s2 = c01.Clone(); // s2.Time2 = (uint)Environment.TickCount; timer.Change(ReceiveTimeout, Timeout.Infinite); await Handshake.WriteAsync(stream, s2, false, cts.Token); timer.Change(Timeout.Infinite, Timeout.Infinite); // handshake check if (!c01.Random.SequenceEqual(s2.Random)) { throw new ProtocolViolationException(); } ushort client_id = GetNewClientId(); var connect = new RtmpConnect(client_socket, stream, this, client_id, context, objectEncoding, true); connect.ChannelDataReceived += sendDataHandler; prepare_to_add.Add(new KeyValuePair <ushort, StreamConnectState>(client_id, new StreamConnectState() { Connect = connect, LastPing = DateTime.UtcNow, ReaderTask = null, WriterTask = null })); return(client_id); }
public static void Main(string[] args) { mAlive = true; DateTime InitStart = DateTime.Now; // Set up basic output, configuration, etc Output.InitializeStream(true, OutputLevel.DebugInformation); Output.WriteLine("Initializing Snowlight..."); ConfigManager.Initialize(Constants.DataFileDirectory + "\\server-main.cfg"); Output.SetVerbosityLevel((OutputLevel)ConfigManager.GetValue("output.verbositylevel")); // Process args foreach (string arg in args) { Output.WriteLine("Command line argument: " + arg); Input.ProcessInput(arg.Split(' ')); } try { // Initialize and test database Output.WriteLine("Initializing MySQL manager..."); SqlDatabaseManager.Initialize(); // Initialize network components Output.WriteLine("Setting up server listener on port " + (int)ConfigManager.GetValue("net.bind.port") + "..."); mServer = new SnowTcpListener(new IPEndPoint(IPAddress.Any, (int)ConfigManager.GetValue("net.bind.port")), (int)ConfigManager.GetValue("net.backlog"), new OnNewConnectionCallback( SessionManager.HandleIncomingConnection)); using (SqlDatabaseClient MySqlClient = SqlDatabaseManager.GetClient()) { Output.WriteLine("Resetting database counters and statistics..."); PerformDatabaseCleanup(MySqlClient); Output.WriteLine("Initializing game components and workers..."); // Core DataRouter.Initialize(); // Sessions, characters Handshake.Initialize(); GlobalHandler.Initialize(); SessionManager.Initialize(); CharacterInfoLoader.Initialize(); RightsManager.Initialize(MySqlClient); SingleSignOnAuthenticator.Initialize(); // Room management and navigator RoomManager.Initialize(MySqlClient); RoomInfoLoader.Initialize(); RoomHandler.Initialize(); RoomItemHandler.Initialize(); Navigator.Initialize(MySqlClient); // Help and moderation HelpTool.Initialize(MySqlClient); ModerationPresets.Initialize(MySqlClient); ModerationTicketManager.Initialize(MySqlClient); ModerationHandler.Initialize(); ModerationBanManager.Initialize(MySqlClient); // Catalog, pets and items ItemDefinitionManager.Initialize(MySqlClient); CatalogManager.Initialize(MySqlClient); CatalogPurchaseHandler.Initialize(); Inventory.Initialize(); ItemEventDispatcher.Initialize(); PetDataManager.Initialize(MySqlClient); // Messenger MessengerHandler.Initialize(); // Achievements and quests AchievementManager.Initialize(MySqlClient); QuestManager.Initialize(MySqlClient); // Misc/extras CrossdomainPolicy.Initialize("Data\\crossdomain.xml"); InfobusManager.Initialize(); ActivityPointsWorker.Initialize(); BotManager.Initialize(MySqlClient); InterstitialManager.Initialize(MySqlClient); ChatEmotions.Initialize(); EffectsCacheWorker.Initialize(); RecyclerManager.Initialize(MySqlClient); DrinkSetManager.Initialize(MySqlClient); SongManager.Initialize(); TradeHandler.Initialize(); RandomGenerator.Initialize(); StatisticsSyncUtil.Initialize(); // Polish WarningSurpressors.Initialize(); } } catch (Exception e) { HandleFatalError("Could not initialize Snowlight: " + e.Message + "\n" + e.StackTrace); return; } // Init complete TimeSpan TimeSpent = DateTime.Now - InitStart; Output.WriteLine("The server has initialized successfully (" + Math.Round(TimeSpent.TotalSeconds, 2) + " seconds). Ready for connections.", OutputLevel.Notification); Output.WriteLine("Press the ENTER key for command input. Shut down server with 'STOP' command.", OutputLevel.Notification); Console.Beep(); Input.Listen(); // This will make the main thread process console while Program.Alive. }
/// <summary> /// Finds or creates a child process which can act as a node. /// </summary> /// <returns>The pipe stream representing the node.</returns> protected NodeContext GetNode(string msbuildLocation, string commandLineArgs, int nodeId, INodePacketFactory factory, Handshake hostHandshake, NodeContextTerminateDelegate terminateNode) { #if DEBUG if (Execution.BuildManager.WaitForDebugger) { commandLineArgs += " /wfd"; } #endif if (String.IsNullOrEmpty(msbuildLocation)) { msbuildLocation = _componentHost.BuildParameters.NodeExeLocation; } if (String.IsNullOrEmpty(msbuildLocation)) { string msbuildExeName = Environment.GetEnvironmentVariable("MSBUILD_EXE_NAME"); if (!String.IsNullOrEmpty(msbuildExeName)) { // we assume that MSBUILD_EXE_NAME is, in fact, just the name. msbuildLocation = Path.Combine(msbuildExeName, ".exe"); } } #if FEATURE_NODE_REUSE // Try to connect to idle nodes if node reuse is enabled. if (_componentHost.BuildParameters.EnableNodeReuse) { (string expectedProcessName, List <Process> processes)runningNodesTuple = GetPossibleRunningNodes(msbuildLocation); CommunicationsUtilities.Trace("Attempting to connect to each existing {1} process in turn to establish node {0}...", nodeId, runningNodesTuple.expectedProcessName); foreach (Process nodeProcess in runningNodesTuple.processes) { if (nodeProcess.Id == Process.GetCurrentProcess().Id) { continue; } // Get the full context of this inspection so that we can always skip this process when we have the same taskhost context string nodeLookupKey = GetProcessesToIgnoreKey(hostHandshake, nodeProcess.Id); if (_processesToIgnore.Contains(nodeLookupKey)) { continue; } // We don't need to check this again _processesToIgnore.Add(nodeLookupKey); // Attempt to connect to each process in turn. Stream nodeStream = TryConnectToProcess(nodeProcess.Id, 0 /* poll, don't wait for connections */, hostHandshake); if (nodeStream != null) { // Connection successful, use this node. CommunicationsUtilities.Trace("Successfully connected to existed node {0} which is PID {1}", nodeId, nodeProcess.Id); return(new NodeContext(nodeId, nodeProcess.Id, nodeStream, factory, terminateNode)); } } } #endif // None of the processes we tried to connect to allowed a connection, so create a new one. // We try this in a loop because it is possible that there is another MSBuild multiproc // host process running somewhere which is also trying to create nodes right now. It might // find our newly created node and connect to it before we get a chance. CommunicationsUtilities.Trace("Could not connect to existing process, now creating a process..."); int retries = NodeCreationRetries; while (retries-- > 0) { #if FEATURE_NET35_TASKHOST // We will also check to see if .NET 3.5 is installed in the case where we need to launch a CLR2 OOP TaskHost. // Failure to detect this has been known to stall builds when Windows pops up a related dialog. // It's also a waste of time when we attempt several times to launch multiple MSBuildTaskHost.exe (CLR2 TaskHost) // nodes because we should never be able to connect in this case. string taskHostNameForClr2TaskHost = Path.GetFileNameWithoutExtension(NodeProviderOutOfProcTaskHost.TaskHostNameForClr2TaskHost); if (Path.GetFileNameWithoutExtension(msbuildLocation).Equals(taskHostNameForClr2TaskHost, StringComparison.OrdinalIgnoreCase)) { if (FrameworkLocationHelper.GetPathToDotNetFrameworkV35(DotNetFrameworkArchitecture.Current) == null) { CommunicationsUtilities.Trace ( "Failed to launch node from {0}. The required .NET Framework v3.5 is not installed or enabled. CommandLine: {1}", msbuildLocation, commandLineArgs ); string nodeFailedToLaunchError = ResourceUtilities.GetResourceString("TaskHostNodeFailedToLaunchErrorCodeNet35NotInstalled"); throw new NodeFailedToLaunchException(null, nodeFailedToLaunchError); } } #endif // Create the node process int msbuildProcessId = LaunchNode(msbuildLocation, commandLineArgs); _processesToIgnore.Add(GetProcessesToIgnoreKey(hostHandshake, msbuildProcessId)); // Note, when running under IMAGEFILEEXECUTIONOPTIONS registry key to debug, the process ID // gotten back from CreateProcess is that of the debugger, which causes this to try to connect // to the debugger process. Instead, use MSBUILDDEBUGONSTART=1 // Now try to connect to it. Stream nodeStream = TryConnectToProcess(msbuildProcessId, TimeoutForNewNodeCreation, hostHandshake); if (nodeStream != null) { // Connection successful, use this node. CommunicationsUtilities.Trace("Successfully connected to created node {0} which is PID {1}", nodeId, msbuildProcessId); return(new NodeContext(nodeId, msbuildProcessId, nodeStream, factory, terminateNode)); } } // We were unable to launch a node. CommunicationsUtilities.Trace("FAILED TO CONNECT TO A CHILD NODE"); return(null); }
public CommSettings(string settings) { _handshake = Handshake.None; _parity = Parity.None; _stopbits = StopBits.One; _databits = 8; _bitrate = 38400; string[] t = settings.Split(':'); if (t.Length >= 1) { int.TryParse(t[0], out _bitrate); } if (t.Length >= 2) { int.TryParse(t[1], out _databits); } if (t.Length >= 3) { switch (t[2].ToUpper()) { case "O": _parity = Parity.Odd; break; case "E": _parity = Parity.Even; break; case "N": default: break; } } if (t.Length >= 4) { switch (t[3]) { case "1.5": _stopbits = StopBits.OnePointFive; break; case "2": _stopbits = StopBits.Two; break; case "1": default: _stopbits = StopBits.One; break; } } if (t.Length >= 5) { switch (t[4].ToUpper()) { case "HW": _handshake = Handshake.RequestToSend; break; case "XON": _handshake = Handshake.XOnXOff; break; case "": default: break; } } }
public WinSerialStream(string port_name, int baud_rate, int data_bits, Parity parity, StopBits sb, bool dtr_enable, bool rts_enable, Handshake hs, int read_timeout, int write_timeout, int read_buffer_size, int write_buffer_size) { handle = CreateFile(port_name, GenericRead | GenericWrite, 0, 0, OpenExisting, FileFlagOverlapped, 0); if (handle == -1) { ReportIOError(port_name); } // Set port low level attributes SetAttributes(baud_rate, parity, data_bits, sb, hs); // Clean buffers and set sizes if (!PurgeComm(handle, PurgeRxClear | PurgeTxClear) || !SetupComm(handle, read_buffer_size, write_buffer_size)) { ReportIOError(null); } // Set timeouts this.read_timeout = read_timeout; this.write_timeout = write_timeout; timeouts = new Timeouts(read_timeout, write_timeout); if (!SetCommTimeouts(handle, timeouts)) { ReportIOError(null); } /// Set DTR and RTS SetSignal(SerialSignal.Dtr, dtr_enable); if (hs != Handshake.RequestToSend && hs != Handshake.RequestToSendXOnXOff) { SetSignal(SerialSignal.Rts, rts_enable); } // Init overlapped structures NativeOverlapped wo = new NativeOverlapped(); write_event = new ManualResetEvent(false); #if NET_2_0 wo.EventHandle = write_event.Handle; #else wo.EventHandle = (int)write_event.Handle; #endif write_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped))); Marshal.StructureToPtr(wo, write_overlapped, true); NativeOverlapped ro = new NativeOverlapped(); read_event = new ManualResetEvent(false); #if NET_2_0 ro.EventHandle = read_event.Handle; #else ro.EventHandle = (int)read_event.Handle; #endif read_overlapped = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(NativeOverlapped))); Marshal.StructureToPtr(ro, read_overlapped, true); }
/// <summary> /// Generate a string from task host context and the remote process to be used as key to lookup processes we have already /// attempted to connect to or are already connected to /// </summary> private string GetProcessesToIgnoreKey(Handshake hostHandshake, int nodeProcessId) { return(hostHandshake.ToString() + "|" + nodeProcessId.ToString(CultureInfo.InvariantCulture)); }
private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { bool rts = Handshake.RequestToSend == handshake || Handshake.RequestToSendXOnXOff == handshake; bool xonxoff = Handshake.XOnXOff == handshake || Handshake.RequestToSendXOnXOff == handshake; byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.Handshake = handshake; com1.Open(); com2.Open(); //Setup to ensure write will block with type of handshake method being used if (rts) { com2.RtsEnable = false; } if (xonxoff) { com2.Write(XOffBuffer, 0, 1); Thread.Sleep(250); } char[] writeArr = new char[] { 'A', 'B', 'C' }; Task writeTask = Task.Run(() => com1.Write(writeArr, 0, writeArr.Length)); CancellationTokenSource cts = new CancellationTokenSource(); Task <int> readTask = com2.BaseStream.ReadAsync(new byte[3], 0, 3, cts.Token); // Give it some time to make sure transmission doesn't happen Thread.Sleep(200); Assert.False(readTask.IsCompleted); cts.CancelAfter(500); if (rts) { Assert.False(com1.CtsHolding); com2.RtsEnable = true; } if (xonxoff) { com2.Write(XOnBuffer, 0, 1); } writeTask.Wait(); Assert.True(readTask.Result > 0); //Verify that CtsHolding is true if the RequestToSend or RequestToSendXOnXOff handshake method is used if (rts) { Assert.True(com1.CtsHolding); } } }
public void UpdateLastSentHandshake(Handshake handshake) { LastSentHandshakeTime = handshake.HandshakeData.Time; }
/// <summary> /// 设置参数 /// </summary> /// <param name="baudRate">波特率</param> /// <param name="dataBits">数据位长度</param> /// <param name="readTimeOut">读取超时时间</param> /// <param name="writeTimeOut">写入超时时间</param> /// <param name="parity">奇偶检验</param> /// <param name="stopBits">停止位</param> /// <param name="handshake">握手协议</param> public void Set(int baudRate, int dataBits, int readTimeOut, int writeTimeOut, Parity parity, StopBits stopBits, Handshake handshake) { sp.BaudRate = baudRate; sp.DataBits = dataBits; sp.ReadTimeout = readTimeOut; sp.WriteTimeout = writeTimeOut; sp.Parity = parity; sp.StopBits = stopBits; sp.Handshake = handshake; }
public int newConnection(UDTSOCKET listen, IPEndPoint peer, Handshake hs) { UdtSocketInternal ns = null; UdtSocketInternal ls = locate(listen); if (null == ls) { return(-1); } // if this connection has already been processed if (null != (ns = locate(peer, hs.m_iID, hs.m_iISN))) { if (ns.m_pUDT.m_bBroken) { // last connection from the "peer" address has been broken ns.m_Status = UDTSTATUS.CLOSED; ns.m_TimeStamp = Timer.getTime(); lock (ls.m_AcceptLock) { ls.m_pQueuedSockets.Remove(ns.m_SocketID); ls.m_pAcceptSockets.Remove(ns.m_SocketID); } } else { // connection already exist, this is a repeated connection request // respond with existing HS information hs.m_iISN = ns.m_pUDT.m_iISN; hs.m_iMSS = ns.m_pUDT.m_iMSS; hs.m_iFlightFlagSize = ns.m_pUDT.m_iFlightFlagSize; hs.m_iReqType = -1; hs.m_iID = ns.m_SocketID; return(0); //except for this situation a new connection should be started } } // exceeding backlog, refuse the connection request if (ls.m_pQueuedSockets.Count >= ls.m_uiBackLog) { return(-1); } ns = new UdtSocketInternal(); ns.m_pUDT = new UDT(ls.m_pUDT); ns.m_pSelfAddr = new IPEndPoint(IPAddress.Any, 0); ns.m_pPeerAddr = peer; lock (m_IDLock) { ns.m_SocketID = --m_SocketID; } ns.m_ListenSocket = listen; ns.m_iIPversion = ls.m_iIPversion; ns.m_pUDT.m_SocketID = ns.m_SocketID; ns.m_PeerID = hs.m_iID; ns.m_iISN = hs.m_iISN; int error = 0; try { // bind to the same addr of listening socket ns.m_pUDT.open(); updateMux(ns, ls); ns.m_pUDT.connect(peer, hs); } catch (Exception e) { error = 1; goto ERR_ROLLBACK; } ns.m_Status = UDTSTATUS.CONNECTED; // copy address information of local node ns.m_pUDT.m_pSndQueue.m_pChannel.getSockAddr(ref ns.m_pSelfAddr); ConvertIPAddress.ToUintArray(ns.m_pSelfAddr.Address, ref ns.m_pUDT.m_piSelfIP); // protect the m_Sockets structure. lock (m_ControlLock) { m_Sockets[ns.m_SocketID] = ns; HashSet <int> sockets; if (!m_PeerRec.TryGetValue((ns.m_PeerID << 30) + ns.m_iISN, out sockets)) { sockets = new HashSet <int>(); m_PeerRec.Add((ns.m_PeerID << 30) + ns.m_iISN, sockets); } sockets.Add(ns.m_SocketID); } lock (ls.m_AcceptLock) { ls.m_pQueuedSockets.Add(ns.m_SocketID); } // acknowledge users waiting for new connections on the listening socket //m_EPoll.update_events(listen, ls.m_pUDT.m_sPollID, UDT_EPOLL_IN, true); Timer.triggerEvent(); ERR_ROLLBACK: if (error > 0) { ns.m_pUDT.close(); ns.m_Status = UDTSTATUS.CLOSED; ns.m_TimeStamp = Timer.getTime(); return(-1); } // wake up a waiting accept() call ls.m_AcceptCond.Set(); return(1); }
public void SetAttributes (int baud_rate, Parity parity, int data_bits, StopBits bits, Handshake hs) { DCB dcb = new DCB (); if (!GetCommState (handle, dcb)) ReportIOError (null); dcb.SetValues (baud_rate, parity, data_bits, bits, hs); if (!SetCommState (handle, dcb)) ReportIOError (null); }
// Token: 0x06000521 RID: 1313 RVA: 0x00017D38 File Offset: 0x00015F38 private void Initialize(string uri, string subProtocol, List <KeyValuePair <string, string> > cookies, List <KeyValuePair <string, string> > customHeaderItems, string userAgent, string origin, WebSocketVersion version, EndPoint httpConnectProxy, int receiveBufferSize) { if (version == WebSocketVersion.None) { this.NotSpecifiedVersion = true; version = WebSocketVersion.Rfc6455; } this.Version = version; this.ProtocolProcessor = WebSocket.GetProtocolProcessor(version); this.Cookies = cookies; this.Origin = origin; if (!string.IsNullOrEmpty(userAgent)) { if (customHeaderItems == null) { customHeaderItems = new List <KeyValuePair <string, string> >(); } customHeaderItems.Add(new KeyValuePair <string, string>("User-Agent", userAgent)); } if (customHeaderItems != null && customHeaderItems.Count > 0) { this.CustomHeaderItems = customHeaderItems; } Handshake handshake = new Handshake(); this.m_CommandDict.Add(handshake.Name, handshake); Text text = new Text(); this.m_CommandDict.Add(text.Name, text); Binary binary = new Binary(); this.m_CommandDict.Add(binary.Name, binary); Close close = new Close(); this.m_CommandDict.Add(close.Name, close); Ping ping = new Ping(); this.m_CommandDict.Add(ping.Name, ping); Pong pong = new Pong(); this.m_CommandDict.Add(pong.Name, pong); BadRequest badRequest = new BadRequest(); this.m_CommandDict.Add(badRequest.Name, badRequest); this.m_StateCode = -1; this.SubProtocol = subProtocol; this.Items = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); this.m_HttpConnectProxy = httpConnectProxy; TcpClientSession tcpClientSession; if (uri.StartsWith("ws://", StringComparison.OrdinalIgnoreCase)) { tcpClientSession = this.CreateClient(uri); } else { if (!uri.StartsWith("wss://", StringComparison.OrdinalIgnoreCase)) { throw new ArgumentException("Invalid uri", "uri"); } tcpClientSession = this.CreateSecureClient(uri); } tcpClientSession.ReceiveBufferSize = ((receiveBufferSize > 0) ? receiveBufferSize : 4096); tcpClientSession.Connected += this.client_Connected; tcpClientSession.Closed += this.client_Closed; tcpClientSession.Error += this.client_Error; tcpClientSession.DataReceived += this.client_DataReceived; this.Client = tcpClientSession; this.EnableAutoSendPing = true; }
public HandshakeMenuItem(Handshake type) { this.type = type; }
/// <summary> /// Constructor /// </summary> /// <param name="portName">Name of the serial port</param> /// <param name="baudRate">Baud rate</param> /// <param name="parity">PArity</param> /// <param name="dataBits">Data bits</param> /// <param name="stopBits">Stop bits</param> /// <param name="handshake">Handshake</param> public SerialDevice(string portName, BaudRate baudRate, Parity parity, int dataBits, StopBits stopBits, Handshake handshake) { _PortName = portName; _BaudRate = baudRate; _Parity = parity; _DataBits = dataBits; _StopBits = stopBits; _Handshake = handshake; }