You are on page 1of 7

communicationmanager; using System; using System.Text; using System.Drawing; using System.IO.Ports; using System.

Windows.Forms; //****************************************************************************** *********** // LICENSE INFORMATION //****************************************************************************** *********** // PCCom.SerialCommunication Version 1.0.0.0 // Class file for managing serial port communication // // Copyright (C) 2007 // Richard L. McCutchen // Email: richard@psychocoder.net // Created: 20OCT07 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. //****************************************************************************** *********** namespace PCComm { class CommunicationManager { #region Manager Enums /// <summary> /// enumeration to hold our transmission types /// </summary> public enum TransmissionType { Text, Hex } /// <summary> /// enumeration to hold our message types /// </summary> public enum MessageType { Incoming, Outgoing, Normal, Warning, Error }; #endregion #region Manager Variables //property variables private string _baudRate = string.Empty; private string _parity = string.Empty; private string _stopBits = string.Empty; private string _dataBits = string.Empty; private string _portName = string.Empty; private TransmissionType _transType; private RichTextBox _displayWindow; //global manager variables

} set { _portName = value.Red }.private Color[] MessageColor = { Color.Blue. } } /// <summary> /// property to hold the PortName /// of our manager class /// </summary> public string PortName { get { return _portName. } } /// /// /// /// <summary> property to hold our TransmissionType of our manager class </summary> . Color.Black. } set { _parity = value.Green. } set { _dataBits = value. Color. } } /// <summary> /// property to hold the Parity /// of our manager class /// </summary> public string Parity { get { return _parity. } } /// <summary> /// property to hold the StopBits /// of our manager class /// </summary> public string StopBits { get { return _stopBits.Orange. private SerialPort comPort = new SerialPort(). Color. } set { _baudRate = value. } } /// <summary> /// property to hold the DataBits /// of our manager class /// </summary> public string DataBits { get { return _dataBits. C olor. } set { _stopBits = value. #endregion #region Manager Properties /// <summary> /// Property to hold the BaudRate /// of our manager class /// </summary> public string BaudRate { get { return _baudRate.

Empty.Empty. _stopBits = sBits.Empty. _portName = "COM1". } set { _transType = value. } set { _displayWindow = value. strin g dBits. _portName = name. _parity = string. } } /// <summary> /// property to hold our display window /// value /// </summary> public RichTextBox DisplayWindow { get { return _displayWindow. //now add an event handler comPort. string par. } } #endregion #region Manager Constructors /// <summary> /// Constructor to set the properties of our Manager Class /// </summary> /// <param name="baud">Desired BaudRate</param> /// <param name="par">Desired Parity</param> /// <param name="sBits">Desired StopBits</param> /// <param name="dBits">Desired DataBits</param> /// <param name="name">Desired PortName</param> public CommunicationManager(string baud.public TransmissionType CurrentTransmissionType { get { return _transType. _dataBits = dBits. string name. } /// <summary> /// Comstructor to set the properties of our /// serial port communicator to nothing /// </summary> public CommunicationManager() { _baudRate = string. _parity = par. string sBits. _displayWindow = rtb. } #endregion #region WriteData public void WriteData(string msg) .DataReceived += new SerialDataReceivedEventHandler(comPort_D ataReceived). _displayWindow = null.DataReceived += new SerialDataReceivedEventHandler(comPort_D ataReceived). //add event handler comPort. RichTextBox rtb) { _baudRate = baud. _dataBits = string. _stopBits = string.Empty.

{ switch (CurrentTransmissionType) { case TransmissionType. newMsg.IsOpen == true)) comPort. ByteToHex(newMsg) + "\ n").Outgoing. //send the message to the port comPort. break.Open().SelectAll().Open(). break. msg + "\n").Write(msg).Outgoing. default: //first make sure the port is open //if its not open then open it if (!(comPort.Message).Replace(" ".Write(newMsg.Length). 0.Outgoing. //create a byte array the length of the //divided by 2 (Hex is 2 characters in length) byte[] comBuffer = new byte[msg.IsOpen == true)) comPort. break. msg + "\n").Text: //first make sure the port is open //if its not open then open it if (!(comPort. //send the message to the port comPort.Error. ""). ex. } finally { _displayWindow. } break.Length / 2]. //display the message DisplayData(MessageType. //send the message to the port comPort. //display the message DisplayData(MessageType. } catch (FormatException ex) { //display error message DisplayData(MessageType. //convert back to hex and display DisplayData(MessageType. .Write(msg). } } #endregion #region HexToByte /// <summary> /// method to convert hex string into a byte array /// </summary> /// <param name="msg">string to convert</param> /// <returns>a byte array</returns> private byte[] HexToByte(string msg) { //remove any spaces from the string msg = msg.Hex: try { //convert the message to byte array byte[] newMsg = HexToByte(msg). case TransmissionType.

