// private static System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); public static void display(string Line1, string Line2, string Line3, string Line4) { System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); try { serialPort1.PortName = PortName; serialPort1.BaudRate = Convert.ToInt32(BaudRate); serialPort1.DataBits = Convert.ToInt32(DataBits); serialPort1.Parity = Parity.None; serialPort1.StopBits = StopBits.One; serialPort1.DtrEnable = true; serialPort1.RtsEnable = true; serialPort1.Open(); serialPort1.Write(new byte[] { 0x0C }, 0, 1); // byte[] data = Encoding.ASCII.GetBytes(Line1 + space1 + Line2); // your byte data; serialPort1.Write(Line1 + Line2); //Goto Bottem Line //serialPort1.Write(new byte[] { 0x0A, 0x0D }, 0, 2); //byte[] data1 = Encoding.ASCII.GetBytes(Line3 + space2 + Line4); // your byte data; serialPort1.Write(Line3 + Line4); serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; } catch (Exception) { serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; //MessageBox.Show(ex.ToString() + "----"+ PortName+"----"+ BaudRate.ToString()+"----"+ DataBits.ToString()); } }
private void button3_Click(object sender, EventArgs e) {//连接 try { if (_SP != null) { _SP.Dispose(); } _SP = new SerialPort(); _SP.PortName = comboBox1.Text; _SP.BaudRate = int.Parse(comboBox2.Text); _SP.DataBits = int.Parse(comboBox3.Text); _SP.StopBits = (StopBits)comboBox4.SelectedValue; _SP.ReadBufferSize = 1024; _SP.Parity = (Parity)comboBox5.SelectedValue; //Parity.Even; _SP.DataReceived += _SP_DataReceived; _SP.Open(); panel2.BackColor = Color.Green; } catch (Exception ex) { panel2.BackColor = Color.Red; MessageBox.Show(ex.Message); } }
public static void OpenDrawer() { System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort(); serialPort1.PortName = CashDrawPortName; serialPort1.Encoding = Encoding.ASCII; serialPort1.BaudRate = Convert.ToInt32(CashDrawBaudRate); serialPort1.Parity = System.IO.Ports.Parity.None; serialPort1.DataBits = Convert.ToInt32(CashDrawDataBits); serialPort1.StopBits = System.IO.Ports.StopBits.One; serialPort1.DtrEnable = true; try { serialPort1.Open(); serialPort1.Write(Char.ConvertFromUtf32(27) + char.ConvertFromUtf32(64)); serialPort1.Write(char.ConvertFromUtf32(27) + char.ConvertFromUtf32(112) + char.ConvertFromUtf32(0) + char.ConvertFromUtf32(5) + char.ConvertFromUtf32(5)); serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; } catch (Exception) { serialPort1.Close(); serialPort1.Dispose(); serialPort1 = null; // MessageBox.Show(ex.ToString() + "----" + CashDrawPortName + "----" + CashDrawBaudRate.ToString() + "----" + CashDrawDataBits.ToString()); } }
public bool OpenPort(int portNo, int baudRate, int dataBits, StopBits stopBites, Parity parity, Handshake handshake) { _PortNo = portNo; if (_PortNo == 0) { Debug.Assert(false, "��ЁE����趨���ںţ���������"); return(false); // û���趨�˿ں� } if (_PortObj == null) { _PortObj = SerialPortManager.Instance.GetComPortInstance(_PortNo); } if (_PortObj == null) { Debug.Print("���� COM{0}: ������.ǁE�E����û��ЁE", portNo); return(false); } else { try { if (!_PortObj.IsOpen) { _PortObj.BaudRate = baudRate; // Ĭ�����ʡ�����λ��ֹͣλ��У��λ�Ȳ��� _PortObj.DataBits = dataBits; _PortObj.StopBits = stopBites; _PortObj.Parity = parity; _PortObj.Handshake = handshake; _PortObj.DtrEnable = true; _PortObj.ReceivedBytesThreshold = 256; //m_PortObj.RtsEnable = false; //m_PortObj.DiscardNull = false; //m_PortObj.ReadBufferSize = 20480; //m_PortObj.WriteBufferSize = 10240; //m_PortObj.NewLine = string.Empty; _PortObj.ReadTimeout = 10000; _PortObj.WriteTimeout = Timeout.Infinite; _PortObj.Open(); _PortObj.ErrorReceived += new SerialErrorReceivedEventHandler(this.OnSerialErrorReceivedEvent); } else { Debug.Print("���Դ��� {0}: ʱ�����������Ѵ�������ϵͳ�еĶ���豸ʹ������ͬ�Ĵ��ںţ�ǁE�ϸ��E顣���ϵͳʹ�ù����Ĵ����豸�����ٴ��ޡ�", _PortObj.PortName); } } catch (UnauthorizedAccessException e) { // ���ڲ����ڻ��Ѿ������������ Debug.Print("���� {0}: �����ڻ��Ѿ������������", _PortObj.PortName, e.ToString()); _PortObj.Dispose(); _PortObj = null; } catch (Exception e) { Debug.Print("���� {0}: ��ʧ��", _PortObj.PortName, e.ToString()); } } return(true); }
public bool OpenPort(int portNo, int baudRate, int dataBits, StopBits stopBites, Parity parity, Handshake handshake) { _PortNo = portNo; if (_PortNo == 0) { Debug.Assert(false, "必须首先设定串口号,否则无法打开!"); return(false); // 没有设定端口号 } if (_PortObj == null) { _PortObj = SerialPortManager.Instance.GetComPortInstance(_PortNo); } if (_PortObj == null) { Debug.Print("串口 COM{0}: 不存在.请检查配置或程序.", portNo); return(false); } else { try { if (!_PortObj.IsOpen) { _PortObj.BaudRate = baudRate; // 默认速率、数据位、停止位、校验位等参数 _PortObj.DataBits = dataBits; _PortObj.StopBits = stopBites; _PortObj.Parity = parity; _PortObj.Handshake = handshake; _PortObj.DtrEnable = true; _PortObj.ReceivedBytesThreshold = 256; //m_PortObj.RtsEnable = false; //m_PortObj.DiscardNull = false; //m_PortObj.ReadBufferSize = 20480; //m_PortObj.WriteBufferSize = 10240; //m_PortObj.NewLine = string.Empty; _PortObj.ReadTimeout = 10000; _PortObj.WriteTimeout = Timeout.Infinite; _PortObj.Open(); _PortObj.ErrorReceived += new SerialErrorReceivedEventHandler(this.OnSerialErrorReceivedEvent); } else { Debug.Print("尝试打开串口 {0}: 时,发现其早已打开,可能是系统中的多个设备使用了相同的串口号!请仔细检查。如果系统使用共享的串行设备,则不再此限。", _PortObj.PortName); } } catch (UnauthorizedAccessException e) { // 串口不存在或已经被其他程序打开 Debug.Print("串口 {0}: 不存在或已经被其他程序打开", _PortObj.PortName, e.ToString()); _PortObj.Dispose(); _PortObj = null; } catch (Exception e) { Debug.Print("串口 {0}: 打开失败", _PortObj.PortName, e.ToString()); } } return(true); }
private bool identify(ref Dictionary<string, Arduino> _ArduinoMap, string _potentialArduino) { if (!_ArduinoMap.ContainsKey(_potentialArduino)) { SerialPort temp; try { temp = new SerialPort(_potentialArduino); temp.Open(); string toWrite = Arduino_Codes.IDENTITY_QUERY; temp.WriteLine(toWrite); Thread.Sleep(300); string ID = temp.ReadExisting(); if (ID.Contains(Arduino_Codes.ARM_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.ARM_IDENTITY, new Arduino(temp, Arduino_Codes.ARM_IDENTITY)); return true; } else if (ID.Contains(Arduino_Codes.WRIST_IDENTITY_RESPONSE)) { _ArduinoMap.Add(Arduino_Codes.WRIST_IDENTITY, new Arduino(temp, Arduino_Codes.WRIST_IDENTITY)); return true; } temp.Dispose(); //Gets rid of safe handle issue! Or at least appears to! } catch { return false; } } return false; }
public void Connect(String comPort) { try { serialPort = new SerialPort(); serialPort.PortName = comPort; serialPort.BaudRate = 115200; serialPort.ReadTimeout = 3000; serialPort.Open(); } catch (Exception ex) { if (serialPort.IsOpen) serialPort.Close(); serialPort.Dispose(); serialPort = null; throw ex; } CheckVersion(); serialPort.DataReceived += serialPort_DataReceived; PrepareSend(); }
public void Cancel() { if (isCanceled) { return; } isCanceled = !isCanceled; if (port.IsOpen) { port.DataReceived -= port_DataReceived; port.Close(); port.Dispose(); } if (newFileTimer.Enabled) { newFileTimer.Enabled = false; newFileTimer.Elapsed -= newFileTimer_Elapsed; newFileTimer.Dispose(); } if (writeTimer.Enabled) { writeTimer.Enabled = false; writeTimer.Elapsed -= writeTimer_Elapsed; writeTimer.Dispose(); } writeTimer_Elapsed(null, null); fs.Flush(); fs.Close(); fs.Dispose(); fileMutex.Dispose(); }
public void CreatePort(string portName) { // 默认:115200,无校验, 8数据位,1停止位 if (sensorPort == null) { sensorPort = new System.IO.Ports.SerialPort(portName, 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); } // 重新创建新的串口 else if (portName != sensorPort.PortName) { sensorPort.Close(); sensorPort.Dispose(); sensorPort = new System.IO.Ports.SerialPort(portName, 115200, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One); } if (sensorPort.IsOpen == false) { sensorPort.Open(); sensorPort.ReadTimeout = 1000; sensorPort.WriteTimeout = 10; } }
private void InitializeSerialPort(string comPort) { _SerialPort = new System.IO.Ports.SerialPort(comPort); try { Directory.CreateDirectory("Data"); _Logger.Info("Open SerialPort:" + comPort); _SerialPort.BaudRate = 9600; _SerialPort.Parity = Parity.None; _SerialPort.StopBits = StopBits.One; _SerialPort.DataBits = 8; _SerialPort.Handshake = Handshake.None; _SerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); _SerialPort.Open(); _SerialPort.RtsEnable = true; _SerialPort.DtrEnable = true; _Logger.Info("Port Status" + _SerialPort.IsOpen.ToString()); _SerialPort.RtsEnable = true; } catch (Exception ex) { _Logger.ErrorFormat("Fatal Error: Close Serial Port: {0}", ex.Message); _SerialPort.DataReceived -= new SerialDataReceivedEventHandler(DataReceivedHandler); _SerialPort.Close(); _SerialPort.Dispose(); } }
public void RequestStop() { _shouldStop = true; if (myPort != null) { myPort.Dispose(); myPort = null; } }
protected virtual void Dispose(bool disposing) { Disconnect(); if (disposing) { serialPort?.Dispose(); } }
private void CloseComm() { if (com != null) { com.Close(); com.Dispose(); com = null; } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { } Close(); serialport.Dispose(); disposed = true; } }
/// <summary> /// Close the serial port /// </summary> public override void Close() { if (SystemPort != null) { SystemPort.DataReceived -= SystemPort_DataReceived; IsConnected = false; SystemPort.Close(); SystemPort.Dispose(); SystemPort = null; } }
protected virtual void Dispose(bool disposing) { if (!disposed) { if (disposing) { serialPort.Close(); serialPort.Dispose(); } disposed = true; } }
public void Close() { if (port != null) { if (port.IsOpen) { port.Close(); } port.Dispose(); port = null; } isOpen = false; }
private void CloseSerialPort(bool useEventHandler) { if (useEventHandler) { m_spGPS.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived); } m_spGPS.Close(); m_blnSocketOpen = false; m_spGPS.Dispose(); m_spGPS = null; }
public void Dispose() { if (_port == null) { return; } if (_port.IsOpen) { Cts.Cancel(); _port.DiscardInBuffer(); _port.DiscardOutBuffer(); _port.Close(); } _port.Dispose(); }
public LunaSerial(string portName) : base() { try { port = new SerialPort(portName); port.BaudRate = 115200; port.WriteTimeout = 1000; port.ReadTimeout = 1000; port.WriteBufferSize = 1024; port.DataBits = 8; port.DiscardNull = false; port.Open(); //SendTurnOn(); } catch { port.Dispose(); throw; } }
static void Main(string[] args) { bool fClose = false; string aCom = ""; if (args.Count() > 0) aCom = args[0]; Console.WriteLine("Opening com-port: "+aCom+"..."); if (aCom == "") return; aComP = new SerialPort(aCom, 57600); aComP.DataReceived += new SerialDataReceivedEventHandler(aComP_DataReceived); try { aComP.Open(); Console.WriteLine("com-port opened."); string apath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); fLogFile = Path.Combine(apath, "_" + aCom + ".log"); Console.WriteLine("recording to \"" + fLogFile + "\"..."); File.Delete(fLogFile); try { Console.WriteLine("press \"q\" to quit."); while (Console.ReadKey().KeyChar != 'q') { } fClose = true; Console.WriteLine("closing comport..."); aComP.Close(); while (aComP.IsOpen) { Thread.Sleep(100); } Console.WriteLine("comport closed."); } finally { if (aComP.IsOpen) aComP.Close(); aComP.Dispose(); } } catch (Exception e) { Console.WriteLine("Error: " + e.Message); } }
private bool disposedValue = false; // 要检测冗余调用 protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: 释放托管状态(托管对象)。 if (serialPort != null) { serialPort.Dispose(); serialPort = null; } } // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。 // TODO: 将大型字段设置为 null。 disposedValue = true; } }
private void Discover() { EventWaitHandle waithandler = new EventWaitHandle( false, EventResetMode.AutoReset, Guid.NewGuid().ToString()); while (startDiscovering) { // possible fix for OSX's toomanyfilesexception GC.Collect(); string[] ports = SerialPort.GetPortNames(); foreach (string p in ports) { foreach (Link l in Links) { if (p == l.Address) { continue; } } SerialPort sp = new SerialPort(p, baudRate); if (DetectRoadAt(sp)) { RoadLink rl = new RoadLink(this, sp); NewLink(rl); } else { sp.Close(); sp.Dispose(); } } // discover at interval to reduce cpu usage waithandler.WaitOne(TimeSpan.FromSeconds(discoverInterval)); } }
public void ClosePort() { serial.ErrorReceived -= new Ports.SerialErrorReceivedEventHandler(serial_ErrorReceived); serial.DataReceived -= new Ports.SerialDataReceivedEventHandler(serial_DataReceived); serial.DiscardInBuffer(); serial.DiscardOutBuffer(); var stream = serial.BaseStream; stream.Flush(); stream.Close(); stream.Dispose(); serial.Close(); serial.Dispose(); serial = null; stream = null; GC.Collect(); }
public SerialBridge(string realRadioPort, string fakeRadioPort, int baud) { try { m_RealRadio = new SerialPort(realRadioPort); m_FakeRadio = new SerialPort(fakeRadioPort); m_RealRadio.BaudRate = m_FakeRadio.BaudRate = baud; m_RealRadio.Open(); m_FakeRadio.Open(); m_RealRadio.DataReceived += new SerialDataReceivedEventHandler(m_RealRadio_DataReceived); m_FakeRadio.DataReceived += new SerialDataReceivedEventHandler(m_FakeRadio_DataReceived); } catch { if (m_RealRadio != null) m_RealRadio.Dispose(); if (m_FakeRadio != null) m_FakeRadio.Dispose(); throw; } }
public void Dispose() { if (_output_thread != null) { if (_output_thread.IsAlive) { _output_thread.Abort(); } } try { if (_ser_out == null) { return; } _ser_out.Dispose(); } catch { } }
public void Stop() { try { ThreadRunFlag = false; if (SerialPortMng != null) { SerialPortMng.DiscardOutBuffer(); SerialPortMng.DiscardInBuffer(); SerialPortMng.Close(); SerialPortMng.Dispose(); } SendOrderQueue.Clear(); ReceiveDataQueue.Clear(); ReceiveData.Clear(); } catch (Exception ex) { } }
public Sender(string portName) { port = new SerialPort(); port.PortName = portName; port.WriteTimeout = Settings.Default.SerialPortTimeout; port.ReadTimeout = Settings.Default.SerialPortTimeout; try { port.Open(); foreach (var item in Settings.Default.CheckBalanceNumberList) { SendUSSD(item); Thread.Sleep(5000); } port.Close(); } catch (Exception) { port.Dispose(); return; } }
/// <summary> /// Release resources /// </summary> /// <param name="releaseSerialPort">Indicates if the serial port will be close</param> public void Dispose(bool releaseSerialPort = true) { m_IsAliveThread = false; DataReceivedEvent = null; if (releaseSerialPort) { try { if (m_serialPort != null && m_serialPort.IsOpen) { closePort(m_serialPort); m_serialPort.Dispose(); m_serialPort = null; } } catch (Exception ex) { Console.WriteLine(System.Reflection.MethodInfo.GetCurrentMethod().Name + ". Error: " + ex.Message); } } }
public DecompressieKamer(int maxTries = 3) { AreValuesUpToDate = false; _SerialPort = new SerialPort(); //RP6 default config 38400,8N1 _SerialPort.BaudRate = 38400; _SerialPort.DataBits = 8; _SerialPort.Parity = Parity.None; _SerialPort.StopBits = StopBits.One; if (!SearchForDecompressionDevice(maxTries)) { _SerialPort.Dispose(); throw new NoDeviceFoundException(); } _Message = new Message(_SerialPort); _LastTimeAlive = DateTime.Now; _LastUpdateTime = DateTime.Now; }
public static void Connect() { keyboardStateSTM = new STMKeyboardState(); string[] portNames = SerialPort.GetPortNames(); Thread readThread = new Thread(Read); foreach (string s in portNames) { serialPort = new SerialPort(); serialPort.PortName = s; serialPort.Open(); Thread connectThread = new Thread(Find); connectThread.Start(); Thread.Sleep(1000); if (connectThread.ThreadState == ThreadState.Stopped) break; else { serialPort.Close(); serialPort.Dispose(); connectThread.Abort(); } } if (serialPort.IsOpen) { isConnected = true; readThread.Start(); } else { isConnected = false; } }
private void closePort() { if (port != null && port.IsOpen) { port.DiscardInBuffer(); port.Dispose(); port.Close(); // close the port } StatusLabel.Text = "Disconnected"; StatusLabel.BackColor = Color.IndianRed; DissconnectButton.Enabled = false; BaudrateBox.Enabled = false; //baud rate DatabitBox.Enabled = false; //BFS StopbitBox.Enabled = false; //stop bit ParityBox.Enabled = false; //pairty box CommandPanelButton.Enabled = false; //you can inter the command SendPanelButton.Enabled = false; // files enabled RecievePanelButton.Enabled = false; SendPara.Enabled = false; if (ControllerParaChange != true) { ConnectButton.Enabled = true; } }
private void button2_Click(object sender, EventArgs e) { //設定連接埠為9600、n、8、1、n serialport.PortName = comboBox1.Text; serialport.BaudRate = 9600; serialport.DataBits = 8; serialport.StopBits = System.IO.Ports.StopBits.One; serialport.Parity = System.IO.Ports.Parity.None; serialport.Handshake = System.IO.Ports.Handshake.None; serialport.Encoding = Encoding.Default; //傳輸編碼方式 serialport.DataReceived += new SerialDataReceivedEventHandler(ReceiveMessage); try { serialport.Open(); label21.Text = "connect ok"; } catch (UnauthorizedAccessException uae) { serialport.Close(); serialport.Dispose(); label21.Text = "connect fall"; } //button2.Text = "連線"; }
public void Dispose() { if (!m_bDisposed) { m_bDisposed = true; try { if (null != m_SerialPort) { m_SerialPort.Dispose(); } } catch (Exception Err) { Err.ToString(); } finally { m_SerialPort = null; GC.SuppressFinalize(this); } } }
/// <summary> /// Takes reading from Atlas Scientific ElectricalConductivity Stamp /// </summary> /// <returns></returns> private float GetPPM() { float PPM = 0.0F; SerialPort sp = new SerialPort(Serial.COM2, 38400, Parity.None, 8, StopBits.One); sp.ReadTimeout = 1000; try { string command = ""; string response = ""; char inChar; // Send the temperature reading if available if (m_Temperature > 0) command = m_Temperature.ToString("F") + "\rR\r"; else command = "R\r"; Debug.Print(command); byte[] message = Encoding.UTF8.GetBytes(command); sp.Open(); sp.Write(message, 0, message.Length); sp.Flush(); Debug.Print("sending message"); // Now collect response while ((inChar = (char)sp.ReadByte()) != '\r') { response += inChar; } response = response.Split(',')[1]; // Stamp can return text if reading was not successful, so test before returning double ppmReading; if (Double.TryParse(response, out ppmReading)) PPM = (float)ppmReading; } catch (Exception e) { Debug.Print(e.StackTrace); } finally { sp.Close(); sp.Dispose(); } return PPM; }
private void AttemptConnect() { connected = false; string[] names = SerialPort.GetPortNames(); List<string> Ports = new List<string>(); foreach(string name in names) { if(name != "COM1" && name != "COM2" && name != "COM3" && name != "COM4") Ports.Add( name ); } // Check status if(Ports.Count == 0) { commStat = CommStatus.NoDevice; return; } commStat = CommStatus.NoElev8; try { bool FoundElev8 = false; for(int i = 0; i < Ports.Count && FoundElev8 == false; i++) { serial = new SerialPort( Ports[i], 115200, Parity.None, 8, StopBits.One ); serial.Open(); txBuffer[0] = (byte)'E'; txBuffer[1] = (byte)'l'; txBuffer[2] = (byte)'v'; txBuffer[3] = (byte)'8'; for(int j = 0; j < 10 && FoundElev8 == false; j++) // Keep pinging until it replies, or we give up { serial.Write( txBuffer, 0, 4 ); System.Threading.Thread.Sleep( 50 ); int bytesAvail = serial.BytesToRead; if(bytesAvail > 0) { int TestVal = 0; while(bytesAvail > 0) { int bytesRead = serial.Read( rxBuffer, 0, 1 ); if(bytesRead == 1) { TestVal = (TestVal << 8) | rxBuffer[0]; if(TestVal == (int)(('E' << 0) | ('l' << 8) | ('v' << 16) | ('8' << 24))) { FoundElev8 = true; commStat = CommStatus.Connected; break; } } } } } if(FoundElev8) { connected = true; if(ConnectionStarted != null) { ConnectionStarted(); } break; } else { serial.Close(); serial.Dispose(); serial = null; } } } catch(Exception) { return; } }
private void btnRun_Click(object sender, EventArgs e) { string SCRFile = tssStatusScrFile.Text.Trim(); txtResult.Clear(); Application.DoEvents(); if (File.Exists(SCRFile) == true) { SerialPort mySer = new SerialPort(cmbSerial.SelectedItem.ToString(), int.Parse(cmbBaud.SelectedItem.ToString())); mySer.WriteBufferSize = 1000; mySer.ReadBufferSize = (int)numRXBuffSize.Value; mySer.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cmbHandShaking.SelectedItem.ToString()); mySer.WriteTimeout = 1000; try { string[] FileAllLines = File.ReadAllLines(SCRFile); IAtScriptProcessing iAtScriptProc = new AtScriptProcessing(); var ret = iAtScriptProc.ProcessArrayString(FileAllLines); try { mySer.Open(); } catch { MessageBox.Show("Error Opening Serial Port!"); return; } btnRun.Enabled = false; foreach (var x in ret) { string temp; mySer.DiscardInBuffer(); if (x.IsSpecialCommand) { temp = String.Format("Special Command: Sending Hex Data 0x{0:X2}\r\n", x.ByteToSend); txtResult.AppendText(temp); mySer.Write(new byte[] { x.ByteToSend }, 0, 1); } else { txtResult.AppendText("Sending Command: " + x.ATCommandToSend); txtResult.AppendText("\r\n"); try { mySer.Write(x.ATCommandToSend); mySer.Write(new byte[] { 0x0D }, 0, 1); } catch { MessageBox.Show("Error Sending Data to GSM Modem!", FRM_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } } txtResult.AppendText("Delay: " + x.Delay + "msec"); txtResult.AppendText("\r\n"); Thread.Sleep(x.Delay); if (x.ReceiveData) { string readSer = mySer.ReadExisting(); if (chkBinMode.Checked) { char[] readChar = readSer.ToCharArray(); StringBuilder strb = new StringBuilder(); foreach (char mychar in readChar) { strb.AppendFormat("<0x{0:X2}>", (int)mychar); } readSer = strb.ToString(); } else if (chkShowEndHex.Checked) { for (int ctr = 0; ctr < 0x20; ctr++) { readSer = readSer.Replace(String.Format("{0}", (char)ctr), String.Format("<0x{0:X2}>", ctr)); } } txtResult.AppendText("Received Reply:\r\n"); txtResult.AppendText(readSer); txtResult.AppendText("\r\n"); } txtResult.AppendText("===========================\r\n"); } } finally { btnRun.Enabled = true; mySer.Dispose(); System.GC.Collect(); } txtResult.AppendText("===========================\r\n"); txtResult.AppendText("===========END===========\r\n"); } else { if (String.IsNullOrEmpty(SCRFile)) MessageBox.Show("Choose file first!", FRM_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Stop); else MessageBox.Show("File does not exist!", FRM_TITLE, MessageBoxButtons.OK, MessageBoxIcon.Stop); } }
/// <summary> /// 释放由创建串口所使用的非托管资源 /// </summary> public void Dispose() { COM.Dispose(); }
private void TriggerArduino() { SerialPort arduinoPort = new SerialPort(); arduinoPort.PortName = Device.ArduinoPort; arduinoPort.BaudRate = 9600; arduinoPort.Open(); arduinoPort.WriteLine(Device.ArduinoOn); int arduinoDelay = Convert.ToInt32(Device.ArduinoDelay) * 60000; Thread.Sleep(arduinoDelay); arduinoPort.WriteLine(Device.ArduinoOff); arduinoPort.Close(); arduinoPort.Dispose(); Device.Arduino = true; }
/// <summary> /// Attempt to read our data from a serial port. /// </summary> /// <param name="spName">Serial port name</param> /// <returns>name of robot attached to port</returns> private string TrySerialPort(string spName) { #if DEBUG Console.WriteLine("Trying Serial Port: " + spName); //DEBUG #endif SerialPort p = null; string robotname = null; try { p = new SerialPort(spName, _baudRate, Parity.None, 8, StopBits.One); p.Handshake = Handshake.None; p.Encoding = Encoding.ASCII; p.Open(); _serialPort = p; #if DEBUG Console.WriteLine("reading once"); //DEBUG #endif // Send the GETINFO string ScribblerResponse srp = SendCommand(new ScribblerCommand(ScribblerHelper.Commands.GET_INFO)); // GTEMP: Send twice - some problem with dongle srp = SendCommand(new ScribblerCommand(ScribblerHelper.Commands.GET_INFO)); UTF8Encoding enc = new UTF8Encoding(); string s = enc.GetString(srp.Data); if (s.Length == 0) { System.Threading.Thread.Sleep((int)(noCommsTimeout * 1.5)); #if DEBUG Console.WriteLine("reading again"); //DEBUG #endif s = p.ReadExisting(); //try again } if (s.Length == 0) { #if DEBUG Console.WriteLine("length == 0"); //DEBUG #endif throw new ScribblerProtocolException("Could not interpret Scribbler info, probably not a Scribbler robot."); } // we are receiving data. #if DEBUG Console.WriteLine("we are receiving data."); //DEBUG Console.WriteLine("received: \"" + s + "\""); #endif int index = s.IndexOf(characteristicString); //not a Scribbler robot if (index < 0) { #if DEBUG Console.WriteLine("not a Scribbler robot."); //DEBUG #endif _serialPort = null; throw new ScribblerProtocolException("Could not find magic string, not a Scribbler robot."); } // Sending Echo off command SendCommand(new ScribblerCommand(ScribblerHelper.Commands.SET_ECHO_MODE, (byte)1, (byte)1)); // Now get robotname srp = SendCommand(new ScribblerCommand(ScribblerHelper.Commands.GET_NAME)); enc = new UTF8Encoding(); robotname = enc.GetString(srp.Data); if (robotname.Length == 0) { #if DEBUG Console.WriteLine("Cannot get name"); //DEBUG #endif robotname = "Noname"; } #if DEBUG Console.WriteLine("TrySerialPort found: " + robotname); //DEBUG #endif } catch (Exception) { throw; } // catch (Exception ex) // { // throw; //#if DEBUG // Console.WriteLine("TrySerialPort caught exception: " + ex); // //throw new Exception("TrySerialPort caught exception", ex); //#endif // } finally { if (p != null && p.IsOpen) p.Close(); p.Dispose(); } return robotname; }
public bool Open(int baud = 115200) { if (_isOpen) Close(); bool result = false; try { _port = new SerialPort(_portName, baud, Parity.None, 8, StopBits.One); int openRetries = 5; bool fDone = false; do { try { _port.Open(); _port.DataReceived += _port_DataReceived; } catch (System.UnauthorizedAccessException ex) { _port.Close(); _port.Dispose(); _port = null; Debug.WriteLine("SerialPort open failed with exception : " + ex.Message); Thread.Sleep(1000); } catch (System.IO.IOException) { // this may be a CDC port - try a serial wrapper - the port parameters don't matter - only the name _port.Dispose(); _port = null; Thread.Sleep(300); _pdpPort = new pdp.SerialPort(_portName, baud, Parity.None, 8, StopBits.One); _pdpPort.Open(); new Thread(() => { PdpSerialReadLoop(); }).Start(); } fDone = (_pdpPort != null && _pdpPort.IsOpen) || (_port != null && _port.IsOpen) || (--openRetries <= 0); } while (!fDone); if ((_port != null && _port.IsOpen) || (_pdpPort != null && _pdpPort.IsOpen)) { new Thread(() => { ProcessReceivedData(); }).Start(); } result = (_pdpPort != null && _pdpPort.IsOpen) || (_port != null && _port.IsOpen); } catch { result = false; } _isOpen = result; return result; }
// nalezne vsechna pripojena zarizeni a da je do listu public void find_devices() { devices.Clear(); numberOfPorts = 0; if (!connected) { serialPort = new SerialPort(); serialPort.ReadBufferSize = 128*1024; serialPort.BaudRate = 115200; this.connectingInProgress = true; this.error = 0; foreach (string s in SerialPort.GetPortNames()) { numberOfPorts++; } int counter = 0; foreach (string s in SerialPort.GetPortNames()) { counter++; progress = (counter * 100) / numberOfPorts; try { Thread.Yield(); serialPort.PortName = s; serialPort.Open(); serialPort.Write(Defines.IDNRequest); Thread.Sleep(250); char[] msg = new char[1024]; int toRead = serialPort.BytesToRead; serialPort.Read(msg, 0, toRead); string msgInput = ""; string procesor = ""; string deviceName = ""; string version = ""; int i=0; if (toRead > 4) { for (i = 0; i < 4; i++) { msgInput = msgInput + msg[i]; } } Thread.Yield(); string msgCompare = Defines.IDN; if (msgInput.Contains(msgCompare)) { if (toRead > 10) { while (msg[i] != ' ') { procesor = procesor + msg[i]; i++; } i++; while (msg[i] != 'V') { deviceName = deviceName + msg[i]; i++; } for (int j = 0; j < 4; j++) { version = version + msg[i]; i++; } } string portname = serialPort.PortName; int baud = serialPort.BaudRate; serialPort.Close(); serialPort.Dispose(); Device tmp = new Device(portname, deviceName, procesor, version,baud); devices.Add(tmp); } else { serialPort.Close(); } } catch (Exception ex) { if (serialPort.IsOpen) { serialPort.Close(); } Console.WriteLine(ex); } } newDevices = true; this.connectingInProgress = false; } }
public static void Close(ref SerialPort sp) { sp.Close (); sp.Dispose (); }
public void Dispose() { myPort?.Close(); myPort?.Dispose(); }
public static bool SendSMSMobile(string MobNo, string MessageBody) { bool IsSend = false; try { string PortNo = ""; ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_POTSModem"); foreach (ManagementObject mo in mos.Get()) { string COMPort = mo["AttachedTo"].ToString(); SerialPort serialPort = null; try { serialPort = new SerialPort(); serialPort.PortName = COMPort; serialPort.BaudRate = 9600; serialPort.DataBits = 8; serialPort.Parity = Parity.None; serialPort.ReadTimeout = 300; serialPort.WriteTimeout = 300; serialPort.StopBits = StopBits.One; serialPort.Handshake = Handshake.None; serialPort.Open(); if (serialPort.IsOpen == true) { PortNo = COMPort; break; } } catch { } finally { serialPort.Close(); serialPort.Dispose(); } } if (PortNo.Trim().Length > 0) { MobNo = MobNo.Replace("(", ""); MobNo = MobNo.Replace(")", ""); MobNo = MobNo.Replace("+", ""); MobNo = MobNo.Replace("-", ""); MobNo = MobNo.Replace(",", ""); if (MobNo.Substring(0, 1) == "0" && MobNo.Length > 5) { MobNo = MobNo.Substring(1, MobNo.Length - 1); } if (MobNo.Trim().Length >= 10 && PortNo.Length > 0) { int MsgLength = Convert.ToInt32(MessageBody.Length); int Q = MsgLength / 160; int R = MsgLength % 160; if (R > 0) { Q = Q + 1; } for (int i = 0; i < Q; i++) { int StartIndex = i * 160; int EndIndex = 160; if (i == Q - 1) { EndIndex = R; } string Msg = MessageBody.Substring(StartIndex, EndIndex); SerialPort sp = new SerialPort(); try { #region MOBILE //System.Threading.Thread.Sleep(1000); char[] arr = new char[1]; arr[0] = (char)26; sp.PortName = PortNo; sp.BaudRate = 96000; sp.Parity = Parity.None; sp.DataBits = 8; sp.StopBits = StopBits.One; sp.Handshake = Handshake.XOnXOff; sp.DtrEnable = true; sp.RtsEnable = true; sp.NewLine = Environment.NewLine; sp.Open(); int mSpeed = 1; sp.Write("AT+CMGF=1" + Environment.NewLine); System.Threading.Thread.Sleep(200); sp.Write("AT+CSCS=GSM" + Environment.NewLine); System.Threading.Thread.Sleep(200); sp.Write("AT+CMGS=" + (char)34 + "+91" + MobNo + (char)34 + Environment.NewLine); System.Threading.Thread.Sleep(200); sp.Write(Msg + (char)26); System.Threading.Thread.Sleep(mSpeed); #endregion } catch { IsSend = false; } finally { sp.Close(); ; sp.Dispose(); } } } } } catch { IsSend = false; } return IsSend; }
/// <summary> /// Метод, выполняемый при закрытии формы во время завершения работы программы. /// </summary> private void frmModemCfg_Closing(object sender, FormClosingEventArgs e) { if (MessageBox.Show("Завершить работу с программой?", "Выход ...", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == System.Windows.Forms.DialogResult.Yes) { // Закрываем порт try { COM_Port.Close(); COM_Port.Dispose(); COM_Port = null; } catch { COM_Port.Dispose(); COM_Port = null; } // Ожидаем несколько секунд для закрытия порта System.Threading.Thread.Sleep(2000); } else { e.Cancel = true; } }
public static void SendToAPIPrint() { bool IsOpen = false; switch (Gattr.PortType) { case "并口": SendToLTP(); break; case "串口": System.IO.Ports.SerialPort sPort = new System.IO.Ports.SerialPort(); sPort.PortName = Gattr.PortName; sPort.BaudRate = 9600; sPort.DataBits = 8; sPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "1"); sPort.Parity = (Parity)Enum.Parse(typeof(Parity), "1"); sPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), "1"); IsOpen = POSUtility.Instance.OpenComPort(ref sPort); sPort.Dispose(); break; case "USB": IsOpen = POSUtility.Instance.OpenUSBPort(Gattr.PortName); break; case "驱动": Gfunc.SendToPrint(); //IsOpen = POSUtility.Instance.OpenPrinter(Gattr.PortName); break; case "网口": IsOpen = POSUtility.Instance.OpenNetPort(Gattr.PortName); break; } if (IsOpen) { if (((_listWinPrtStr != null) && (_listWinPrtStr.Count != 0))) { try { //开钱箱 IntPtr res = POSUtility.POS_KickOutDrawer(0x00, 100, 100); if ((uint)res != POSUtility.Instance.POS_SUCCESS) { MessageBox.Show("开钱箱失败!指令调用返回值:" + res.ToString(), "系统提示"); LoggerHelper.Log("MsmkLogger", "开钱箱失败!指令调用返回值:" + res.ToString(), LogEnum.SysLog); } POSUtility.POS_StartDoc(); POSUtility.POS_SetMode(0x00); POSUtility.POS_SetRightSpacing(0); POSUtility.POS_SetLineSpacing(80); foreach (t_pos_printer_out _out in _listWinPrtStr) { POSUtility.POS_FeedLine(); POSUtility.POS_S_TextOut(_out.Text, 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); } POSUtility.POS_FeedLines(4); POSUtility.POS_Reset(); POSUtility.POS_EndDoc(); _listWinPrtStr.Clear(); } catch (Exception exception) { MessageBox.Show(exception.Message, "系统提示"); LoggerHelper.Log("MsmkLogger", "API打印报错:" + exception.Message, LogEnum.SysLog); } } //关闭端口 POSUtility.Instance.ClosePrinterPort(); } else { if (Gattr.PortType != "驱动" && Gattr.PortType != "并口") { MessageBox.Show(Gattr.PortType + "端口打印机无效!", Gattr.AppTitle); LoggerHelper.Log("MsmkLogger", Gattr.PortType + "端口打印机无效!", LogEnum.SysLog); } } }
private void btnRun_Click(object sender, EventArgs e) { string SCRFile=tssStatusScrFile.Text.Trim(); txtResult.Clear(); Application.DoEvents(); if(File.Exists(SCRFile)==true) { SerialPort mySer=new SerialPort(cmbSerial.SelectedItem.ToString(),int.Parse(cmbBaud.SelectedItem.ToString())); mySer.WriteBufferSize=1000; mySer.ReadBufferSize=(int)numRXBuffSize.Value; mySer.Handshake=(Handshake)Enum.Parse( typeof(Handshake),cmbHandShaking.SelectedItem.ToString()); mySer.WriteTimeout=1000; try { string [] FileAllLines=File.ReadAllLines(SCRFile); try {mySer.Open();} catch { MessageBox.Show("Error Opening Serial Port!"); return; } btnRun.Enabled=false; foreach(string x in FileAllLines) { string temp=x.Trim(); if(temp.StartsWith(@"//")) continue; string [] spliString=temp.Split(new char[]{'|'},StringSplitOptions.RemoveEmptyEntries); if(spliString.Length!=4) continue; int delay=0; bool boolReadRx=false; string ATcmd=""; try { delay=int.Parse(spliString[2].Trim()); boolReadRx=Convert.ToBoolean(spliString[1].Trim()); ATcmd=spliString[0].Trim(); } catch { MessageBox.Show("Error Parsing Data, Please Recheck AT Script File: " + temp,FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop); return; } mySer.DiscardInBuffer(); if(ATcmd.StartsWith("__@HEX")) // if special command { txtResult.AppendText("Sending Command: " + ATcmd); txtResult.AppendText("\r\n"); try { string []splitstr=ATcmd.Split(new char[]{'='},StringSplitOptions.RemoveEmptyEntries); byte ByToSend=Convert.ToByte(splitstr[1],16); temp=String.Format("Special Command: Sending Hex Data 0x{0:X2}\r\n", ByToSend); txtResult.AppendText(temp); mySer.Write(new byte[]{ByToSend},0,1); } catch { MessageBox.Show("Error Parsing Data, Please Recheck AT Script File: " + temp,FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop); return; } } else { txtResult.AppendText("Sending Command: " + ATcmd); txtResult.AppendText("\r\n"); try { mySer.Write(ATcmd); mySer.Write(new byte[]{0x0D},0,1); } catch { MessageBox.Show("Error Sending Data to GSM Modem!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop); return; } } txtResult.AppendText("Delay: " + delay + "msec"); txtResult.AppendText("\r\n"); System.Threading.Thread.Sleep(delay); if(boolReadRx) { string readSer=mySer.ReadExisting(); if(chkBinMode.Checked) { char [] readChar= readSer.ToCharArray(); StringBuilder strb=new StringBuilder(); foreach(char mychar in readChar) { strb.AppendFormat("<0x{0:X2}>",(int)mychar); } readSer=strb.ToString(); } else if(chkShowEndHex.Checked) { for(int ctr=0;ctr<0x20;ctr++) { readSer =readSer.Replace(String.Format("{0}",(char)ctr),String.Format("<0x{0:X2}>",ctr)); } } txtResult.AppendText("Received Reply:\r\n"); txtResult.AppendText(readSer); txtResult.AppendText("\r\n"); } txtResult.AppendText("===========================\r\n"); } } finally { btnRun.Enabled=true; mySer.Dispose(); System.GC.Collect(); } txtResult.AppendText("===========================\r\n"); txtResult.AppendText("===========END===========\r\n"); } else { if(SCRFile==String.Empty) MessageBox.Show("Choose file first!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop); else MessageBox.Show("File does not exist!",FRM_TITLE,MessageBoxButtons.OK,MessageBoxIcon.Stop); } }
/// <summary> /// Given a split Serial Command this method will send the command over the serial port according to the command structure supplied. /// </summary> /// <param name="commands">An array of arguments for the method (the output of SplitSerialCommand).</param> public static void ProcessSerialCommand(string[] commands) { if (commands == null) throw new ArgumentNullException("commands"); Byte[] command = ReplaceSpecial(commands[0]); string comPort = commands[1]; int baudRate = int.Parse(commands[2]); Parity parity = (Parity)Enum.Parse(typeof(Parity), commands[3], true); int dataBits = int.Parse(commands[4]); StopBits stopBits = (StopBits)Enum.Parse(typeof(StopBits), commands[5], true); bool waitForResponse = bool.Parse(commands[6]); SerialPort serialPort = new SerialPort(comPort, baudRate, parity, dataBits, stopBits); serialPort.Open(); try { serialPort.Write(command, 0, command.Length); if (waitForResponse) { try { serialPort.ReadTimeout = 5000; serialPort.ReadByte(); } catch (Exception ex) { IrssLog.Debug("ProcessSerialCommand: {0}", ex.Message); } } } finally { serialPort.Close(); } serialPort.Dispose(); }
public MFTestResults DataRcdEvent() { if (!IsLoopback) return MFTestResults.Skip; // BUGBUG: 21216 result = MFTestResults.Fail; try { eventCount = 0; eventSerialPort = new SerialPort(Serial.COM1); // register before open eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventserialPort_DataReceived_BeforeOpen); eventSerialPort.Open(); eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen); eventSerialPort.DataReceived += new SerialDataReceivedEventHandler(eventSerialPort_DataReceived_AfterOpen2); eventSerialPort.Write(sendbuff, 0, sendbuff.Length); eventSerialPort.Flush(); for (int i = 0; i < 100; i++) { Thread.Sleep(100); if (eventCount >= 3) { result = MFTestResults.Pass; break; } } Log.Comment(eventCount + " events fired"); eventSerialPort.Close(); } catch (Exception ex) { Log.Exception(ex.Message); } finally { eventSerialPort.Dispose(); } return result; }
public static void Start(Handshake handshake) { int nWritten; // Note: zeros must be sent first to help the receiver sync after the noise generated // by the port initialization - don't send the important stuff right away...! byte[] start = { 0 }; if (handshake == Handshake.None) { Debug.Print("***** Testing No Flow Control *****"); start = new byte[] { 0, 0, 0, 0, 0, (byte)'X', (byte)'2', (byte)'3', (byte)'\r', (byte)'\n', 0 }; } else if (handshake == Handshake.XOnXOff) { Debug.Print("***** Testing SW Flow Control *****"); start = new byte[] { 0, 0, 0, 0, 0, (byte)'X', (byte)'2', (byte)'4', (byte)'\r', (byte)'\n', 0 }; } else if (handshake == Handshake.RequestToSend) { Debug.Print("***** Testing HW Flow Control *****"); start = new byte[] { 0, 0, 0, 0, 0, (byte)'X', (byte)'2', (byte)'5', (byte)'\r', (byte)'\n', 0 }; } SerialPortTest app = new SerialPortTest(); byte[] Record = new byte[c_BufferSize]; UInt32 uiRecordNumber = 0x1323; // Starting record number (pulled from a hat) SerialPort hPort = new SerialPort("COM1", (int)BaudRate.Baudrate115200); hPort.Handshake = handshake; hPort.ReadTimeout = 500; hPort.Open(); hPort.Flush(); while (0 < hPort.Read(Record, 0, Record.Length)) ; // Note: // When a hardware reset is issued to some targets prior to a deploy, the original deployed // code begins to execute for a second or two before Visual Studio is able to gain control, // halt the old deployed code and deploy the current program. // The following two second delay is to prevent this app from issuing the start record prior // to VS gaining control. Otherwise, the PC side app will get the signal to start before // the target side app has even deployed. This will result in the loss of the first three // or four data records and the test will fail. Thread.Sleep(2000); // Send out a simple signal to show the PC side test software that we're ready to go hPort.Write(start, 0, start.Length); // Test COM port handshake by flooding the port with testable sequential records // and verifying that the records arrive correctly. The handshake is verified // by causing 5 second pauses during reading which should translate to five // second pauses in the transmit as well - unless the driver buffer is obviating // the need for handshake - in which case, the buffer should be diminished or the // volume of traffic should increase until handshake must be employed. for (int i = 0; i < c_NumRecords; i++) { if (!app.ReceiveRecord(hPort, Record)) // If there were problems { Debug.Print("There were problems with test #1, record #" + toString(i + 1) + " of " + toString(c_NumRecords)); // return; // We may as well quit now } //Debug.Print(AsString(Record)); //Debug.Print(new string(System.Text.UTF8Encoding.UTF8.GetChars(Record))); if (!app.CheckRecord(uiRecordNumber, Record)) // If there were problems { Debug.Print("There were problems with test #1, record #" + toString(i + 1) + " of " + toString(c_NumRecords)); //return; // We may as well quit now } uiRecordNumber++; // Next record } for (int i = 0; i < c_NumRecords; i++) { app.CreateRecord(uiRecordNumber, Record); //Debug.Print("\nSending Record: " + uiRecordNumber); //Debug.Print(new string(System.Text.UTF8Encoding.UTF8.GetChars(Record))); if(!app.SendRecord(hPort, Record)) // If there were problems { Debug.Print("There were problems with test #2, record #" + toString(i + 1) + " of " + toString(c_NumRecords)); return; // We may as well quit now } uiRecordNumber++; } // This is just like the previous test - except that a gap of five seconds // will be inserted before receiving the rest of the records which will // hopefully hold off transmission due to a functioning handshake. for (int i = 0; i < 5; i++) { if (!app.ReceiveRecord(hPort, Record)) // If there were problems { Debug.Print("There were problems with test #3, record #" + toString(i + 1) + " of 5"); return; // We may as well quit now } if (!app.CheckRecord(uiRecordNumber, Record)) // If there were problems { return; // We may as well quit now } uiRecordNumber++; // Next record } Thread.Sleep(5000); // Do not allow reception of characters for five seconds (simulate erasing FLASH or some such) for (int i = 0; i < (c_NumRecords - 5); i++) { if (!app.ReceiveRecord(hPort, Record)) // If there were problems { Debug.Print("There were problems with test #4, record #" + toString(i + 1) + " of " + toString(c_NumRecords - 5)); return; // We may as well quit now } if (!app.CheckRecord(uiRecordNumber, Record)) // If there were problems { byte[] CRecord = new byte[c_BufferSize]; app.CreateRecord(uiRecordNumber, CRecord); Debug.Print("got: " + AsString(Record)); Debug.Print("exp: " + AsString(CRecord)); Debug.Print("There were problems with test #4, record #" + toString(i + 1) + " of " + toString(c_NumRecords - 5)); return; // We may as well quit now } uiRecordNumber++; // Next record } // During this test, the receiving unit will hopefully hold off which will // cause this transmission to also (hopefully) report the same holdoff for (int i = 0; i < c_NumRecords; i++) { app.CreateRecord(uiRecordNumber, Record); if (!app.SendRecord(hPort, Record)) // If there were problems { Debug.Print("There were problems with test #5, record #" + toString(i + 1) + " of " + toString(c_NumRecords)); return; // We may as well quit now } uiRecordNumber++; } Debug.Print("All records apparently sent and received as expected"); hPort.Dispose(); GC.WaitForPendingFinalizers(); }
private static void ScanPorts(object o, bool b) { if(Interlocked.Exchange(ref _scanBusy, 1)!=0) { return; } byte[] buf=new byte[64]; byte[] tmpBuf=new byte[64]; byte[] disconnectAll=(new MsDisconnect()).GetBytes(); bool escChar; int cnt=0, tryCnt; SerialPort port=null; int length; bool found; List<string> pns=new List<string>(); Topic dev=Topic.root.Get("/dev"); lock(dev) { var ifs=dev.children.Where(z => z.valueType==typeof(MsDevice)).Cast<DVar<MsDevice>>().Where(z => z.value!=null).Select(z => z.value).ToArray(); foreach(var devSer in ifs) { cnt++; if(devSer.state==State.Connected) { continue; } if(string.IsNullOrWhiteSpace(devSer.via)) { _scanAllPorts=true; break; } string via=devSer.via; if(via!="offline" && !pns.Exists(z => string.Equals(z, via, StringComparison.InvariantCultureIgnoreCase))) { pns.Add(via); } } } if(_scanAllPorts || cnt==0) { _scanAllPorts=false; pns.Clear(); pns.AddRange(SerialPort.GetPortNames()); } else { pns=pns.Intersect(SerialPort.GetPortNames()).ToList(); } Topic tmp; if(Topic.root.Exist("/local/cfg/MQTT-SN.Serial/whitelist", out tmp)) { var whl=tmp as DVar<string>; if(whl!=null && !string.IsNullOrEmpty(whl.value)) { var wps=whl.value.Split(';', ','); if(wps!=null && wps.Length>0) { pns=pns.Intersect(wps).ToList(); } } } if(Topic.root.Exist("/local/cfg/MQTT-SN.Serial/blacklist", out tmp)) { var bll=tmp as DVar<string>; if(bll!=null && !string.IsNullOrEmpty(bll.value)) { var bps=bll.value.Split(';', ','); if(bps!=null && bps.Length>0) { pns=pns.Except(bps).ToList(); } } } for(int i=0; i<pns.Count; i++) { if(_gates.Exists(z => z.name==pns[i])) { continue; } try { port=new SerialPort(pns[i], 38400, Parity.None, 8, StopBits.One); port.ReadBufferSize=300; port.WriteBufferSize=300; port.Open(); port.DiscardInBuffer(); SendRaw(port, disconnectAll, tmpBuf); // Send Disconnect Thread.Sleep(500); cnt=-1; tryCnt=6; escChar=false; length=-1; found=false; while(--tryCnt>0) { if(GetPacket(port, ref length, buf, ref cnt, ref escChar)) { var msgTyp=(MsMessageType)(buf[0]>1?buf[1]:buf[3]); if(msgTyp==MsMessageType.SEARCHGW || msgTyp==MsMessageType.DHCP_REQ) { // Received Ack found=true; MsGSerial gw; lock(_gates) { gw=new MsGSerial(port); _gates.Add(gw); } MsDevice.ProcessInPacket(gw, gw._gateAddr, buf, 0, cnt); break; } else if(_verbose.value) { Log.Debug("r {0}: {1} {2}", pns[i], BitConverter.ToString(buf, 0, cnt), msgTyp); } SendRaw(port, disconnectAll, tmpBuf); // Send Disconnect } Thread.Sleep(90); } if(!found) { port.Close(); continue; } } catch(Exception ex) { if(_verbose.value) { Log.Debug("MQTTS.Serial search on {0} - {1}", pns[i], ex.Message); } try { if(port!=null) { if(port!=null && port.IsOpen) { port.Close(); } port.Dispose(); } } catch(Exception) { } } port=null; } _scanBusy=0; }
private void btnPrint_Click(object sender, EventArgs e) { bool IsOpen = false; System.IO.Ports.SerialPort sPort = new System.IO.Ports.SerialPort(); switch (Port) { case "并口": SendToLTP(cboxBK.Text); break; case "串口": sPort.PortName = cboxCK.Text; sPort.BaudRate = 19200; sPort.DataBits = 8; sPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "1"); sPort.Parity = (Parity)Enum.Parse(typeof(Parity), "1"); sPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), "2"); IsOpen = POSUtility.Instance.OpenComPort(ref sPort); //sPort.Dispose(); break; case "USB": IsOpen = POSUtility.Instance.OpenUSBPort(cboxUSB.Text); break; case "驱动": MessageBox.Show("驱动打印测试与开钱箱相同!"); break; case "网口": IsOpen = POSUtility.Instance.OpenNetPort(maskedtboxIP.Text); break; } if (IsOpen) { try { POSUtility.POS_SetMode(0x00); POSUtility.POS_SetRightSpacing(0); POSUtility.POS_SetLineSpacing(80); POSUtility.POS_S_TextOut("【" + Port + "】 --打印测试", 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); POSUtility.POS_FeedLine(); POSUtility.POS_S_TextOut("--------------------------", 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); POSUtility.POS_FeedLine(); POSUtility.POS_S_TextOut("清晰程度-字体大小-打印测试", 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); POSUtility.POS_FeedLine(); POSUtility.POS_S_TextOut("--------------------------", 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); POSUtility.POS_FeedLine(); POSUtility.POS_S_TextOut(System.DateTime.Now.ToString(), 0, 1, 1, POSUtility.Instance.POS_FONT_TYPE_STANDARD, POSUtility.Instance.POS_FONT_STYLE_NORMAL); POSUtility.POS_FeedLines(4); POSUtility.POS_Reset(); } catch (Exception exception) { MessageBox.Show(exception.Message, "系统提示"); } //关闭端口 POSUtility.Instance.ClosePrinterPort(); } else { if (Port != "驱动" && Port != "并口") { MessageBox.Show("端口打开失败,请检查一下端口选择是否正确!", Gattr.AppTitle); } } sPort.Dispose(); }
private void beginSerial(object sender, EventArgs e) { setCallBack(callback); if (this.thread == null) { this.thread = new Thread(threadRun); } this.thread.Start(); string portStr = Properties.Settings.Default.portName; string[] ports = SerialPort.GetPortNames(); if (!ports.Contains(portStr)) { this.outPutText.Text += "com3 port is not exsit \n"; if (this.thread.IsAlive) { this.thread.Abort(); } this.thread = null; return; } this.port = new SerialPort(portStr, 9600); if (this.port != null && this.port.IsOpen) { port.Close(); } port.Encoding = Encoding.ASCII; if (this.receviceBox.Checked) { port.DataReceived += dataReceived; } this.sendBox.Enabled = false; this.receviceBox.Enabled = false; this.button1.Enabled = false; this.button2.Enabled = true; try { port.Open(); } catch (System.Exception ex) { this.sendBox.Enabled = true; this.receviceBox.Enabled = true; this.button1.Enabled = true; this.button2.Enabled = false; this.outPutText.Text += "com3 port is not open \n"; port.Dispose(); if (this.thread.IsAlive) { this.thread.Abort(); } this.thread = null; } }
private static string AquirePort() { foreach (string name in SerialPort.GetPortNames()) { SerialPort port = new SerialPort(name, 4800, Parity.None, 8, StopBits.One); port.ReadTimeout = (int)Timeout.TotalMilliseconds; try { port.Open(); } catch { continue; } DateTime target = DateTime.Now + Timeout; while (DateTime.Now < target) { string message; try { message = port.ReadLine(); } catch (TimeoutException) { break; } message = message.Replace("$", String.Empty); if (message.StartsWith("GPGGA") || message.StartsWith("GPGLL") || message.StartsWith("GPGSA") || message.StartsWith("GPGSV") || message.StartsWith("GPRMC") || message.StartsWith("GPVTG")) { port.Close(); port.Dispose(); return name; } } port.Close(); port.Dispose(); } throw new DeviceNotFoundException("Cannot locate NMEA device."); }
private void SaveButton_Click(object sender, EventArgs e) { byte[] buff = new byte[12]; int m_num = machineNumber * 100000 + currentNum; buff[0] = (byte)0xCA; buff[1] = (byte)0xD0; buff[2] = (byte)(lineNumber / 200); buff[3] = (byte)(lineNumber % 200); buff[4] = (byte)(m_num / (200 * 200 * 200) % 200); buff[5] = (byte)(m_num / (200 * 200) % 200); buff[6] = (byte)(m_num / (200) % 200); buff[7] = (byte)(m_num / (1) % 200); buff[8] = (byte)(codeTime / 200); buff[9] = (byte)(codeTime % 200); buff[10] = (byte)(sale % 200); buff[11] = (byte)0xCB; if(!portSelect) { foreach(string port in allPortNames) { sp = new SerialPort(port, bitRate, Parity.None, 8, StopBits.One); sp.ReadTimeout = 1; if(!sp.IsOpen) { try { sp.Open(); } catch(System.Exception ex) { sp.Dispose(); sp = null; continue; } } sp.Write(buff, 0, buff.Length); System.Threading.Thread.Sleep(20); if(SaveData()) { portSelect = true; OnSaveSucceed(); return; } } MessageBox.Show("没有找到合适的串口!<激情派对>和电脑是否连接?"); } else { sp.Write(buff, 0, buff.Length); System.Threading.Thread.Sleep(20); if(!SaveData()) { portSelect = false; MessageBox.Show("写入失败!"); } else { OnSaveSucceed(); } } }
/// <summary> /// Attempts to open and configure the serial port named in the 'port' parameter. /// Read and Write timeouts are set to 1 second. /// Baud Rate is 115200 /// </summary> /// <param name="port">The name of the serial port to open (i.e. "COM1")</param> /// <returns>True if able to open the port.</returns> public bool OpenComm(string port) { m_SerialPort = new SerialPort(port); m_SerialPort.BaudRate = 115200; m_SerialPort.DtrEnable = true; m_SerialPort.RtsEnable = true; m_SerialPort.Parity = Parity.None; m_SerialPort.StopBits = StopBits.One; m_SerialPort.ReadTimeout = 1000; m_SerialPort.WriteTimeout = 1000; try { m_SerialPort.Open(); // Work-around for serial port bug in .NET GC.SuppressFinalize(m_SerialPort.BaseStream); } catch { m_SerialPort.Dispose(); m_SerialPort = null; return false; } return true; }
// Creates the event ArduinoAvailable if any Arduino has been found that is ready to connect. // Caution, contains long operation / Thread.Sleep(ArduinoResetTime); public static bool CheckArduinoAvailable(string comPort) { if (!NamesAndPorts.Values.Contains(comPort) && SerialPort.GetPortNames().Contains(comPort)) { SerialPort sp = new SerialPort(comPort); sp.BaudRate = BaudRate; sp.DtrEnable = true; if (!sp.IsOpen) { string read = ""; string name = ""; try { // Caution, long operation! sp.Open(); GC.SuppressFinalize(sp.BaseStream); // Again f**********ck you Microsoft } catch (Exception e) { Console.WriteLine(comPort); sp.Close(); sp.Dispose(); return false; } Thread.Sleep(ArduinoResetTime); try { read = sp.ReadExisting(); } catch (Exception e) { Console.WriteLine(e); return false; } Console.WriteLine(read); // Format names if (read.StartsWith("Name<") && read.EndsWith(">;")) { name = read.Substring(5, read.Length - 7); } else { return false; } // Only send event if the name is not empty and is not already connected if (name != "" && !NamesAndPorts.Keys.Contains(name) && sp.IsOpen) { // Create the event. RaiseArduinoAvailable(new KeyValuePair<string, string>(name, comPort), sp); return true; } } } return false; }
//打印机检测 private void button1_Click(object sender, EventArgs e) { bool IsOpen = false; switch (Port) { case "并口": SendMoneyBox(cboxBK.Text); break; case "串口": System.IO.Ports.SerialPort sPort = new System.IO.Ports.SerialPort(); sPort.PortName = cboxCK.Text; sPort.BaudRate = 9600; sPort.DataBits = 8; sPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), "1"); sPort.Parity = (Parity)Enum.Parse(typeof(Parity), "1"); sPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), "1"); IsOpen = POSUtility.Instance.OpenComPort(ref sPort); sPort.Dispose(); break; case "USB": IsOpen = POSUtility.Instance.OpenUSBPort(cboxUSB.Text); break; case "驱动": Gfunc.OpenCash(); break; case "网口": IsOpen = POSUtility.Instance.OpenNetPort(maskedtboxIP.Text); break; } if (IsOpen) { try { if (Port == "并口") { //开钱箱 bool res = POSUtility.Instance.PrintESC(3); if (!res) { MessageBox.Show("开钱箱失败!指令调用返回值:" + res.ToString(), "系统提示"); LoggerHelper.Log("MsmkLogger", "开钱箱失败!指令调用返回值:" + res.ToString(), LogEnum.SysLog); } else { LoggerHelper.Log("MsmkLogger", Gattr.OperId + "通过打印设置打开钱箱", LogEnum.SysLog); } //关闭端口 POSUtility.Instance.ClosePrintLPT(); } else { IntPtr res = POSUtility.POS_KickOutDrawer(0x00, 100, 100); if ((uint)res != POSUtility.Instance.POS_SUCCESS) { MessageBox.Show("开钱箱失败!指令调用返回值:" + res.ToString(), "系统提示"); LoggerHelper.Log("MsmkLogger", "开钱箱失败!指令调用返回值:" + res.ToString(), LogEnum.SysLog); } else { LoggerHelper.Log("MsmkLogger", Gattr.OperId + "通过打印设置打开钱箱", LogEnum.SysLog); } //关闭端口 POSUtility.Instance.ClosePrinterPort(); } } catch (Exception exception) { MessageBox.Show(exception.Message, "系统提示"); } } else { if (Port != "驱动" && Port != "并口") { MessageBox.Show("端口打开失败,请检查一下端口选择是否正确!", Gattr.AppTitle); } } }
public MFTestResults ErrorRcvdEvent() { if (!IsLoopback || IsEmulator) return MFTestResults.Skip; result = MFTestResults.Pass; try { eventCount = 0; // create a buffer several bytes bigger then internal buffers byte[] buffer = Encoding.UTF8.GetBytes(new string('a', 512+40)); eventSerialPort = new SerialPort(Serial.COM1); eventSerialPort.WriteTimeout = 1000; eventSerialPort.Handshake = Handshake.None; // register events eventSerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(eventSerialPort_ErrorReceived_BeforeOpen); eventSerialPort.Open(); eventSerialPort.ErrorReceived += new SerialErrorReceivedEventHandler(eventSerialPort_ErrorReceived_AfterOpen); // Test RX overflow (no flow control) expectedError = SerialError.RXOver; eventSerialPort.Write(buffer, 0, buffer.Length / 2); Thread.Sleep(100); eventSerialPort.Write(buffer, 0, buffer.Length / 2); eventSerialPort.Close(); Thread.Sleep(500); if (eventCount == 0) { // BUGBUG: 21222 Log.Exception("Expected RXOver events fired, saw " + eventCount + " fired."); result = MFTestResults.Fail; } eventCount = 0; // Test TX overflow (flow control - HW) expectedError = SerialError.TXFull; eventSerialPort.Open(); for (int i = 0; i < 2; i++) { eventSerialPort.Write(buffer, 0, buffer.Length); } eventSerialPort.Close(); Thread.Sleep(500); if (eventCount == 0) { // BUGBUG: 21222 Log.Exception("Expected TXFull events fired, saw " + eventCount + " fired."); result = MFTestResults.Fail; } // TODO: Need to add PC based tests that allow testing Parity, Overrun, and Frame errors. This is done manually now. } catch (Exception ex) { result = MFTestResults.Fail; Log.Exception(ex.Message); } finally { eventSerialPort.Dispose(); } return result; }