RE: How to get data from com port (ex. COM8) ?
From: Daniel Strigl (DanielStrigl_at_discussions.microsoft.com)
Date: 09/06/04
- Next message: Daniel Strigl: "RE: IRDA device-to-device File Transfer"
- Previous message: Andrey Yatsyk: "Re: What tools should I start with?"
- In reply to: alan: "How to get data from com port (ex. COM8) ?"
- Messages sorted by: [ date ] [ thread ]
Date: Mon, 6 Sep 2004 01:15:07 -0700
Here is a sample code, working with the OpenNetCF Smart Device Framework v1.2:
//////////////////////////////////////////////////////////////////////
//
// IRDA Port class, a class for IRDA support.
//
// Copyright (c) 2004, Daniel Strigl.
//
// License:
// --------
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this source code; if not, write to the Free
// Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
// MA 02111-1307 USA.
//
// Author: Daniel Strigl [http://www.hh-system.com/danielstrigl]
//
//////////////////////////////////////////////////////////////////////
using System;
using System.Diagnostics;
using OpenNETCF.Win32;
using OpenNETCF.IO.Serial;
namespace IrdaMobile.Net
{
public class IrdaPort: IDisposable
{
private Port port;
private bool disposed = false;
public static int FindPortIndex()
{
int index = 0;
RegistryKey subKey = null;
//
// Try to read the port index from the key
"HKEY_LOCAL_MACHINE\Drivers\BuiltIn\IrDA" value "Index".
//
try
{
subKey = Registry.LocalMachine.OpenSubKey(@"Drivers\BuiltIn\IrDA");
if (subKey != null && subKey.ValueCount > 0)
index = Convert.ToInt32(subKey.GetValue("Index", 0));
}
catch
{
}
finally
{
if (subKey != null)
subKey.Close();
}
if (index != 0)
return index;
//
// Try to read the port index from the key "HKEY_LOCAL_MACHINE\Comm\IrDA"
value "Port".
//
try
{
subKey = Registry.LocalMachine.OpenSubKey(@"Comm\IrDA");
if (subKey != null && subKey.ValueCount > 0)
index = Convert.ToInt32(subKey.GetValue("Port", 0));
}
catch
{
}
finally
{
if (subKey != null)
subKey.Close();
}
if (index != 0)
return index;
//
// Read the "Bind" value from the key
"HKEY_LOCAL_MACHINE\Comm\IrDA\Linkage".
//
try
{
subKey = Registry.LocalMachine.OpenSubKey(@"Comm\IrDA\Linkage");
if (subKey != null && subKey.ValueCount > 0)
{
string str = null;
try
{
str = (string) subKey.GetValue("Bind", null);
}
catch (InvalidCastException)
{
try
{
str = ((string []) subKey.GetValue("Bind", null))[0];
}
catch (InvalidCastException)
{
}
}
if (str != null && str.Length > 0)
{
RegistryKey newSubKey = null;
//
// Now read the value "Port" from the key
"HKEY_LOCAL_MACHINE\Comm\[Bind]\Parms",
// where [Bind] is the previously found sub key.
//
try
{
#if DEBUG
// System.Windows.Forms.MessageBox.Show("Bind: " +
string.Format(@"HKEY_LOCAL_MACHINE\Comm\{0}\Parms", str));
#endif
newSubKey =
Registry.LocalMachine.OpenSubKey(string.Format(@"Comm\{0}\Parms", str));
if (newSubKey != null && newSubKey.ValueCount > 0)
index = Convert.ToInt32(newSubKey.GetValue("Port", 0));
}
catch
{
}
finally
{
if (newSubKey != null)
newSubKey.Close();
}
}
}
}
catch
{
}
finally
{
if (subKey != null)
subKey.Close();
}
if (index != 0)
return index;
//
// Try to read the port index from the key
"HKEY_LOCAL_MACHINE\Drivers\BuiltIn\IrCOMM" value "Index".
//
try
{
subKey = Registry.LocalMachine.OpenSubKey(@"Drivers\BuiltIn\IrCOMM");
if (subKey != null && subKey.ValueCount > 0)
index = Convert.ToInt32(subKey.GetValue("Index", 0));
}
catch
{
}
finally
{
if (subKey != null)
subKey.Close();
}
return index;
}
public IrdaPort(int ComPort)
{
Debug.Assert(ComPort > 0 && ComPort <= 255);
//
// Open the IRDA port.
//
DetailedPortSettings portSettings = new DetailedPortSettings();
portSettings.BasicSettings.BaudRate = BaudRates.CBR_9600;
port = new Port(string.Format("COM{0}:", ComPort), portSettings,
2048, 2048);
port.InputLen = 1;
port.SThreshold = 1;
try
{
port.IREnable = true;
}
catch (CommPortException /*ex*/)
{
#if DEBUG
// System.Windows.Forms.MessageBox.Show(ex.ToString());
#endif
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (!disposed)
{
//
// Close the IRDA port.
//
if (disposing)
port.Dispose();
}
disposed = true;
}
~IrdaPort()
{
Dispose(false);
}
public bool Enabled
{
//
// Returns whether or not the IRDA port is currently open.
//
get { return port.IsOpen; }
//
// Open / close the IRDA port.
//
set
{
if (value)
port.Open();
else
port.Close();
}
}
public void Send(string Value)
{
Debug.Assert(Value.Length > 0);
Debug.Assert(port.IsOpen);
//
// Send AT command.
//
port.Output = System.Text.Encoding.ASCII.GetBytes(Value + '\r');
}
public string WaitForResponse(int Timeout)
{
Debug.Assert(Timeout > 0);
Debug.Assert(port.IsOpen);
//
// Wait for a response.
//
char lastChar = '\0';
char penultimateChar = '\0';
bool isData = false;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
uint start = GetTickCount();
while (true)
{
//
// Has the timeout occured?
//
if ((GetTickCount() - start) >= Timeout)
return null;
//
// Receive the data from the serial port.
//
byte [] data = port.Input;
if (data != null && data.GetLength(0) > 0)
{
char currentChar = Convert.ToChar(data[0]);
if (penultimateChar == '\r' && lastChar == '\n' &&
!isData)
{
//
// Received start sequence (<CR><LF>).
//
isData = true;
}
else if (lastChar == '\r' && currentChar == '\n' &&
isData)
{
//
// Received end sequence (<CR><LF>).
//
break;
}
//
// Add the character to the string.
//
if (isData && !Char.IsControl(currentChar))
sb.Append(currentChar);
penultimateChar = lastChar;
lastChar = currentChar;
//
// Reset the idle timeout since data was received.
//
start = GetTickCount();
}
else
{
System.Threading.Thread.Sleep(100);
}
}
return sb.ToString();
}
//
// This function returns the number of milliseconds since boot time.
//
[System.Runtime.InteropServices.DllImport("coredll.dll")]
private static extern UInt32 GetTickCount();
}
}
using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
namespace IrdaMobile.Net
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.ColumnHeader columnHeader1;
private System.Windows.Forms.ColumnHeader columnHeader2;
private System.Windows.Forms.ComboBox comboPort;
private System.Windows.Forms.Button cmdRead;
private System.Windows.Forms.TextBox textPhone;
private System.Windows.Forms.TextBox textModel;
private System.Windows.Forms.ListView lviewNumbers;
private System.Windows.Forms.Label labelEntries;
private System.Windows.Forms.Label label3;
private const int TIMEOUT = 5000;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
for (int n = 1; n <= 255; n++)
comboPort.Items.Add(string.Format("COM{0}", n));
int index = IrdaPort.FindPortIndex();
comboPort.SelectedIndex =
(index > 0 && index <= 255) ? (index - 1) : 2;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new
System.Resources.ResourceManager(typeof(Form1));
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.label1 = new System.Windows.Forms.Label();
this.comboPort = new System.Windows.Forms.ComboBox();
this.textPhone = new System.Windows.Forms.TextBox();
this.textModel = new System.Windows.Forms.TextBox();
this.lviewNumbers = new System.Windows.Forms.ListView();
this.columnHeader1 = new System.Windows.Forms.ColumnHeader();
this.columnHeader2 = new System.Windows.Forms.ColumnHeader();
this.labelEntries = new System.Windows.Forms.Label();
this.cmdRead = new System.Windows.Forms.Button();
this.label3 = new System.Windows.Forms.Label();
//
// pictureBox1
//
this.pictureBox1.Image =
((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(8, 8);
this.pictureBox1.Size = new System.Drawing.Size(76, 109);
//
// label1
//
this.label1.Location = new System.Drawing.Point(96, 11);
this.label1.Size = new System.Drawing.Size(40, 16);
this.label1.Text = "Port:";
//
// comboPort
//
this.comboPort.Location = new System.Drawing.Point(136, 8);
this.comboPort.Size = new System.Drawing.Size(96, 24);
//
// textPhone
//
this.textPhone.Location = new System.Drawing.Point(96, 64);
this.textPhone.ReadOnly = true;
this.textPhone.Size = new System.Drawing.Size(136, 22);
this.textPhone.Text = "";
//
// textModel
//
this.textModel.Location = new System.Drawing.Point(96, 96);
this.textModel.ReadOnly = true;
this.textModel.Size = new System.Drawing.Size(136, 22);
this.textModel.Text = "";
//
// lviewNumbers
//
this.lviewNumbers.Columns.Add(this.columnHeader1);
this.lviewNumbers.Columns.Add(this.columnHeader2);
this.lviewNumbers.FullRowSelect = true;
this.lviewNumbers.HeaderStyle =
System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lviewNumbers.Location = new System.Drawing.Point(8, 128);
this.lviewNumbers.Size = new System.Drawing.Size(224, 124);
this.lviewNumbers.View = System.Windows.Forms.View.Details;
//
// columnHeader1
//
this.columnHeader1.Text = "Name";
this.columnHeader1.Width = 110;
//
// columnHeader2
//
this.columnHeader2.Text = "Number";
this.columnHeader2.Width = 111;
//
// labelEntries
//
this.labelEntries.Location = new System.Drawing.Point(8, 265);
this.labelEntries.Text = "0 Entries";
//
// cmdRead
//
this.cmdRead.Location = new System.Drawing.Point(120, 261);
this.cmdRead.Size = new System.Drawing.Size(112, 24);
this.cmdRead.Text = "&Read ...";
this.cmdRead.Click += new System.EventHandler(this.cmdRead_Click);
//
// label3
//
this.label3.Location = new System.Drawing.Point(96, 40);
this.label3.Size = new System.Drawing.Size(136, 20);
this.label3.Text = "Phone:";
//
// Form1
//
this.ClientSize = new System.Drawing.Size(240, 296);
this.Controls.Add(this.label3);
this.Controls.Add(this.cmdRead);
this.Controls.Add(this.labelEntries);
this.Controls.Add(this.lviewNumbers);
this.Controls.Add(this.textModel);
this.Controls.Add(this.textPhone);
this.Controls.Add(this.comboPort);
this.Controls.Add(this.label1);
this.Controls.Add(this.pictureBox1);
this.MinimizeBox = false;
this.Text = "IrdaMobile.Net";
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
Application.Run(new Form1());
}
private void cmdRead_Click(object sender, System.EventArgs e)
{
IrdaPort irdaPort = null;
//
// Change cursor into wait cursor.
//
Cursor.Current = Cursors.WaitCursor;
try
{
//
// Try to open the IRDA port.
//
irdaPort = new IrdaPort(comboPort.SelectedIndex + 1);
irdaPort.Enabled = true;
textPhone.Text = "";
textModel.Text = "";
lviewNumbers.Items.Clear();
lviewNumbers.Invalidate();
lviewNumbers.Update();
labelEntries.Text = "0 Entries";
labelEntries.Invalidate();
labelEntries.Update();
//
// Try to connect to the Mobile Phone.
//
// Command : AT<CR>
//
// Valid response: <CR><LF>OK<CR><LF>
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
irdaPort.Send("AT");
string response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
else if (response.IndexOf("OK") == -1)
throw new Exception("Wrong response.");
//
// Request the manufacturer identification.
//
// Command : AT+CGMI<CR>
//
// Valid response: <CR><LF>manufacturer<CR><LF>
// <CR><LF>OK<CR><LF>
//
// manufacturer ... manufacturer identification
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
irdaPort.Send("AT+CGMI");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
string phone = response;
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
else if (response.IndexOf("OK") == -1)
throw new Exception("Wrong response.");
textPhone.Text = phone;
//
// Request the model identification.
//
// Command : AT+CGMM<CR>
//
// Valid response: <CR><LF>model<CR><LF>
// <CR><LF>OK<CR><LF>
//
// model ... model identification
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
irdaPort.Send("AT+CGMM");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
string model = response;
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
else if (response.IndexOf("OK") == -1)
throw new Exception("Wrong response.");
textModel.Text = model;
//
// Select the phonebook memory storage where phonebook commands operate.
//
// Command : AT+CPBS=storage<CR>
//
// storage ... memory where phonebook commands operate
//
// "FD" ... SIM fixdialling-phonebook
// "LD" ... SIM last-dialling-phonebook
// "ME" ... ME phonebook
// "MT" ... combined ME and SIM phonebook
// "SM" ... SIM phonebook
// "TA" ... TA phonebook
//
// Valid response: <CR><LF>OK<CR><LF>
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
irdaPort.Send("AT+CPBS=\"SM\"");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("ERROR") > -1)
throw new Exception("Invalid command.");
else if (response.IndexOf("OK") == -1)
throw new Exception("Wrong response.");
//
// Read the size of the selected phonebook memory.
//
// Command : AT+CPBR=?<CR>
//
// Valid response: <CR><LF>+CPBR: (index-list),nlength,tlength<CR><LF>
// <CR><LF>OK<CR><LF>
//
// index ..... integer type values in the range of
// location numbers of phonebook memory
// list ...... integer type value indicating the size of
// the selected phonebook memory
// nlength ... integer type value indicating the maximum
// length of the number field
// tlength ... integer type value indicating the maximum
// length of name field
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
irdaPort.Send("AT+CPBR=?");
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
string memory = response;
//
// Check the response.
//
response = response.ToUpper();
int sizePhoneBook = 0;
if (response.IndexOf("CPBR") > -1)
{
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("OK") > -1)
{
//
// Get the size of the phonebook memory.
//
int start = memory.IndexOf('-');
int end = memory.IndexOf(')', start + 1);
sizePhoneBook = Convert.ToInt32(memory.Substring(start + 1, end -
start - 1));
Debug.Assert(sizePhoneBook >= 0);
#if DEBUG
// MessageBox.Show("Phonebook size: " + sizePhoneBook.ToString());
#endif
}
else
{
throw new Exception("Wrong response.");
}
}
else if (response.IndexOf("ERROR") > -1)
{
throw new Exception("Invalid command.");
}
else
{
throw new Exception("Wrong response.");
}
//
// Read all phonebook entries.
//
// Command : AT+CPBR=index<CR>
//
// index ... integer type values in the
range of
// location numbers of phonebook
memory
//
// Valid response: <CR><LF>+CPBR: index, "number", type,
"name"<CR><LF>
// <CR><LF>OK<CR><LF>
//
// index .... integer type values in the
range of
// location numbers of phonebook
memory
// number ... string type phone number of
format type
// type ..... type of address octet in
integer format
// name ..... the name of the phonebook entry
//
// Response for
// an empty entry: <CR><LF>OK<CR><LF>
//
// Error response: <CR><LF>ERROR<CR><LF>
//
// <CR> ... Carriage return
// <LF> ... Line feed
//
int entries = 0;
for (int n = 1; n <= sizePhoneBook; n++)
{
irdaPort.Send(string.Format("AT+CPBR={0}", n));
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
string entry = response;
//
// Check the response.
//
response = response.ToUpper();
if (response.IndexOf("CPBR") > -1)
{
response = irdaPort.WaitForResponse(TIMEOUT);
if (response == null || response.Length == 0)
throw new Exception("Timeout, no response.");
response = response.ToUpper();
if (response.IndexOf("OK") > -1)
{
//
// Insert the name and the number in the list view.
//
int start = entry.IndexOf('\"');
int end = entry.IndexOf('\"', start + 1);
string number = entry.Substring(start + 1, end - start - 1);
#if DEBUG
// MessageBox.Show("Number: " + number);
#endif
start = entry.IndexOf('\"', end + 1);
end = entry.IndexOf('\"', start + 1);
string name = entry.Substring(start + 1, end - start - 1);
#if DEBUG
// MessageBox.Show("Name: " + name);
#endif
ListViewItem lvi = new ListViewItem(new string[] { name, number });
lviewNumbers.Items.Insert(0, lvi);
lviewNumbers.Invalidate();
lviewNumbers.Update();
labelEntries.Text = string.Format("{0} Entries", ++entries);
labelEntries.Invalidate();
labelEntries.Update();
}
else
{
throw new Exception("Wrong response.");
}
}
else if (response.IndexOf("OK") > -1)
{
//
// Empty phonebook entry.
//
continue;
}
else if (response.IndexOf("ERROR") > -1)
{
throw new Exception("Invalid command.");
}
else
{
throw new Exception("Wrong response.");
}
}
}
catch (Exception ex)
{
//
// Show error message.
//
MessageBox.Show(ex.Message, " Error", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
}
finally
{
//
// Close the IRDA port.
//
if (irdaPort != null)
irdaPort.Dispose();
//
// Back to normal cursor.
//
Cursor.Current = Cursors.Default;
}
}
}
}
Regards,
Daniel.
"alan" wrote:
> Using VB.net as develop tool? How can I get data from com
> port? thanks.
>
- Next message: Daniel Strigl: "RE: IRDA device-to-device File Transfer"
- Previous message: Andrey Yatsyk: "Re: What tools should I start with?"
- In reply to: alan: "How to get data from com port (ex. COM8) ?"
- Messages sorted by: [ date ] [ thread ]