Advertisement
olcayertas

JPEG data read from UART camera

Jun 17th, 2012
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.42 KB | None | 0 0
  1. #region Namespace Inclusions
  2. using System;
  3. using System.Linq;
  4. using System.Data;
  5. using System.Text;
  6. using System.Drawing;
  7. using System.IO.Ports;
  8. using System.Windows.Forms;
  9. using System.ComponentModel;
  10. using System.Collections.Generic;
  11.  
  12. using SerialPortTerminal.Properties;
  13. using System.Threading;
  14. using System.IO;
  15. #endregion
  16.  
  17. namespace SerialPortTerminal
  18. {
  19.   #region Public Enumerations
  20.   public enum DataMode { Text, Hex }
  21.   public enum LogMsgType { Incoming, Outgoing, Normal, Warning, Error };
  22.   #endregion
  23.  
  24.   public partial class frmTerminal : Form
  25.   {
  26.     #region Local Variables
  27.  
  28.     // The main control for communicating through the RS-232 port
  29.     private SerialPort comport = new SerialPort();
  30.  
  31.     // Various colors for logging info
  32.     private Color[] LogMsgTypeColor = { Color.Blue, Color.Green, Color.Black, Color.Orange, Color.Red };
  33.  
  34.     private BinaryWriter writer;
  35.  
  36.     //sFileStream str = new FileStream("image.jpeg", FileMode.Create);
  37.  
  38.     private StreamWriter file = new StreamWriter("test.txt");
  39.  
  40.     // Temp holder for whether a key was pressed
  41.     private bool KeyHandled = false;
  42.  
  43.         private Settings settings = Settings.Default;
  44.     #endregion
  45.  
  46.     #region Constructor
  47.     public frmTerminal()
  48.     {
  49.             // Load user settings
  50.             settings.Reload();
  51.  
  52.       // Build the form
  53.       InitializeComponent();
  54.  
  55.       // Restore the users settings
  56.       InitializeControlValues();
  57.  
  58.       // Enable/disable controls based on the current state
  59.       EnableControls();
  60.  
  61.       // When data is recieved through the port, call this method
  62.       comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
  63.             comport.PinChanged += new SerialPinChangedEventHandler(comport_PinChanged);
  64.  
  65.  
  66.            
  67.     }
  68.  
  69.         void comport_PinChanged(object sender, SerialPinChangedEventArgs e)
  70.         {
  71.             // Show the state of the pins
  72.             UpdatePinState();
  73.         }
  74.  
  75.         private void UpdatePinState()
  76.         {
  77.             this.Invoke(new ThreadStart(() => {
  78.                 // Show the state of the pins
  79.                 //chkCD.Checked = comport.CDHolding;
  80.                 //chkCTS.Checked = comport.CtsHolding;
  81.                 //chkDSR.Checked = comport.DsrHolding;
  82.             }));
  83.         }
  84.     #endregion
  85.  
  86.     #region Local Methods
  87.    
  88.     /// <summary> Save the user's settings. </summary>
  89.     private void SaveSettings()
  90.     {
  91.             settings.BaudRate = int.Parse(cmbBaudRate.Text);
  92.             settings.DataBits = int.Parse(cmbDataBits.Text);
  93.             settings.DataMode = CurrentDataMode;
  94.             settings.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
  95.             settings.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
  96.             settings.PortName = cmbPortName.Text;
  97.             //settings.ClearOnOpen = chkClearOnOpen.Checked;
  98.             //settings.ClearWithDTR = chkClearWithDTR.Checked;
  99.  
  100.             settings.Save();
  101.     }
  102.  
  103.     /// <summary> Populate the form's controls with default settings. </summary>
  104.     private void InitializeControlValues()
  105.     {
  106.       cmbParity.Items.Clear(); cmbParity.Items.AddRange(Enum.GetNames(typeof(Parity)));
  107.       cmbStopBits.Items.Clear(); cmbStopBits.Items.AddRange(Enum.GetNames(typeof(StopBits)));
  108.  
  109.             cmbParity.Text = settings.Parity.ToString();
  110.             cmbStopBits.Text = settings.StopBits.ToString();
  111.             cmbDataBits.Text = settings.DataBits.ToString();
  112.             cmbParity.Text = settings.Parity.ToString();
  113.             cmbBaudRate.Text = settings.BaudRate.ToString();
  114.             CurrentDataMode = settings.DataMode;
  115.  
  116.             RefreshComPortList();
  117.  
  118.             //chkClearOnOpen.Checked = settings.ClearOnOpen;
  119.             //chkClearWithDTR.Checked = settings.ClearWithDTR;
  120.  
  121.             // If it is still avalible, select the last com port used
  122.             if (cmbPortName.Items.Contains(settings.PortName)) cmbPortName.Text = settings.PortName;
  123.       else if (cmbPortName.Items.Count > 0) cmbPortName.SelectedIndex = cmbPortName.Items.Count - 1;
  124.       else
  125.       {
  126.         MessageBox.Show(this, "There are no COM Ports detected on this computer.\nPlease install a COM Port and restart this app.", "No COM Ports Installed", MessageBoxButtons.OK, MessageBoxIcon.Error);
  127.         this.Close();
  128.       }
  129.     }
  130.  
  131.     /// <summary> Enable/disable controls based on the app's current state. </summary>
  132.     private void EnableControls()
  133.     {
  134.       // Enable/disable controls based on whether the port is open or not
  135.       gbPortSettings.Enabled = !comport.IsOpen;
  136.       //txtSendData.Enabled = btnSend.Enabled = comport.IsOpen;
  137.             //chkDTR.Enabled = chkRTS.Enabled = comport.IsOpen;
  138.  
  139.       if (comport.IsOpen) btnOpenPort.Text = "&Close Port";
  140.       else btnOpenPort.Text = "&Open Port";
  141.     }
  142.  
  143.     /// <summary> Send the user's data currently entered in the 'send' box.</summary>
  144.     private void SendData()
  145.     {
  146.         /*
  147.       if (CurrentDataMode == DataMode.Text)
  148.       {
  149.         // Send the user's text straight out the port
  150.         comport.Write(txtSendData.Text);
  151.  
  152.         // Show in the terminal window the user's text
  153.         Log(LogMsgType.Outgoing, txtSendData.Text + "\n");
  154.       }
  155.       else
  156.       {
  157.         try
  158.         {
  159.           // Convert the user's string of hex digits (ex: B4 CA E2) to a byte array
  160.           byte[] data = HexStringToByteArray(txtSendData.Text);
  161.  
  162.           // Send the binary data out the port
  163.           comport.Write(data, 0, data.Length);
  164.  
  165.           // Show the hex digits on in the terminal window
  166.           Log(LogMsgType.Outgoing, ByteArrayToHexString(data) + "\n");
  167.         }
  168.         catch (FormatException)
  169.         {
  170.           // Inform the user if the hex string was not properly formatted
  171.           Log(LogMsgType.Error, "Not properly formatted hex string: " + txtSendData.Text + "\n");
  172.         }
  173.       }
  174.       txtSendData.SelectAll();*/
  175.     }
  176.  
  177.     /// <summary> Log data to the terminal window. </summary>
  178.     /// <param name="msgtype"> The type of message to be written. </param>
  179.     /// <param name="msg"> The string containing the message to be shown. </param>
  180.     private void Log(LogMsgType msgtype, string msg)
  181.     {
  182.       rtfTerminal.Invoke(new EventHandler(delegate
  183.       {
  184.         rtfTerminal.SelectedText = string.Empty;
  185.         rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
  186.         rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
  187.         rtfTerminal.AppendText(msg);
  188.         rtfTerminal.ScrollToCaret();
  189.       }));
  190.     }
  191.  
  192.     /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
  193.     /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
  194.     /// <returns> Returns an array of bytes. </returns>
  195.     private byte[] HexStringToByteArray(string s)
  196.     {
  197.       s = s.Replace(" ", "");
  198.       byte[] buffer = new byte[s.Length / 2];
  199.       for (int i = 0; i < s.Length; i += 2)
  200.         buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
  201.       return buffer;
  202.     }
  203.  
  204.     /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
  205.     /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
  206.     /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
  207.     private string ByteArrayToHexString(byte[] data)
  208.     {
  209.       StringBuilder sb = new StringBuilder(data.Length * 3);
  210.       foreach (byte b in data)
  211.           sb.Append(Convert.ToString(b, 16));//(b,16).PadLeft(2, '0').PadRight(3, ' ')
  212.       return sb.ToString().ToUpper();
  213.     }
  214.     #endregion
  215.  
  216.     #region Local Properties
  217.     private DataMode CurrentDataMode
  218.     {
  219.       get
  220.       {
  221.         if (rbHex.Checked) return DataMode.Hex;
  222.         else return DataMode.Text;
  223.       }
  224.       set
  225.       {
  226.         if (value == DataMode.Text) rbText.Checked = true;
  227.         else rbHex.Checked = true;
  228.       }
  229.     }
  230.     #endregion
  231.  
  232.     #region Event Handlers
  233.     private void lnkAbout_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
  234.     {
  235.       // Show the user the about dialog
  236.       (new frmAbout()).ShowDialog(this);
  237.     }
  238.    
  239.     private void frmTerminal_Shown(object sender, EventArgs e)
  240.     {
  241.       Log(LogMsgType.Normal, String.Format("Application Started at {0}\n", DateTime.Now));
  242.     }
  243.     private void frmTerminal_FormClosing(object sender, FormClosingEventArgs e)
  244.     {
  245.       // The form is closing, save the user's preferences
  246.       SaveSettings();
  247.     }
  248.  
  249.     private void rbText_CheckedChanged(object sender, EventArgs e)
  250.     { if (rbText.Checked) CurrentDataMode = DataMode.Text; }
  251.  
  252.     private void rbHex_CheckedChanged(object sender, EventArgs e)
  253.     { if (rbHex.Checked) CurrentDataMode = DataMode.Hex; }
  254.  
  255.     private void cmbBaudRate_Validating(object sender, CancelEventArgs e)
  256.     { int x; e.Cancel = !int.TryParse(cmbBaudRate.Text, out x); }
  257.  
  258.     private void cmbDataBits_Validating(object sender, CancelEventArgs e)
  259.     { int x; e.Cancel = !int.TryParse(cmbDataBits.Text, out x); }
  260.  
  261.     private void btnOpenPort_Click(object sender, EventArgs e)
  262.     {
  263.             bool error = false;
  264.  
  265.       // If the port is open, close it.
  266.             if (comport.IsOpen) {
  267.                 file.Close();
  268.                 writer.Close();
  269.                 comport.Close(); }
  270.             else
  271.             {
  272.                 // Set the port's settings
  273.                 comport.BaudRate = int.Parse(cmbBaudRate.Text);
  274.                 comport.DataBits = int.Parse(cmbDataBits.Text);
  275.                 comport.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
  276.                 comport.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
  277.                 comport.PortName = cmbPortName.Text;
  278.  
  279.                 try
  280.                 {
  281.                     // Open the port
  282.                     comport.Open();
  283.                 }
  284.                 catch (UnauthorizedAccessException) { error = true; }
  285.                 catch (IOException) { error = true; }
  286.                 catch (ArgumentException) { error = true; }
  287.  
  288.                 if (error) MessageBox.Show(this, "Could not open the COM port.  Most likely it is already in use, has been removed, or is unavailable.", "COM Port Unavalible", MessageBoxButtons.OK, MessageBoxIcon.Stop);
  289.                 else
  290.                 {
  291.                     // Show the initial pin states
  292.                     UpdatePinState();
  293.                     //chkDTR.Checked = comport.DtrEnable;
  294.                     //chkRTS.Checked = comport.RtsEnable;
  295.                 }
  296.             }
  297.  
  298.       // Change the state of the form's controls
  299.       EnableControls();
  300.  
  301.       // If the port is open, send focus to the send data box
  302.             if (comport.IsOpen)
  303.             {
  304.                 //txtSendData.Focus();
  305.                 //if (chkClearOnOpen.Checked) ClearTerminal();
  306.             }
  307.     }
  308.     private void btnSend_Click(object sender, EventArgs e)
  309.     { SendData(); }
  310.  
  311.     private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
  312.     {
  313.             // If the com port has been closed, do nothing
  314.             if (!comport.IsOpen) return;
  315.  
  316.       // This method will be called when there is data waiting in the port's buffer
  317.  
  318.       // Determain which mode (string or binary) the user is in
  319.       if (CurrentDataMode == DataMode.Text)
  320.       {
  321.         // Read all the data waiting in the buffer
  322.         string data = comport.ReadExisting();
  323.  
  324.         file.Write(data);
  325.         // Display the text to the user in the terminal
  326.         Log(LogMsgType.Incoming, data);
  327.       }
  328.       else
  329.       {
  330.         // Obtain the number of bytes waiting in the port's buffer
  331.         int bytes = comport.BytesToRead;
  332.  
  333.         // Create a byte array buffer to hold the incoming data
  334.         byte[] buffer = new byte[bytes];
  335.  
  336.         // Read the data from the port and store it in our buffer
  337.         comport.Read(buffer, 0, bytes);
  338.  
  339.         //file.WriteLine(ByteArrayToHexString(buffer);
  340.         using(FileStream stream = new FileStream("image.jpeg", FileMode.Append)){
  341.             using (writer = new BinaryWriter(stream))
  342.             {
  343.                 writer.Write(buffer);
  344.             }
  345.         }
  346.  
  347.         // Show the user the incoming data in hex format
  348.         Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
  349.       }
  350.     }
  351.  
  352.     private void txtSendData_KeyDown(object sender, KeyEventArgs e)
  353.     {
  354.       // If the user presses [ENTER], send the data now
  355.       if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); }
  356.     }
  357.     private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
  358.     { e.Handled = KeyHandled; }
  359.     #endregion
  360.  
  361.         private void chkDTR_CheckedChanged(object sender, EventArgs e)
  362.         {
  363.             //comport.DtrEnable = chkDTR.Checked;
  364.             //if (chkDTR.Checked && chkClearWithDTR.Checked) ClearTerminal();
  365.         }
  366.  
  367.         private void chkRTS_CheckedChanged(object sender, EventArgs e)
  368.         {
  369.             //comport.RtsEnable = chkRTS.Checked;
  370.         }
  371.  
  372.         private void btnClear_Click(object sender, EventArgs e)
  373.         {
  374.             ClearTerminal();
  375.         }
  376.  
  377.         private void ClearTerminal()
  378.         {
  379.             rtfTerminal.Clear();
  380.         }
  381.  
  382.         private void tmrCheckComPorts_Tick(object sender, EventArgs e)
  383.         {
  384.             // checks to see if COM ports have been added or removed
  385.             // since it is quite common now with USB-to-Serial adapters
  386.             RefreshComPortList();
  387.         }
  388.  
  389.         private void RefreshComPortList()
  390.         {
  391.             // Determain if the list of com port names has changed since last checked
  392.             string selected = RefreshComPortList(cmbPortName.Items.Cast<string>(), cmbPortName.SelectedItem as string, comport.IsOpen);
  393.  
  394.             // If there was an update, then update the control showing the user the list of port names
  395.             if (!String.IsNullOrEmpty(selected))
  396.             {
  397.                 cmbPortName.Items.Clear();
  398.                 cmbPortName.Items.AddRange(OrderedPortNames());
  399.                 cmbPortName.SelectedItem = selected;
  400.             }
  401.         }
  402.  
  403.         private string[] OrderedPortNames()
  404.         {
  405.             // Just a placeholder for a successful parsing of a string to an integer
  406.             int num;
  407.  
  408.             // Order the serial port names in numberic order (if possible)
  409.             return SerialPort.GetPortNames().OrderBy(a => a.Length > 3 && int.TryParse(a.Substring(3), out num) ? num : 0).ToArray();
  410.         }
  411.        
  412.         private string RefreshComPortList(IEnumerable<string> PreviousPortNames, string CurrentSelection, bool PortOpen)
  413.         {
  414.             // Create a new return report to populate
  415.             string selected = null;
  416.  
  417.             // Retrieve the list of ports currently mounted by the operating system (sorted by name)
  418.             string[] ports = SerialPort.GetPortNames();
  419.  
  420.             // First determain if there was a change (any additions or removals)
  421.             bool updated = PreviousPortNames.Except(ports).Count() > 0 || ports.Except(PreviousPortNames).Count() > 0;
  422.  
  423.             // If there was a change, then select an appropriate default port
  424.             if (updated)
  425.             {
  426.                 // Use the correctly ordered set of port names
  427.                 ports = OrderedPortNames();
  428.  
  429.                 // Find newest port if one or more were added
  430.                 string newest = SerialPort.GetPortNames().Except(PreviousPortNames).OrderBy(a => a).LastOrDefault();
  431.  
  432.                 // If the port was already open... (see logic notes and reasoning in Notes.txt)
  433.                 if (PortOpen)
  434.                 {
  435.                     if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
  436.                     else if (!String.IsNullOrEmpty(newest)) selected = newest;
  437.                     else selected = ports.LastOrDefault();
  438.                 }
  439.                 else
  440.                 {
  441.                     if (!String.IsNullOrEmpty(newest)) selected = newest;
  442.                     else if (ports.Contains(CurrentSelection)) selected = CurrentSelection;
  443.                     else selected = ports.LastOrDefault();
  444.                 }
  445.             }
  446.  
  447.             // If there was a change to the port list, return the recommended default selection
  448.             return selected;
  449.         }
  450.  
  451.         private void rtfTerminal_TextChanged(object sender, EventArgs e)
  452.         {
  453.  
  454.         }
  455.     }
  456. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement