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

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

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

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

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

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

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

Sign up to vote on this title
UsefulNot useful