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

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

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

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

ToString(). } #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.//loop through the length of the provided string for (int i = 0.ToByte(msg. 2).Length.PadLeft(2. //return the converted value return builder. string msg) { _displayWindow. 16) . i += 2) //convert each set of 2 characters to a byte //and add to the array comBuffer[i / 2] = (byte)Convert. 16).Invoke(new EventHandler(delegate { _displayWindow. ' ')). //return the array return comBuffer.ToString(data. _displayWindow. })). _displayWindow.Empty.Substring(i.Length * 3). } #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.SelectionFont = new Font(_displayWindow. FontStyle.Bold).PadRig ht(3.SelectedText = string. '0'). _displayWindow. } #endregion #region OpenPort public bool OpenPort() { try { //first check if the port is already open //if its open then close it .Append(Convert.SelectionFont . //loop through each byte in the array foreach (byte data in comByte) //convert the byte to a string and add to the stringbuilder builder.ScrollToCaret(). i < msg. _displayWindow.SelectionColor = MessageColor[(int)type].AppendText(msg).ToUpper().

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

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