public void Excute() { OnPreExecute(); //会调用重写的方法 SerialPortController mSerialPortController = SerialPortController.GetInstance(); //这个类只会new一次 mSerialPortController.PortName = Param.PortName; mSerialPortController.BaudRate = Param.BaudRate; mSerialPortController.Initialization((object sender, EventArgs e) => { SerialPortEventArgs mSerialPortEventArgs = e as SerialPortEventArgs; //通知异常 OnPostExecute(default(T), new Exception(mSerialPortEventArgs.ErrorMessage)); }, (object sender, EventArgs e) => { SerialPortEventArgs mSerialPortEventArgs = e as SerialPortEventArgs; recvByteArray = mSerialPortEventArgs.Data; if (null != MyProtocol && null != mSerialPortEventArgs) { //会调用重写的方法 OnPostExecute(MyProtocol.Decode(mSerialPortEventArgs.Data) as T, null); } else { //通知异常 OnPostExecute(default(T), new Exception("返回数据为空")); } }, MyProtocol); if (RequestProtocol != null && RequestProtocol.GetCommand() != SerialPortConst.COMMAND_EMPTY_VIRTUAL) { mSerialPortController.SendCommand(RequestProtocol.Encode()); Console.WriteLine("-----------------send value-----------------\n" + Util.ToHexString(RequestProtocol.Encode())); } }
protected virtual void OnDataReceived(SerialPortEventArgs pObjEventArgs) { if (DataReceived != null) { DataReceived(pObjEventArgs); } }
/// <summary> /// 串口打开事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SerialPort1_ComOpenEvent(object sender, SerialPortEventArgs e) { if (SerialPort1.IsOpen) { Dispatcher.Invoke(new Action(() => { Message(SerialPort1.GetSerialPortStatus()); btnOpenSerialPort.Content = "Close"; btnOpenSerialPort.Background = Brushes.Red; statbrMain.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0xCA, 0x51, 0x00)); cmbBaudRate.IsEnabled = false; cmbCommMethod.IsEnabled = false; cmbDataBits.IsEnabled = false; cmbParity.IsEnabled = false; cmbSerialPortName.IsEnabled = false; cmbStopbits.IsEnabled = false; btnRefreshSerialPort.IsEnabled = false; btnSendData.IsEnabled = true; MnuItmCommPort.IsEnabled = false; })); SerialPort1.ComReceiveDataEvent += SerialPort1_ComReceiveDataEvent; } else { Message(e.message); } }
private void passDataBackToUpperLayer(SerialPortEventArgs arg) { if (onDataReceived != null) { onDataReceived(this, arg); } }
public void LaserOpenComEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(LaserOpenComEvent), sender, e); return; } if (e.isOpend) //Open successfully { laserStatus.Text = laserComListCbx.Text + " Opened"; laserOpenCloseSpbtn.Text = "Close"; laserComListCbx.Enabled = false; laserBaudRateCbx.Enabled = false; laserDataBitsCbx.Enabled = false; laserStopBitsCbx.Enabled = false; laserParityCbx.Enabled = false; laserHandshakingcbx.Enabled = false; Program.SysConfig.LaserPort = laserComListCbx.Text; } else //Open failed { } }
protected void OnDeviceDisconnected(SerialPortEventArgs e) { if (DeviceDisconnected != null) { DeviceDisconnected(this, e); } }
/// <summary> /// When serial received data, will call this method /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void DataReceived(object sender, SerialDataReceivedEventArgs e) { if (sp.BytesToRead <= 0) { return; } //Thread Safety explain in MSDN: // Any public static (Shared in Visual Basic) members of this type are thread safe. // Any instance members are not guaranteed to be thread safe. // So, we need to synchronize I/O lock (thisLock) { int len = sp.BytesToRead; Byte[] data = new Byte[len]; try { sp.Read(data, 0, len); } catch (System.Exception) { //catch read exception } SerialPortEventArgs args = new SerialPortEventArgs(); args.receivedBytes = data; if (comReceiveDataEvent != null) { comReceiveDataEvent.Invoke(this, args); } } }
public virtual void OnSerialPortNotify(object sender, SerialPortEventArgs e) { if (e.TransactStatus != TransStatus.Start) { GlobalValue.SerialPortMgr.SerialPortEvent -= new SerialPortHandle(SerialPortNotify); HideWaitForm(); this.Enabled = true; } }
//////////////////////////////////////////////////////////////////////////////////////////////////// /// \fn void serialPort_DataReceived(object sender, SerialPortEventArgs e) /// /// \brief /// method that will be called when theres data waiting in the buffer. /// The received text is parsed, that it macthes the expected Nuvo telegram. /// It should start with a '#' sign and end with a 'carriage return' /// /// \author Ch. Imfeld /// \date 18.05.2009 /// /// \param sender - . /// \param e - . //////////////////////////////////////////////////////////////////////////////////////////////////// void serialPort_DataReceived(object sender, SerialPortEventArgs e) { // Add received message to the telegram _currentTelegramBuffer += e.Message; cutAndSendTelegram(); while (IsResponseTelegramComplete) { cutAndSendTelegram(); } }
public void followOpenComEvent(object sender, SerialPortEventArgs e) { if (e.isOpend) { this.followSerialOpenBtn.Text = "关闭"; } else { MessageBox.Show("打开失败"); } }
private void Worker_SerialPortEvent(SerialPortEventArgs args) { if (!args.IsSucceed) { return; } Dispatcher.Invoke(() => { txtResult.Text = JsonConvert.SerializeObject(args.Result.Data); }); }
/// <summary> /// update status bar /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void CloseComEvent(Object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(CloseComEvent), sender, e); return; } if (!e.isOpend) //close successfully { statuslabel.Text = " Closed"; } }
public void followCloseComEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(followCloseComEvent), sender, e); return; } if (!e.isOpend) { this.followSerialOpenBtn.Text = "打开"; } }
protected void SerialPortNotify(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { this.BeginInvoke(new SerialPortHandle(OnSerialPortNotify), new object[2] { sender, e }); } else { OnSerialPortNotify(sender, e); } }
/// <summary> /// Open Serial port /// </summary> /// <param name="portName"></param> /// <param name="baudRate"></param> /// <param name="dataBits"></param> /// <param name="stopBits"></param> /// <param name="parity"></param> /// <param name="handshake"></param> public void Open(string portName, String baudRate, string dataBits, string stopBits, string parity, string handshake) { if (sp.IsOpen) { Close(); } sp.PortName = portName; sp.BaudRate = Convert.ToInt32(baudRate); sp.DataBits = Convert.ToInt16(dataBits); /** * If the Handshake property is set to None the DTR and RTS pins * are then freed up for the common use of Power, the PC on which * this is being typed gives +10.99 volts on the DTR pin & +10.99 * volts again on the RTS pin if set to true. If set to false * it gives -9.95 volts on the DTR, -9.94 volts on the RTS. * These values are between +3 to +25 and -3 to -25 volts this * give a dead zone to allow for noise immunity. */ if (handshake == "None") { //Never delete this property sp.RtsEnable = true; sp.DtrEnable = true; } SerialPortEventArgs args = new SerialPortEventArgs(); try { sp.StopBits = (StopBits)Enum.Parse(typeof(StopBits), stopBits); sp.Parity = (Parity)Enum.Parse(typeof(Parity), parity); sp.Handshake = (Handshake)Enum.Parse(typeof(Handshake), handshake); sp.WriteTimeout = 1000; /*Write time out*/ sp.Open(); sp.DataReceived += new SerialDataReceivedEventHandler(DataReceived); args.isOpend = true; } catch (System.Exception) { args.isOpend = false; } if (comOpenEvent != null) { comOpenEvent.Invoke(this, args); } }
public override void Next(SerialPortEventArgs args) { var comEventArgs = new CommunicationEventArgs { Command = args.Command, DirectiveId = args.Result.Data.DirectiveId, DeviceType = args.Result.Data.DeviceType, DeviceId = args.Result.Data.DeviceId, Description = args.Message, Data = args.Result.Data }; this.Status.Handle(args.Result.SourceDirectiveType, args.Result.Data, comEventArgs); OnCommunication(comEventArgs); }
private void SerialPort1_ComReceiveDataEvent(object sender, SerialPortEventArgs e) { Dispatcher.Invoke(new Action(() => { if ((bool)chkHexDisplay.IsChecked) { txtRecvData.Text += UsrMethod.UsrConversion.Byte2HexString(e.receiveBytes); } else { txtRecvData.Text += UsrMethod.UsrConversion.Byte2String(e.receiveBytes); } RecvDataCounterBing.IntValue = SerialPort1.receiveBytesCount; txtRecvData.ScrollToEnd(); })); }
/// <summary> /// update status bar /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void OpenComEvent(Object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(OpenComEvent), sender, e); return; } if (e.isOpend) //Open successfully { statuslabel.Text = " Opend"; } else //Open failed { statuslabel.Text = "Open failed !"; } }
public void followComReceiveDataEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { try { Invoke(new Action <Object, SerialPortEventArgs>(followComReceiveDataEvent), sender, e); } catch (System.Exception) { //disable form destroy exception } return; } this.followTextBox.AppendText(Encoding.Default.GetString(e.receivedBytes)); }
private void SerialPort_OnReceived(object sender, SerialPortEventArgs e) { RunOnUiThread(() => { getTextView.Append("Data:"); }); foreach (var item in e.Data) { System.Diagnostics.Debug.WriteLine(item); RunOnUiThread(() => { getTextView.Append(item + " "); }); } RunOnUiThread(() => { getTextView.Append("\n"); }); }
/// <summary> /// Close serial port thread /// </summary> private void CloseSpThread() { SerialPortEventArgs args = new SerialPortEventArgs(); args.isOpend = false; try { sp.Close(); //close the serial port sp.DataReceived -= new SerialDataReceivedEventHandler(DataReceived); } catch (Exception) { args.isOpend = true; } if (comCloseEvent != null) { comCloseEvent.Invoke(this, args); } }
private void Instance_SerialPortEvent(SerialPortEventArgs args) { if (args.Result?.Data == null || args.Result.Data.DeviceId <= 0) { LogFactory.Create().Warnning("receive data is illness"); return; } if (!args.IsSucceed) { // 错误处理 LogFactory.Create().Warnning($"device{args.Result.Data.DeviceId} receive Directive failed"); return; } var ctrl = GetControllerById(args.Result.Data.DeviceId); ctrl?.Next(args); }
private void SerialPort1_ComComCloseEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { try { Invoke(new Action <Object, SerialPortEventArgs>(SerialPort1_ComComCloseEvent), sender, e); } catch (System.Exception) { //disable form destroy exception } return; } tstlblPortStatus.Text = SerialPort1.GetSerialPortStatus(); this.Text = SerialPort1.GetSerialPortStatus(); //statusStrip1.BackColor = btnRefresh.BackColor; tstlblConnectionSTAT.BackColor = btnRefresh.BackColor; }
public void MotorCloseComEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(MotorCloseComEvent), sender, e); return; } if (!e.isOpend) //close successfully { motorStatus.Text = laserComListCbx.Text + " Closed"; motorOpenCloseSpbtn.Text = "Open"; motorComListCbx.Enabled = true; motorBaudRateCbx.Enabled = true; motorDataBitsCbx.Enabled = true; motorStopBitsCbx.Enabled = true; motorParityCbx.Enabled = true; motorHandshakingcbx.Enabled = true; } }
private void Instance_SerialPortEvent(SerialPortEventArgs args) { if (!args.Result.Status) { return; } Dispatcher.Invoke(() => { if (args.Result.Data.DeviceId == Config.GasId) { if (args.Result.Data.DirectiveType == DirectiveTypeEnum.TryStart) { fillGasSeconds = DEFAULT_FILLGAS - 1; txtFillGas.Text = $"充气{fillGasSeconds}秒后停止"; gasTimer.Start(); } else if (args.Result.Data.DirectiveType == DirectiveTypeEnum.TryPause) { txtFillGas.Text = "充气停止"; } } }); }
/// <summary> /// 串口关闭事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void SerialPort1_ComCloseEvent(object sender, SerialPortEventArgs e) { if (!SerialPort1.IsOpen) { Dispatcher.Invoke(new Action(() => { Message("Closed"); btnOpenSerialPort.Content = "Open"; btnOpenSerialPort.Background = default; statbrMain.Background = new SolidColorBrush(Color.FromArgb(0xFF, 0x00, 0x7A, 0xCC)); cmbBaudRate.IsEnabled = true; cmbCommMethod.IsEnabled = true; cmbDataBits.IsEnabled = true; cmbParity.IsEnabled = true; cmbSerialPortName.IsEnabled = true; cmbStopbits.IsEnabled = true; btnRefreshSerialPort.IsEnabled = true; btnSendData.IsEnabled = false; MnuItmCommPort.IsEnabled = true; })); SerialPort1.ComReceiveDataEvent -= SerialPort1_ComReceiveDataEvent; } }
public void MotorOpenComEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { Invoke(new Action <Object, SerialPortEventArgs>(MotorOpenComEvent), sender, e); return; } if (e.isOpend) { motorStatus.Text = motorComListCbx.Text + " Opend"; motorOpenCloseSpbtn.Text = "Close"; motorComListCbx.Enabled = false; motorBaudRateCbx.Enabled = false; motorDataBitsCbx.Enabled = false; motorStopBitsCbx.Enabled = false; motorParityCbx.Enabled = false; motorHandshakingcbx.Enabled = false; } else { motorStatus.Text = "Open failed !"; } }
/// <summary> /// Display received data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ComReceiveDataEvent(Object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { try { Invoke(new Action <Object, SerialPortEventArgs>(ComReceiveDataEvent), sender, e); } catch (System.Exception) { //disable form destroy exception } return; } //display as hex if (receivetbx.Text.Length > 0) { receivetbx.AppendText("-"); } receivetbx.AppendText(IController.Bytes2Hex(e.receivedBytes)); //update status bar receiveBytesCount += e.receivedBytes.Length; toolStripStatusRx.Text = "Received: " + receiveBytesCount.ToString(); }
private void SerialPort1_ComReceiveDataEvent(object sender, SerialPortEventArgs e) { if (this.InvokeRequired) { try { Invoke(new Action <Object, SerialPortEventArgs>(SerialPort1_ComReceiveDataEvent), sender, e); } catch (System.Exception) { //disable form destroy exception } return; } if (rdoHexReceived.Checked) { txtReceived.Text += UsrMethod.UsrConversion.Byte2HexString(e.receiveBytes); } else { txtReceived.Text += UsrMethod.UsrConversion.Byte2String(e.receiveBytes); } tstlblReceiveCounter.Text = "R: " + SerialPort1.receiveBytesCount.ToString(); }
protected void OnInternalDataReceived(SerialPortEventArgs pObjEventArgs) { LogService.WriteSuccess(string.Format("Dato recibido: {0}", pObjEventArgs.Value)); mStrDataReceived += pObjEventArgs.Value; ProcessDataReceived(); }