//loop through the length of the provided string for (int i = 0.ScrollToCaret(). _displayWindow. //loop through each byte in the array foreach (byte data in comByte) //convert the byte to a string and add to the stringbuilder builder.Length * 3). i < msg.ToUpper(). } #endregion #region ByteToHex /// <summary> /// method to convert a byte array into a hex string /// </summary> /// <param name="comByte">byte array to convert</param> /// <returns>a hex string</returns> private string ByteToHex(byte[] comByte) { //create a new StringBuilder object StringBuilder builder = new StringBuilder(comByte. string msg) { _displayWindow.SelectionFont . })).SelectionFont = new Font(_displayWindow.Empty.ToByte(msg. 2). } #endregion #region DisplayData /// <summary> /// method to display the data to & from the port /// on the screen /// </summary> /// <param name="type">MessageType of the message</param> /// <param name="msg">Message to display</param> [STAThread] private void DisplayData(MessageType type.Invoke(new EventHandler(delegate { _displayWindow. _displayWindow.PadLeft(2.Substring(i.ToString(). 16) .ToString(data. _displayWindow. //return the converted value return builder. 16).Append(Convert.PadRig ht(3. } #endregion #region OpenPort public bool OpenPort() { try { //first check if the port is already open //if its open then close it .SelectedText = string. _displayWindow. FontStyle. i += 2) //convert each set of 2 characters to a byte //and add to the array comBuffer[i / 2] = (byte)Convert.Bold).Length. //return the array return comBuffer.SelectionColor = MessageColor[(int)type]. '0'). ' ')).AppendText(msg).

comPort.if (comPort. } } #endregion #region SetParityValues public void SetParityValues(object obj) { foreach (string str in Enum. //Parity . "Port opened at " + DateTime.Parse(_dataBits).Items.GetNames(typeof(StopBits))) { ((ComboBox)obj).Items. //set the properties of our SerialPort Object comPort.Close().StopBits = (StopBits)Enum. return false.Add(str). } } #endregion #region comPort_DataReceived /// <summary> /// method that will be called when theres data waiting in the buffer its). } catch (Exception ex) { DisplayData(MessageType.Parse(_baudRate).Add(str). //display message DisplayData(MessageType. //DataBits comPort. //BaudRate comPort. //PortName //now open the port comPort.Items.Message).GetNames(typeof(Parity))) { ((ComboBox)obj).PortName = _portName.Parse(typeof(StopBits).IsOpen == true) comPort.Parity = (Parity)Enum. _stopB //StopBits comPort.Now + "\n").Error. } } #endregion #region SetPortNameValues public void SetPortNameValues(object obj) { foreach (string str in SerialPort.Normal. } } #endregion #region SetStopBitValues public void SetStopBitValues(object obj) { foreach (string str in Enum.GetPortNames()) { ((ComboBox)obj).Add(str). _parity). //return true return true.DataBits = int.Open().BaudRate = int.Parse(typeof(Parity). ex.

//read the data and store it comPort. //display the data to the user DisplayData(MessageType.Incoming. break.Text: //read data waiting in the buffer string msg = comPort. 0. break.Read(comBuffer. default: //read data waiting in the buffer string str = comPort. break.ReadExisting().Incoming. } } #endregion } } . //user chose binary case TransmissionType.Hex: //retrieve number of bytes in the buffer int bytes = comPort.ReadExisting(). //display the data to the user DisplayData(MessageType./// </summary> /// <param name="sender"></param> /// <param name="e"></param> void comPort_DataReceived(object sender.BytesToRead. SerialDataReceivedEventArgs e) { //determine the mode the user selected (binary/string) switch (CurrentTransmissionType) { //user chose string case TransmissionType. str + "\n").Incoming. bytes). ByteToHex(comBuffer) + "\n "). //create a byte array to hold the awaiting data byte[] comBuffer = new byte[bytes]. //display the data to the user DisplayData(MessageType. msg + "\n").