//-- Constructor public Chronopic(SerialPort sp) { //-- Comprobar si puerto serie ya estaba abierto if (sp != null) if (sp.IsOpen) sp.Close(); //-- Abrir puerto serie sp.Open(); //-- Configurar timeout por defecto //de momento no en windows (hasta que no encontremos por qué falla) //OperatingSystem os = Environment.OSVersion; //not used, now there's no .NET this was .NET related //on mono timeouts work on windows and linux //if( ! os.Platform.ToString().ToUpper().StartsWith("WIN")) sp.ReadTimeout = DefaultTimeout; //-- Guardar el puerto serie this.sp = sp; // //-- Vaciar buffer // //done in a separate method // this.flush(); }
/// <summary> /// Modbus RTU slave factory method. /// </summary> public static ModbusSerialSlave CreateRtu(byte unitId, SerialPort serialPort) { if (serialPort == null) throw new ArgumentNullException("serialPort"); return CreateRtu(unitId, new SerialPortAdapter(serialPort)); }
private bool rcvAndEcho(ref SerialPort mySP) { byte rcv; char tmp; bool hasRcvd = false; try { rcv = (byte)mySP.ReadByte(); if (rcv != 255) { hasRcvd = true; tmp = (char)rcv; if (tmp != 0x0d && tmp != 0x0a) { // not CRLF accRcvd = accRcvd + tmp.ToString(); } if (tmp == 0x0d) { // CR mySP.WriteLine(accRcvd); rcvdCRLF = true; } } } catch (System.Exception) { } return hasRcvd; }
// Use this for initialization void Start () { serialPort = new SerialPort ("/dev/cu.usbmodem1421", 57600); serialPort.Open (); serialPort.ReadTimeout = 1; }
// Use this for initialization void Start () { rb = GetComponent<Rigidbody>(); stream = new SerialPort("COM4", 9600); stream.ReadTimeout = 50; stream.Open(); }
// The state object is necessary for a TimerCallback. public void checkConnection(object stateObject) { Process p = new Process(); Ping pingSender = new Ping (); p.StartInfo.FileName = "arp"; p.StartInfo.Arguments = "-a"; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; string data = "a"; byte[] buffer = Encoding.ASCII.GetBytes (data); for(int i = 0; i < 25 ; i++){ pingSender.Send ("10.0.0."+i.ToString(),10,buffer); } p.Start(); string output = p.StandardOutput.ReadToEnd(); p.WaitForExit(); string MAC = "xx-xx-xx-xx-xx-xx"; if(output.Contains(MAC)){ SerialPort port = new SerialPort("COM5", 9600); port.Open(); port.Write("u"); port.Close(); } else{ SerialPort port = new SerialPort("COM5", 9600); port.Open(); port.Write("l"); port.Close(); } }
// Use this for initialization void Start() { //Screen.showCursor = false; isPlaying = false; //Health = 100; isDead = false; Health = 100; _curHealth = Health; PlArmIdentity = PlayerArm.transform.rotation; Instantiate(Spells[0], PlayerArm.transform.GetChild(0).position, Quaternion.identity); CastingSpell = GameObject.FindGameObjectWithTag("Spell"); string[] ports = SerialPort.GetPortNames(); // foreach (string port in ports) // { // Console.WriteLine(port); // } _serialPort = new SerialPort(ports[1], 9600); _serialPort.Open(); Debug.Log(_serialPort.PortName); Debug.Log(_serialPort.BaudRate); Debug.Log(_serialPort.IsOpen); }
public static void runProgram(SerialPort port) { //System.IO.Ports.SerialPort serialPort1; //System.ComponentModel.IContainer components = new System.ComponentModel.Container(); //serialPort1 = new System.IO.Ports.SerialPort(components); //serialPort1.PortName = "COM4"; //serialPort1.BaudRate = 9600; port.Open(); // this turns on ! // serialPort1.DtrEnable = true; Console.Write("starting loop"); while (true) { //port.Write(new byte[] { 1 }, 0, 1); //System.Threading.Thread.Sleep(1000); //port.Write(new byte[] { 0 }, 0, 1); //System.Threading.Thread.Sleep(1000); Transmit(port, 63, 63, 40, 63); //wait for received while (port.BytesToRead==0) { System.Threading.Thread.Sleep(10); } if (port.ReadByte() != 103) { Console.Write("Bad ack"); break; } } }
//int leftPos=500; // Start void Start() { //start the serial connection. if (gameObject.GetComponent<COMParser>() != null) COMPort = gameObject.GetComponent<COMParser>().com; else if (gameObject.transform.parent.GetComponent<COMParser>() != null) COMPort = gameObject.transform.parent.GetComponent<COMParser>().com; else COMPort = gameObject.transform.parent.parent.GetComponent<COMParser>().com; if (COMPort != "COM0") { _SerialPort = new SerialPort(COMPort, 9600); OpenConnection(); //check how many outputs and inputs there are. for (int pinconfigcounter = 0; pinconfigcounter < pinConfig.Length; pinconfigcounter++) { if (pinConfig[pinconfigcounter].Equals("o")) outputcount++; if (pinConfig[pinconfigcounter].Equals("i")) inputcount++; if (pinConfig[pinconfigcounter].Equals("p")) pwmcount++; } DigitalInputs = new int[inputcount]; FromJavaToArduino = new char[pinConfig.Length]; } }// Start
// Use this for initialization void Start() { Debug.Log(SerialPort.GetPortNames().ToString()); mySerialPort = new SerialPort("\\\\.\\COM18"); mySerialPort.BaudRate = 9600; //mySerialPort.Parity = Parity.None; //mySerialPort.StopBits = StopBits.One; //mySerialPort.DataBits = 8; //mySerialPort.Handshake = Handshake.None; //mySerialPort.RtsEnable = true; //mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); if ( mySerialPort != null ) { if ( mySerialPort.IsOpen ) // close if already open { mySerialPort.Close(); Debug.Log ("Closed stream"); } mySerialPort.Open(); Debug.Log ("Opened stream"); } else { Debug.Log ("ERROR: Uninitialized stream"); } myThread = new Thread(new ThreadStart(GetArduino)); myThread.Start(); }
public static Stream GetMavStreamFromArgs(string[] args) { Stream strm = null; if (args.Length == 0) { strm = Console.OpenStandardInput(); } else if (args.Length == 1) { Console.WriteLine("Usage (todo)"); Console.ReadKey(); Environment.Exit(0); } else if (args[0] == "-S") { if (args.Length != 3) { Console.WriteLine("Usage (todo)"); Environment.Exit(1); } var comport = args[1]; var baud = Convert.ToInt32(args[2]); var port = new SerialPort(comport, baud); port.Open(); strm = port.BaseStream; } else { strm = File.OpenRead(args[1]); } return strm; }
public static void Main() { Debug.Print("BLE Shield"); var port = SerialPorts.COM1; // using D0 & D1 //var port = SerialPorts.COM2; // using D2 & D3 var bleShield = new SerialPort(port, 19200, Parity.None, 8, StopBits.None); bleShield.DataReceived += (sender, args) => { var receiveBuffer = new byte[16]; int bytesReceived = bleShield.Read(receiveBuffer, 0, receiveBuffer.Length); if (bytesReceived > 0) { Debug.Print("Bytes received: " + bytesReceived); Debug.Print(new String(Encoding.UTF8.GetChars(receiveBuffer))); } }; bleShield.Open(); while (true) { var random = new Random(); var sendBuffer = new byte[4]; random.NextBytes(sendBuffer); bleShield.Write(sendBuffer, 0, sendBuffer.Length); Thread.Sleep(1000); } }
public static void ExampleThreadFunction() { // bit rate change acording your GPS SerialPort serialPort = new SerialPort("COM3", 4800); serialPort.Open(); //here we create file in SD card main folder string rootDirectory = VolumeInfo.GetVolumes()[0].RootDirectory; FileStream FileHandle = new FileStream(rootDirectory + @"\gps.txt", FileMode.Create); while (true) { int bytesToRead = serialPort.BytesToRead; if (bytesToRead > 0) { // all struff from GPS streams in to file byte[] buffer = new byte[bytesToRead]; serialPort.Read(buffer, 0, buffer.Length); Debug.Print(new String(System.Text.Encoding.UTF8.GetChars(buffer)) + "\n"); FileHandle.Write(buffer, 0, buffer.Length); Thread.Sleep(500); } // Cleaning Debug.GC(true); Debug.EnableGCMessages(false); } }
/// <summary> /// コンストラクタ /// </summary> /// <param name="_sleep">モニタのスリープ時間</param> public Class_FeedbackStage(string _stageName="") { stageName = _stageName + ": "; serialPort = new SerialPort(); serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived); }
public static ModbusIpMaster CreateIp(SerialPort serialPort) { if (serialPort == null) throw new ArgumentNullException("serialPort"); return CreateIp(new SerialPortAdapter(serialPort)); }
private void spInit() { sp = new SerialPort(); sp.PortName = "COM40"; sp.BaudRate = 57600; sp.DataBits = 8; sp.Parity = Parity.Even; try { sp.Open(); try { sp.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);//事件 } catch (Exception ex) { MessageBox.Show(ex.Message); } } catch (Exception) { MessageBox.Show("无法连接串口"); } }
public TrainDrukteForm() { InitializeComponent(); timer1.Start(); _serialPort = new SerialPort(); }
public void Open () { // Opens the serial port stream = new SerialPort(port, baudrate); stream.ReadTimeout = 50; stream.Open(); //this.stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); }
// Use this for initialization void Start() { stm = new SerialPort("COM3", 38400, Parity.None, 8, StopBits.One); try { stm.Open(); if (!stm.IsOpen) { Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu); Destroy(this); } else { Debug.Log("Otwarto polaczenie z portem: " + nazwaPortu); stmThread = new Thread(stmOdczyt); stmThread.Start(); } } catch (Exception e) { Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu); Destroy(this); } }
/// <summary> /// Initializes a new instance of the Arduino. /// </summary> /// <param name="id">Identifier.</param> /// <param name="comPort">COM port.</param> public Arduino(int id, string comPort) { NextStation = new IPEndPoint(1, 1); this.ComPort = comPort; this.Id = id; this._serialPort = new SerialPort(ComPort, 9600); }
// Use this for initialization void Start() { nazwaPortu = COM.com; // utworzenie obiektu do komunikacji na danym porcie stm = new SerialPort(nazwaPortu, 38400, Parity.None, 8, StopBits.One); // proba otwarcia portu try { stm.Open(); if (!stm.IsOpen) { // jezeli nie udalo sie utworzyc portu to komponent jest likwidowany Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu); Destroy(this); } else { Debug.Log("Otwarto polaczenie z portem: " + nazwaPortu); // udalo sie utworzyc polaczenie z portem - startuje watek do czytania danych z portu stmThread = new Thread(stmOdczyt); stmThread.Start(); } } catch (Exception e) { // jezeli nie udalo sie utworzyc portu to komponent jest likwidowany Debug.LogWarning("Nie udalo sie otworzyc polaczenia z portem: " + nazwaPortu); Destroy(this); } }
protected virtual void OnStartClicked(object sender, System.EventArgs e) { sp = new SerialPort(devtty.Text, int.Parse(baudrate.Text), Parity.None, 8, StopBits.One); sp.Open(); quit = false; readThread = new Thread(new ThreadStart(ReadFromSerialPort)); readThread.Start(); }
private void Open(){ serialPort_ = new SerialPort (portName, baudRate, Parity.None, 8, StopBits.One); serialPort_.Open (); isRunning_ = true; thread_ = new Thread (Read); thread_.Start (); }
void Start() { //Here we are going to set the serialport it needs to listen to. //9600 is the value that you have also read in the arduino code. stream = new SerialPort("COM5", 9600); //COM5 is a port my pc uses, this is different on every pc. stream.ReadTimeout = 100; //define the timeout //stream.Open(); //Open the Serial Stream. }
private void InitConnection() { ports = SerialPort.GetPortNames(); port = new SerialPort("\\\\.\\"+ports[0], 9600); Debug.Log(ports[0]); port.WriteTimeout = 1000; port.Open(); }
void Start() { ports = SerialPort.GetPortNames(); stream = new SerialPort(ports[0], 57600); //stream = new SerialPort(/*ports[0]*/"COM13", 57600); stream.Open(); stream.Write(" "); }
public void Open () { // Opens the serial port stream = new SerialPort("COM3", baudrate); stream.ReadTimeout = 50; stream.Open(); //this.stream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); Debug.Log(ReadFromArduino()); }
/// <summary> /// Initialize the serial connection /// </summary> void Start() { serialPort = new SerialPort ( portName, baudRate, parity, dataBits, stopBits ); serialPort.ReadTimeout = ReadTimeOut; serialPort.WriteTimeout = WriteTimeOut; bitalinoCommunication = new BITalinoCommunicationSerialPort ( serialPort ); }
public frmSerialFinder() { InitializeComponent(); mSelectedDevice = null; mNeedScan = true; mScanning = false; mChosen = false; }
// Use this for initialization void Start() { EditorApplication.playmodeStateChanged = HandleOnPlayModeChanged; SerialStream = new SerialPort("\\\\.\\COM10", BAUD_RATE); // SerialStream.Handshake = Handshake.RequestToSend; // SerialStream.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); SerialStream.Open(); }
private static void VerifyWriteException(SerialPort com, Type expectedException) { Assert.Throws(expectedException, () => com.WriteLine(DEFAULT_STRING)); }
private void setAvailablePorts() { String[] ports = SerialPort.GetPortNames(); portSelect.Items.AddRange(ports); }
private void Verify_Handshake(Handshake handshake) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { byte[] XOffBuffer = new byte[1]; byte[] XOnBuffer = new byte[1]; XOffBuffer[0] = 19; XOnBuffer[0] = 17; int numNewLineBytes; Debug.WriteLine("Verifying Handshake={0}", handshake); com1.WriteTimeout = 3000; com1.Handshake = handshake; com1.Open(); com2.Open(); numNewLineBytes = com1.Encoding.GetByteCount(com1.NewLine.ToCharArray()); //Setup to ensure write will block 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 string randomLine = TCSupport.GetRandomString(s_STRING_SIZE_HANDSHAKE, TCSupport.CharacterOptions.Surrogates); byte[] randomLineBytes = com1.Encoding.GetBytes(randomLine); Task task = Task.Run(() => com1.WriteLine(randomLine)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, randomLineBytes.Length + numNewLineBytes); //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 TCSupport.WaitForTaskCompletion(task); 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); } } }
private void Form1_Load(object sender, EventArgs e) { string[] args = Environment.GetCommandLineArgs(); for (int i = 0; i < args.Length; i++) { if (args[i] == "-h") { MessageBox.Show( "\t---=== INA219 Meter for OBS ===---\n" + "\t-h\tInformation/Help Page\n" + "\t-p\tCOM Port Number\n" + "\t-b\tBaud rate\n" + "\t\tDefault: 115200\n" + "\t-f\tFont\n" + "\t\tDefault: Roboto\n" + "\t-fs\tFont Size\n" + "\t\tDefault: 72\n" + "\t-vc\tColor of voltage text (Hexadecimal)\n" + "\t\tDefault: #3F51B5\n" + "\t-cc\tColor of current text (Hexadecimal)\n" + "\t\tDefault: #3F51B5\n" + "\t-ck\tColor of background for chroma-keying\n\t\t(Hexadecimal)\n" + "\t\tDefault: #000000\n" + "\t-tc\tTruncate decimal points in mA current range\n" + "\t\tDefault: false\n" ); Application.Exit(); } if (args[i] == "-p") { comPort = args[i + 1]; if (!UInt16.TryParse(comPort, out UInt16 cp)) { // Non-number entered MessageBox.Show("Invalid COM port argument.\nCheck that you have entered a valid number!"); Application.Exit(); } } if (args[i] == "-b") { string baud = args[i + 1]; if (!Int32.TryParse(baud, out baudRate)) { // Non-number entered MessageBox.Show("Invalid baudrate argument.\nCheck that you have entered a valid number!"); Application.Exit(); } } if (args[i] == "-f") { fontName = args[i + 1]; } if (args[i] == "-fs") { fontSize = Int32.Parse(args[i + 1]); } if (args[i] == "-vc") { // Voltage color (Default: #3F51B5) string vc = args[i + 1]; vc = vc.Replace("#", ""); voltage.ForeColor = System.Drawing.ColorTranslator.FromHtml("#" + vc); } if (args[i] == "-cc") { // Current color (default: #3F51B5) string cc = args[i + 1]; cc = cc.Replace("#", ""); current.ForeColor = System.Drawing.ColorTranslator.FromHtml("#" + cc); } if (args[i] == "-ck") { // Chroma-key color (Default: #000000) string ck = args[i + 1]; ck = ck.Replace("#", ""); this.BackColor = System.Drawing.ColorTranslator.FromHtml("#" + ck); } if (args[i] == "-tc") { string cv = args[i + 1].ToLower(); if (cv == "false") { truncateCurrent = false; } } voltage.Font = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular); current.Font = new System.Drawing.Font(fontName, fontSize, System.Drawing.FontStyle.Regular); } // Instantiate new SerialPort p = new SerialPort( "COM" + comPort, baudRate, Parity.None, 8, StopBits.One ); // Call our port_DataReceived function when event triggered p.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); try { p.Open(); } catch (Exception ex) { if (ex is System.IO.IOException) { MessageBox.Show("Invalid COM port configuration!"); } if (ex is System.UnauthorizedAccessException) { MessageBox.Show( "Unable to access COM port." + Environment.NewLine + "Is it in use by something else?" ); } Application.Exit(); } }
void DestroyPort(SerialPort port) { port.PinChanged -= HandlePinChanged; port.Dispose(); }
public void Enviar(string cmd) { SerialPort porta = Conectar(); porta.Write(cmd); }
public PC(string PCName, string inPort, string outPort) { COM_in = PortFactory.CreatePort(inPort); COM_out = PortFactory.CreatePort(outPort); WorkName = PCName; }
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { CheckForIllegalCrossThreadCalls = false; string[] str = new string[4]; NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; SerialPort port = new SerialPort("COM8", 9600); port.ReadTimeout = 3000; try { port.Open(); } catch { ErrorPortDialog ErrPort = new ErrorPortDialog(); labelStreemStatus.ForeColor = Color.Red; labelStreemStatus.Text = "Не активний"; ErrPort.ShowDialog(); textBox_NULL(); return; } labelStreemStatus.ForeColor = Color.Green; labelStreemStatus.Text = "Активний"; try { for (int i = 0; i < 4; i++) { str[i] = port.ReadLine(); } } catch { ErrorPortDialog ErrPort = new ErrorPortDialog(); labelStreemStatus.ForeColor = Color.Red; labelStreemStatus.Text = "Не активний"; ErrPort.ShowDialog(); textBox_NULL(); return; } DateTime date = DateTime.Now; StreamWriter writer = new StreamWriter("data\\" + date.Day + "-" + date.Month + "-" + date.Year + ".txt", true); writer.WriteLine("Time=" + date.Hour + ":" + date.Minute + ":" + date.Second); for (int i = 0; i < 4; i++) { writer.WriteLine(str[i]); } writer.WriteLine("=================="); writer.Close(); float presMax = float.Parse(str[0] = str[0].Substring(9), nfi); float presMin = presMax; float presAvg = presMax; float presLast = presMax; float tempMax = float.Parse(str[1] = str[1].Substring(12), nfi); float tempMin = tempMax; float tempAvg = tempMax; float tempLast = tempMax; float airMax = float.Parse(str[2] = str[2].Substring(4), nfi); float airMin = airMax; float airAvg = airMax; float airLast = airMax; float humMax = float.Parse(str[3] = str[3].Substring(9), nfi); float humMin = humMax; float humAvg = humMax; float humLast = humMax; textBoxPresAvg.Text = Convert.ToString(Math.Round(presAvg, 2)); textBoxPresMax.Text = Convert.ToString(Math.Round(presMax, 2)); textBoxPresMin.Text = Convert.ToString(Math.Round(presMin, 2)); textBoxPresLast.Text = Convert.ToString(Math.Round(presLast, 2)); textBoxTempAvg.Text = Convert.ToString(Math.Round(tempAvg, 2)); textBoxTempMax.Text = Convert.ToString(Math.Round(tempMax, 2)); textBoxTempMin.Text = Convert.ToString(Math.Round(tempMin, 2)); textBoxTempLast.Text = Convert.ToString(Math.Round(tempLast, 2)); textBoxAirAvg.Text = Convert.ToString(Math.Round(airAvg, 2)); textBoxAirMax.Text = Convert.ToString(Math.Round(airMax, 2)); textBoxAirMin.Text = Convert.ToString(Math.Round(airMin, 2)); textBoxAirLast.Text = Convert.ToString(Math.Round(airLast, 2)); textBoxHumAvg.Text = Convert.ToString(Math.Round(humAvg, 2)); textBoxHumMax.Text = Convert.ToString(Math.Round(humMax, 2)); textBoxHumMin.Text = Convert.ToString(Math.Round(humMin, 2)); textBoxHumLast.Text = Convert.ToString(Math.Round(humLast, 2)); while (!backgroundWorker1.CancellationPending) { try { for (int i = 0; i < 4; i++) { str[i] = port.ReadLine(); } } catch { ErrorPortDialog ErrPort = new ErrorPortDialog(); labelStreemStatus.ForeColor = Color.Red; labelStreemStatus.Text = "Не активний"; textBox_NULL(); ErrPort.ShowDialog(); return; } date = DateTime.Now; writer = new StreamWriter("data\\" + date.Day + "-" + date.Month + "-" + date.Year + ".txt", true); writer.WriteLine("Time=" + date.Hour + ":" + date.Minute + ":" + date.Second); for (int i = 0; i < 4; i++) { writer.WriteLine(str[i]); } writer.WriteLine("=================="); writer.Close(); presLast = float.Parse(str[0] = str[0].Substring(9), nfi); if (presLast > presMax) { presMax = presLast; } if (presLast < presMin) { presMin = presLast; } if (presAvg == -100) { presAvg = presLast; } else { presAvg = (presAvg + presLast) / 2; } tempLast = float.Parse(str[1] = str[1].Substring(12), nfi); if (tempLast > tempMax) { tempMax = tempLast; } if (tempLast < tempMin) { tempMin = tempLast; } if (tempAvg == -100) { tempAvg = tempLast; } else { tempAvg = (tempAvg + tempLast) / 2; } airLast = float.Parse(str[2] = str[2].Substring(4), nfi); if (airLast > airMax) { airMax = airLast; } if (airLast < airMin) { airMin = airLast; } if (airAvg == -100) { airAvg = airLast; } else { airAvg = (airAvg + airLast) / 2; } humLast = float.Parse(str[3] = str[3].Substring(9), nfi); if (humLast > humMax) { humMax = humLast; } if (humLast < humMin) { humMin = humLast; } if (humAvg == -100) { humAvg = humLast; } else { humAvg = (humAvg + humLast) / 2; } textBoxPresAvg.Text = Convert.ToString(Math.Round(presAvg, 2)); textBoxPresMax.Text = Convert.ToString(Math.Round(presMax, 2)); textBoxPresMin.Text = Convert.ToString(Math.Round(presMin, 2)); textBoxPresLast.Text = Convert.ToString(Math.Round(presLast, 2)); textBoxTempAvg.Text = Convert.ToString(Math.Round(tempAvg, 2)); textBoxTempMax.Text = Convert.ToString(Math.Round(tempMax, 2)); textBoxTempMin.Text = Convert.ToString(Math.Round(tempMin, 2)); textBoxTempLast.Text = Convert.ToString(Math.Round(tempLast, 2)); textBoxAirAvg.Text = Convert.ToString(Math.Round(airAvg, 2)); textBoxAirMax.Text = Convert.ToString(Math.Round(airMax, 2)); textBoxAirMin.Text = Convert.ToString(Math.Round(airMin, 2)); textBoxAirLast.Text = Convert.ToString(Math.Round(airLast, 2)); textBoxHumAvg.Text = Convert.ToString(Math.Round(humAvg, 2)); textBoxHumMax.Text = Convert.ToString(Math.Round(humMax, 2)); textBoxHumMin.Text = Convert.ToString(Math.Round(humMin, 2)); textBoxHumLast.Text = Convert.ToString(Math.Round(humLast, 2)); } port.Close(); labelStreemStatus.ForeColor = Color.Red; labelStreemStatus.Text = "Не активний"; textBox_NULL(); }
public IEnumerable <string> Discover() { var result = SerialPort.GetPortNames(); return(result.ToList()); }
public LedEqpService() { InitializeComponent(); #region LED byte effect = Convert.ToByte(pEffcetNum); byte rate = Convert.ToByte(pRate); byte stime = Convert.ToByte(pSingleTime); byte ttime = Convert.ToByte(pTotalTime); outMsg = Properties.Settings.Default.outmsg; led1 = new CLedShow(Convert.ToByte(pLed1Address), effect, rate, stime, ttime); led2 = new CLedShow(Convert.ToByte(pLed2Address), effect, rate, stime, ttime); led3 = new CLedShow(Convert.ToByte(pLed3Address), effect, rate, stime, ttime); led4 = new CLedShow(Convert.ToByte(pLed4Address), effect, rate, stime, ttime); #region LED通讯端口初始化 try { port_Led1 = new SerialPort(); port_Led1.PortName = "COM" + portNum_Led1; port_Led1.BaudRate = 9600; port_Led1.DataBits = 8; port_Led1.Handshake = Handshake.None; port_Led1.DiscardNull = false; port_Led1.StopBits = StopBits.One; port_Led1.WriteBufferSize = 4096; port_Led1.WriteTimeout = -1; if (port_Led1.IsOpen) { port_Led1.Close(); } port_Led1.Open(); } catch (Exception ex) { CWSException.WriteError("SerialPort_LED1端口初始化异常:" + ex.ToString()); } //try //{ // port_Led2 = new SerialPort(); // port_Led2.PortName = "COM" + portNum_Led2; // port_Led2.BaudRate = 9600; // port_Led2.DataBits = 8; // port_Led2.Handshake = Handshake.None; // port_Led2.DiscardNull = false; // port_Led2.StopBits = StopBits.One; // port_Led2.WriteBufferSize = 4096; // port_Led2.WriteTimeout = -1; // if (port_Led2.IsOpen) // { // port_Led2.Close(); // } // port_Led2.Open(); //} //catch (Exception ex) //{ // CWSException.WriteError("SerialPort_LED2端口初始化异常:" + ex.ToString()); //} try { port_Led3 = new SerialPort(); port_Led3.PortName = "COM" + portNum_Led3; port_Led3.BaudRate = 9600; port_Led3.DataBits = 8; port_Led3.Handshake = Handshake.None; port_Led3.DiscardNull = false; port_Led3.StopBits = StopBits.One; port_Led3.WriteBufferSize = 4096; port_Led3.WriteTimeout = -1; if (port_Led3.IsOpen) { port_Led3.Close(); } port_Led3.Open(); } catch (Exception ex) { CWSException.WriteError("SerialPort_LED3端口初始化异常:" + ex.ToString()); } //try //{ // port_Led4 = new SerialPort(); // port_Led4.PortName = "COM" + portNum_Led4; // port_Led4.BaudRate = 9600; // port_Led4.DataBits = 8; // port_Led4.Handshake = Handshake.None; // port_Led4.DiscardNull = false; // port_Led4.StopBits = StopBits.One; // port_Led4.WriteBufferSize = 4096; // port_Led4.WriteTimeout = -1; // if (port_Led4.IsOpen) // { // port_Led4.Close(); // } // port_Led4.Open(); //} //catch (Exception ex) //{ // CWSException.WriteError("SerialPort_LED4端口初始化异常:" + ex.ToString()); //} #endregion #endregion myDelegate = new CDelegate(); myDelegate.DisplayLed1TitleEvent += new DisplayLed1TitleDelegate(myDelegate_DisplayLed1TitleEvent); myDelegate.DisplayLed2TitleEvent += new DisplayLed2TitleDelegate(myDelegate_DisplayLed2TitleEvent); myDelegate.DisplayLed3TitleEvent += new DisplayLed3TitleDelegate(myDelegate_DisplayLed3TitleEvent); myDelegate.DisplayLed4TitleEvent += new DisplayLed4TitleDelegate(myDelegate_DisplayLed4TitleEvent); }
public static void Execute() { //var ws = Enumerable.Range(0, 100) // .Select(i => new WriteSettingsRequest((ushort)i, (AlarmSettings)(i % 4), (ushort)(i * 10))) // .ToArray(); //var sws = ws.AsSpan(); //var swsd = MemoryMarshal.Cast<WriteSettingsRequest, byte>(sws); //var swsa = swsd.ToArray(); var factory = new RadexOneFactory(); var decoder = new RadexOneDecoder(); var segmenter = factory.GetSegmenter(data => { var result = decoder.Decode(data); Console.WriteLine(result); return(Task.FromResult(0)); }); var ports = SerialPort.GetPortNames().OrderBy(s => s); foreach (var port in ports) { Console.WriteLine(port); } Console.WriteLine($"Enter Port: (Default { ports.FirstOrDefault()})"); var portName = Console.ReadLine(); var serialPort = new PortProvider().GetRadexOnePort(string.IsNullOrWhiteSpace(portName) ? ports.FirstOrDefault() : portName); using (var port = serialPort) using (var cts = new CancellationTokenSource()) { port.Open(); Console.Write("Enter to exit"); Task.WaitAll( Task.Run(async() => await Program.ReadLineAsync().ContinueWith(t => cts.Cancel(false))), Task.Run(async() => { while (!cts.IsCancellationRequested) { try { await port.BaseStream.Follow().With(segmenter).RunAsync(cts.Token); cts.Cancel(true); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } } }), Task.Run(async() => { ushort x = 0; while (!cts.IsCancellationRequested) { x++; try { IRadexObject requestObject = (x % 10) switch { 1 => new ReadSerialNumberRequest(x), // 2 => new ReadSerialNumberRequest(x), //3 => new DevicePing(x), //0 => new DevicePing(x), //4 => new WriteSettingsRequest(x, AlarmSettings.Audio, 30), //5 => new WriteSettingsRequest(x, AlarmSettings.Audio, 30), //6 => new WriteSettingsRequest(x, AlarmSettings.Audio, 30), 7 => new ReadSettingsRequest(x), //8 => new ResetAccumulatedRequest(x), _ => new ReadValuesRequest(x) }; var requestBuffer = new byte[Marshal.SizeOf(requestObject)]; IntPtr ptr = Marshal.AllocHGlobal(requestBuffer.Length); Marshal.StructureToPtr(requestObject, ptr, true); Marshal.Copy(ptr, requestBuffer, 0, requestBuffer.Length); Marshal.FreeHGlobal(ptr); var hex = requestBuffer.ToHexString(); //7BFF 2000 _600 1800 ____ 4600 __08 _C00 F3F7 await port.BaseStream.WriteAsync(requestBuffer, 0, requestBuffer.Length, cts.Token); } catch (Exception ex) { Console.Error.WriteLine(ex.Message); } if (!cts.IsCancellationRequested) { await Task.Delay(1000); } } }) ); } }
public DeviceConnection() { ports = SerialPort.GetPortNames(); port = null; }
public AsyncWriteRndStr(SerialPort com, int strSize) { _com = com; _strSize = strSize; }
/// <summary> /// Коструктор /// </summary> /// <param name="portName">Имя порта</param> public COMBarcodeScaner(string portName) { Port = new SerialPort(portName); Initialize(); }
/// <summary> /// Список доступных портов /// </summary> public string[] GetPortsNames() { return(SerialPort.GetPortNames()); }
public VinceMotorFunction(uint f_ID, SerialPort f_MotorPort) { m_ID = f_ID; m_MotorPort = f_MotorPort; }
public void fillComList(ListBox listBox) { listBox.Items.Clear(); listBox.Items.AddRange(SerialPort.GetPortNames()); //vyhladaj porty COM, vloz do zoznamu portov }
private void Form1_Load(object sender, EventArgs e) { for (int i = 0; i < MotorsCPort.Count; i++) { if (lastPort < MotorsCPort[i]) { lastPort = MotorsCPort[i]; SerialPort serialPort = new SerialPort(); serialPort.BaudRate = 115200; serialPort.PortName = "COM" + MotorsCPort[i]; serialPort.WriteTimeout = 1000; serialPort.DtrEnable = false; serialPort.RtsEnable = false; serialPort.Open(); serialPort.Write("{M0,F,0}{M1,F,0}{M2,F,0}{M3,F,0}{M4,F,0}{M5,F,0}"); serialPort.ReadExisting(); listofPorts.Add(serialPort); } } UdpClient udpClient = new UdpClient(8888); abort = false; arduinoSender = new ArduinoSender(ref listofPorts, ref PhToMtr); arduinoReciver = new ArduinoReciver(ref listofPorts,ref MtrToPh); udpReceiver = new UdpReceiver(ref udpClient); dataExchanger = new DataExchanger(ref arduinoReciver, ref arduinoSender, ref phidgetReciver, ref motionCalculator); PhidgetThread = new Thread(new ThreadStart(phidgetReciver.ThreadRun)); ReciverThread = new Thread(new ThreadStart(arduinoReciver.ThreadRun)); SenderThread = new Thread(new ThreadStart(arduinoSender.ThreadRun)); CalculatorThread = new Thread(new ThreadStart(motionCalculator.ThreadRun)); UDPReceiverThread = new Thread(new ThreadStart(udpReceiver.ThreadRun)); DataExchangerThread = new Thread(new ThreadStart(dataExchanger.ThreadRun)); System.Diagnostics.Trace.WriteLine("Before start thread"); PhidgetThread.Name = "PhidgetThread"; ReciverThread.Name = "ReciverThread"; SenderThread.Name = "SenderThread"; CalculatorThread.Name = "CalculatorThread"; UDPReceiverThread.Name = "UDPReceiverThread"; DataExchangerThread.Name = "DataExchangerThread"; phidgetReciver.abort = false; arduinoReciver.abort = false; arduinoSender.abort = false; motionCalculator.abort = false; dataExchanger.abort = false; PhidgetThread.Start(); ReciverThread.Start(); CalculatorThread.Start(); UDPReceiverThread.Start(); { listOfLEdits.Add(currentLoad1); listOfLEdits.Add(currentLoad2); listOfLEdits.Add(currentLoad3); listOfLEdits.Add(currentLoad4); listOfLEdits.Add(currentLoad5); listOfLEdits.Add(currentLoad6); listOfLEdits.Add(currentLoad7); listOfLEdits.Add(currentLoad8); listOfLEdits.Add(currentLoad9); listOfLEdits.Add(currentLoad10); listOfLEdits.Add(currentLoad11); listOfLEdits.Add(currentLoad12); } { listOfPEdits.Add(currPos1); listOfPEdits.Add(currPos2); listOfPEdits.Add(currPos3); listOfPEdits.Add(currPos4); listOfPEdits.Add(currPos5); listOfPEdits.Add(currPos6); listOfPEdits.Add(currPos7); listOfPEdits.Add(currPos8); listOfPEdits.Add(currPos9); listOfPEdits.Add(currPos10); listOfPEdits.Add(currPos11); listOfPEdits.Add(currPos12); } { listOfTEdits.Add(currTorque1); listOfTEdits.Add(currTorque2); listOfTEdits.Add(currTorque3); listOfTEdits.Add(currTorque4); listOfTEdits.Add(currTorque5); listOfTEdits.Add(currTorque6); listOfTEdits.Add(currTorque7); listOfTEdits.Add(currTorque8); listOfTEdits.Add(currTorque9); listOfTEdits.Add(currTorque10); listOfTEdits.Add(currTorque11); listOfTEdits.Add(currTorque12); } { listOfSEdits.Add(totalDiff1); listOfSEdits.Add(totalDiff2); listOfSEdits.Add(totalDiff3); listOfSEdits.Add(totalDiff4); listOfSEdits.Add(totalDiff5); listOfSEdits.Add(totalDiff6); listOfSEdits.Add(totalDiff7); listOfSEdits.Add(totalDiff8); listOfSEdits.Add(totalDiff9); listOfSEdits.Add(totalDiff10); listOfSEdits.Add(totalDiff11); listOfSEdits.Add(totalDiff12); } { listOfKHEdits.Add(KoeffH1); listOfKHEdits.Add(KoeffH2); listOfKHEdits.Add(KoeffH3); listOfKHEdits.Add(KoeffH4); listOfKHEdits.Add(KoeffH5); listOfKHEdits.Add(KoeffH6); listOfKHEdits.Add(KoeffH7); listOfKHEdits.Add(KoeffH8); listOfKHEdits.Add(KoeffH9); listOfKHEdits.Add(KoeffH10); listOfKHEdits.Add(KoeffH11); listOfKHEdits.Add(KoeffH12); } { listOfKVEdits.Add(KoeffV1); listOfKVEdits.Add(KoeffV2); listOfKVEdits.Add(KoeffV3); listOfKVEdits.Add(KoeffV4); listOfKVEdits.Add(KoeffV5); listOfKVEdits.Add(KoeffV6); listOfKVEdits.Add(KoeffV7); listOfKVEdits.Add(KoeffV8); listOfKVEdits.Add(KoeffV9); listOfKVEdits.Add(KoeffV10); listOfKVEdits.Add(KoeffV11); listOfKVEdits.Add(KoeffV12); } this.Location = new Point(0, 0); }
//===================================================================== public ModbusRTU(SerialPort serialPort) { m_physicalLayer = PhysicalLayer.Serial; m_serialPort = serialPort; }
/// <summary> /// Checks all open serial ports for HMD Exercisers /// </summary> /// <returns> /// Returns true if a valid HMD Kit is detected, otherwise returns false. /// </returns> public bool FindHmdKitDevice() { lock (this.hmdKitLock) { if (this.serialPort != null) { if (this.serialPort.IsOpen) { string response = string.Empty; this.SendCommand("GetVersion", ResponseTimeDefault, null, out response); if (response == (HmdKitVersion + HmdKitShieldType)) { this.isPresent = true; return(true); } else { this.serialPort.Close(); } } } string[] ports = SerialPort.GetPortNames(); foreach (string port in ports) { SerialPort sp = new SerialPort(port, HmdKitBaudRate, Parity.None, 8, StopBits.One); sp.Handshake = Handshake.None; sp.DtrEnable = true; sp.ReadTimeout = 500; try { sp.Open(); } catch (UnauthorizedAccessException) { // Serial port is already open or access is denied continue; } catch (InvalidOperationException) { // The specified port on the current instance of the SerialPort is already open continue; } catch (IOException) { continue; } // Wait for the device to initialize Thread.Sleep(2000); sp.NewLine = "\r\n"; this.serialPort = sp; string response = string.Empty; this.serialPort.WriteLine("version"); try { response = this.serialPort.ReadLine(); } catch (TimeoutException) { sp.Dispose(); continue; } if (response == (HmdKitVersion + HmdKitShieldType)) { this.isPresent = true; return(true); } else { sp.Dispose(); } } this.serialPort = null; this.isPresent = false; return(false); } }
/// public void Initialize(BinaryConnectionConfig config) { _config = (SerialBinaryConfig)config; _serialPort = SerialPortFactory.FromConfig(_config, Logger); _serialPort.DataReceived += OnDataReceived; }
private void btnGetSerialPorts_Click(object sender, EventArgs e) { string[] ArrayComPortsNames = null; int index = -1; string ComPortName = null; //Com Ports ArrayComPortsNames = SerialPort.GetPortNames(); do { index += 1; cboPorts.Items.Add(ArrayComPortsNames[index]); } while (!((ArrayComPortsNames[index] == ComPortName) || (index == ArrayComPortsNames.GetUpperBound(0)))); Array.Sort(ArrayComPortsNames); if (index == ArrayComPortsNames.GetUpperBound(0)) { ComPortName = ArrayComPortsNames[0]; } //get first item print in text cboPorts.Text = ArrayComPortsNames[0]; //Baud Rate cboBaudRate.Items.Add(300); cboBaudRate.Items.Add(600); cboBaudRate.Items.Add(1200); cboBaudRate.Items.Add(2400); cboBaudRate.Items.Add(9600); cboBaudRate.Items.Add(14400); cboBaudRate.Items.Add(19200); cboBaudRate.Items.Add(38400); cboBaudRate.Items.Add(57600); cboBaudRate.Items.Add(115200); cboBaudRate.Items.ToString(); //get first item print in text cboBaudRate.Text = cboBaudRate.Items[0].ToString(); //Data Bits cboDataBits.Items.Add(7); cboDataBits.Items.Add(8); //get the first item print it in the text cboDataBits.Text = cboDataBits.Items[0].ToString(); //Stop Bits cboStopBits.Items.Add("One"); cboStopBits.Items.Add("OnePointFive"); cboStopBits.Items.Add("Two"); //get the first item print in the text cboStopBits.Text = cboStopBits.Items[0].ToString(); //Parity cboParity.Items.Add("None"); cboParity.Items.Add("Even"); cboParity.Items.Add("Mark"); cboParity.Items.Add("Odd"); cboParity.Items.Add("Space"); //get the first item print in the text cboParity.Text = cboParity.Items[0].ToString(); //Handshake cboHandShaking.Items.Add("None"); cboHandShaking.Items.Add("XOnXOff"); cboHandShaking.Items.Add("RequestToSend"); cboHandShaking.Items.Add("RequestToSendXOnXOff"); //get the first item print it in the text cboHandShaking.Text = cboHandShaking.Items[0].ToString(); }
/// <summary> /// Коструктор /// Открывает COM1 /// </summary> public COMBarcodeScaner() { Port = new SerialPort("COM3"); Initialize(); }
/// <summary> /// /// </summary> /// <param name="serialPort"></param> /// <returns></returns> static byte[] readpacket(SerialPort serialPort) { byte[] temp = new byte[4000]; byte[] mes = new byte[2] { 0x0, 0xC0 }; // fail int a = 7; int count = 0; serialPort.ReadTimeout = 1000; while (count < a) { //Console.WriteLine("count {0} a {1} mes leng {2}",count,a,mes.Length); try { temp[count] = (byte)serialPort.ReadByte(); } catch { break; } //Console.Write("{1}", temp[0], (char)temp[0]); if (temp[0] != 0x1b) { count = 0; continue; } if (count == 3) { a = (temp[2] << 8) + temp[3]; mes = new byte[a]; a += 5; } if (count >= 5) { mes[count - 5] = temp[count]; } count++; } //Console.WriteLine("read ck"); try { temp[count] = (byte)serialPort.ReadByte(); } catch { } count++; Array.Resize <byte>(ref temp, count); //Console.WriteLine(this.BytesToRead); return(mes); }
/// <summary> /// List all serial ports /// </summary> /// <returns></returns> public static string[] ListPorts() { return(SerialPort.GetPortNames()); }
/// <summary> /// Detect board version /// </summary> /// <param name="port"></param> /// <returns> boards enum value</returns> public static boards DetectBoard(string port) { SerialPort serialPort = new SerialPort(); serialPort.PortName = port; if (!MainV2.MONO) { try { // check the device reported productname var ports = Win32DeviceMgmt.GetAllCOMPorts(); foreach (var item in ports) { log.InfoFormat("{0}: {1} - {2}", item.name, item.description, item.board); if (port.ToLower() == item.name.ToLower()) { if (item.board == "PX4 FMU v4.x") { log.Info("is a px4v4 pixracer"); return(boards.px4v4); } if (item.board == "fmuv2") { log.Info("is a fmuv2"); return(boards.px4v2); } if (item.board == "fmuv3") { log.Info("is a fmuv3"); return(boards.px4v3); } if (item.board == "fmuv4") { log.Info("is a fmuv4"); return(boards.px4v4); } if (item.board == "fmuv5") { log.Info("is a fmuv5"); return(boards.fmuv5); } if (item.board == "PX4 FMU v2.x") { CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd); DateTime DEADLINE = DateTime.Now.AddSeconds(30); while (DateTime.Now < DEADLINE) { string[] allports = SerialPort.GetPortNames(); foreach (string port1 in allports) { log.Info(DateTime.Now.Millisecond + " Trying Port " + port1); try { using (var up = new Uploader(port1, 115200)) { up.identify(); Console.WriteLine( "Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port1); if (up.fw_maxsize == 2080768 && up.board_type == 9 && up.bl_rev >= 5) { log.Info("is a px4v3"); return(boards.px4v3); } else { log.Info("is a px4v2"); return(boards.px4v2); } } } catch (Exception ex) { log.Error(ex); } } } log.Info("Failed to detect px4 board type"); return(boards.none); } /* * if (item.board == "Arduino Mega 2560") * { * log.Info("is a 2560v2"); * return boards.b2560v2; * }*/ if (item.board == "revo-mini") { log.Info("is a revo-mini"); return(boards.revomini); } if (item.board == "mini-pix") { log.Info("is a mini-pix"); return(boards.minipix); } if (item.board == "mindpx-v2") { log.Info("is a mindpx-v2"); return(boards.mindpxv2); } } } } catch { } ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj2 in searcher.Get()) { log.InfoFormat("-----------------------------------"); log.InfoFormat("Win32_USBDevice instance"); log.InfoFormat("-----------------------------------"); foreach (var item in obj2.Properties) { log.InfoFormat("{0}: {1}", item.Name, item.Value); } // check vid and pid if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_2341&PID_0010")) { // check port name as well if (obj2.Properties["Name"].Value.ToString().ToUpper().Contains(serialPort.PortName.ToUpper())) { log.Info("is a 2560-2"); return(boards.b2560v2); } } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0010")) { // check port name as well //if (obj2.Properties["Name"].Value.ToString().ToUpper().Contains(serialPort.PortName.ToUpper())) { log.Info("is a px4"); return(boards.px4); } } // chibios or normal px4 if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_0483&PID_5740") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0011")) { CustomMessageBox.Show(Strings.PleaseUnplugTheBoardAnd); DateTime DEADLINE = DateTime.Now.AddSeconds(30); while (DateTime.Now < DEADLINE) { string[] allports = SerialPort.GetPortNames(); foreach (string port1 in allports) { log.Info(DateTime.Now.Millisecond + " Trying Port " + port1); try { using (var up = new Uploader(port1, 115200)) { up.identify(); Console.WriteLine( "Found board type {0} boardrev {1} bl rev {2} fwmax {3} on {4}", up.board_type, up.board_rev, up.bl_rev, up.fw_maxsize, port1); if (up.fw_maxsize == 2080768 && up.board_type == 9 && up.bl_rev >= 5) { log.Info("is a px4v3"); return(boards.px4v3); } else { log.Info("is a px4v2"); return(boards.px4v2); } } } catch (Exception ex) { log.Error(ex); } } } log.Info("Failed to detect px4 board type"); return(boards.none); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0021")) { log.Info("is a px4v3 X2.1"); return(boards.px4v3); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0012")) { log.Info("is a px4v4 pixracer"); return(boards.px4v4); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0013")) { log.Info("is a px4v4pro pixhawk 3 pro"); return(boards.px4v4pro); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0001")) { log.Info("is a px4v2 bootloader"); return(boards.px4v2); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0016")) { log.Info("is a px4v2 bootloader"); CustomMessageBox.Show( "You appear to have a bootloader with a bad PID value, please update your bootloader."); return(boards.px4v2); } //|| obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0012") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0013") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0014") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0015") || obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_26AC&PID_0016") if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1140")) { log.Info("is a vrbrain 4.0 bootloader"); return(boards.vrbrainv40); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1145")) { log.Info("is a vrbrain 4.5 bootloader"); return(boards.vrbrainv45); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1150")) { log.Info("is a vrbrain 5.0 bootloader"); return(boards.vrbrainv50); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1151")) { log.Info("is a vrbrain 5.1 bootloader"); return(boards.vrbrainv51); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1152")) { log.Info("is a vrbrain 5.2 bootloader"); return(boards.vrbrainv52); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1154")) { log.Info("is a vrbrain 5.4 bootloader"); return(boards.vrbrainv54); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1910")) { log.Info("is a vrbrain core 1.0 bootloader"); return(boards.vrcorev10); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1351")) { log.Info("is a vrubrain 5.1 bootloader"); return(boards.vrubrainv51); } if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_27AC&PID_1352")) { log.Info("is a vrubrain 5.2 bootloader"); return(boards.vrubrainv52); } } } else { // if its mono if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a APM 2+?", "APM 2+", MessageBoxButtons.YesNo)) { return(boards.b2560v2); } else { if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a PX4/PIXHAWK/PIXRACER?", "PX4/PIXHAWK", MessageBoxButtons.YesNo)) { if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a PIXRACER?", "PIXRACER", MessageBoxButtons.YesNo)) { return(boards.px4v4); } if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a CUBE?", "CUBE", MessageBoxButtons.YesNo)) { return(boards.px4v3); } if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a PIXHAWK?", "PIXHAWK", MessageBoxButtons.YesNo)) { return(boards.px4v2); } return(boards.px4); } else { return(boards.b2560); } } } if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a Linux board?", "Linux", MessageBoxButtons.YesNo)) { if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this Bebop2?", "Bebop2", MessageBoxButtons.YesNo)) { return(boards.bebop2); } if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this Disco?", "Disco", MessageBoxButtons.YesNo)) { return(boards.disco); } } if (serialPort.IsOpen) { serialPort.Close(); } serialPort.DtrEnable = true; serialPort.BaudRate = 57600; serialPort.Open(); Thread.Sleep(100); int a = 0; while (a < 20) // 20 * 50 = 1 sec { //Console.WriteLine("write " + DateTime.Now.Millisecond); serialPort.DiscardInBuffer(); serialPort.Write(new byte[] { (byte)'0', (byte)' ' }, 0, 2); a++; Thread.Sleep(50); //Console.WriteLine("btr {0}", serialPort.BytesToRead); if (serialPort.BytesToRead >= 2) { byte b1 = (byte)serialPort.ReadByte(); byte b2 = (byte)serialPort.ReadByte(); if (b1 == 0x14 && b2 == 0x10) { serialPort.Close(); log.Info("is a 1280"); return(boards.b1280); } } } if (serialPort.IsOpen) { serialPort.Close(); } log.Warn("Not a 1280"); Thread.Sleep(500); serialPort.DtrEnable = true; serialPort.BaudRate = 115200; serialPort.Open(); Thread.Sleep(100); a = 0; while (a < 4) { byte[] temp = new byte[] { 0x6, 0, 0, 0, 0 }; temp = BoardDetect.genstkv2packet(serialPort, temp); a++; Thread.Sleep(50); try { if (temp[0] == 6 && temp[1] == 0 && temp.Length == 2) { serialPort.Close(); //HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\USB\VID_2341&PID_0010\640333439373519060F0\Device Parameters if (!MainV2.MONO && !Thread.CurrentThread.CurrentCulture.IsChildOf(CultureInfoEx.GetCultureInfo("zh-Hans"))) { ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SerialPort"); // Win32_USBControllerDevice ManagementObjectSearcher searcher = new ManagementObjectSearcher(query); foreach (ManagementObject obj2 in searcher.Get()) { //Console.WriteLine("Dependant : " + obj2["Dependent"]); // all apm 1-1.4 use a ftdi on the imu board. /* obj2.Properties.ForEach(x => * { * try * { * log.Info(((PropertyData)x).Name.ToString() + " = " + ((PropertyData)x).Value.ToString()); * } * catch { } * }); */ // check vid and pid if (obj2.Properties["PNPDeviceID"].Value.ToString().Contains(@"USB\VID_2341&PID_0010")) { // check port name as well if ( obj2.Properties["Name"].Value.ToString() .ToUpper() .Contains(serialPort.PortName.ToUpper())) { log.Info("is a 2560-2"); return(boards.b2560v2); } } } log.Info("is a 2560"); return(boards.b2560); } } } catch { } } serialPort.Close(); log.Warn("Not a 2560"); if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a APM 2+?", "APM 2+", MessageBoxButtons.YesNo)) { return(boards.b2560v2); } else { if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a PX4/PIXHAWK?", "PX4/PIXHAWK", MessageBoxButtons.YesNo)) { if ((int)DialogResult.Yes == CustomMessageBox.Show("Is this a PIXHAWK?", "PIXHAWK", MessageBoxButtons.YesNo)) { return(boards.px4v2); } return(boards.px4); } else { return(boards.b2560); } } }
private void Verify_Handshake(Handshake handshake) { using (var com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (var com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { 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.WriteByte(XOnOff.XOFF); Thread.Sleep(250); } // Write a block of random data asynchronously so we can verify some things while the write call is blocking Task task = Task.Run(() => WriteRandomDataBlock(com1, TCSupport.MinimumBlockingByteCount)); TCSupport.WaitForTaskToStart(task); TCSupport.WaitForWriteBufferToLoad(com1, TCSupport.MinimumBlockingByteCount); // 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.WriteByte(XOnOff.XON); } // Wait till write finishes TCSupport.WaitForTaskCompletion(task); // Verify that the correct number of bytes are in the buffer // (There should be nothing because it's all been transmitted after the flow control was released) 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); } } }
void getAvilablePort() { string[] ports = SerialPort.GetPortNames(); }
void TryConfigurePort(SerialPort port, int slice) { try { TrySetPortName(port, ComPortIn[slice].Name); } catch (Exception e) { FLogger.Log(e); } try { TrySetBaudRate(port, BaudRateIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetDataBits(port, DataBitsIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetStopBits(port, StopBitsIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetParity(port, ParityIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetHandshake(port, HandshakeIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetDtrEnable(port, DtrEnableIn[slice]); } catch (Exception e) { FLogger.Log(e); } try { TrySetRtsEnable(port, RtsEnableIn[slice]); } catch (Exception e) { FLogger.Log(e); } }
/// <summary> /// Initializes a new instance with the given com port. /// </summary> /// <param name="port"></param> public SerialPortPacketTransport(SerialPort port) { Port = port; }