Solved

Accessing serial ports using c#..

Posted on 2002-04-08
3
8,138 Views
Last Modified: 2012-06-21
Hi all,
I need to access a serial port to which a mobile(cellular phone) is connected and read an SMS message stored in the phone..
All this using c# or any other .NET supported language..
Can anyone help?

Thank you
0
Comment
Question by:egsemsem
3 Comments
 
LVL 22

Expert Comment

by:CJ_S
ID: 6927903
I do not know how (or at least not the details). But there are programs around that do exactly that. For one of our customers we have a special GSM called the Falcon. This is a machien that acts like a cellular phone but is not. On the internet we found some software that interacted with this. (you can also use windows HyperTerminal, though that will require you to know the commands).

The commands are not that easy, I can look it up tomorrow for a little reference.

Few "cellular" phones use the same commands.

I know how to talk to the serial port using VB, but haven't done anything like that with C# yet...

CJ
0
 
LVL 15

Accepted Solution

by:
Tommy Hui earned 100 total points
ID: 6961327
Here's some sample code:

using System;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;

namespace PPCReadCommPort
{
      /// <summary>
      /// Summary description for Form1.
      /// </summary>
      public class Form1 : System.Windows.Forms.Form
      {
            private System.Windows.Forms.Button btnOpenFile;
            private System.Windows.Forms.TextBox textBox1;
            private System.Windows.Forms.Button btnCloseFile;
            private System.Windows.Forms.Button btnConfigure;
            private System.Windows.Forms.TextBox textBox2;
            private System.Windows.Forms.Label label1;
            private System.Windows.Forms.Button btnReadFile;
      
            #region VS Stuff
            public Form1()
            {
                  //
                  // Required for Windows Form Designer support
                  //
                  InitializeComponent();

                  //
                  // TODO: Add any constructor code after InitializeComponent call
                  //
            }
#if COMPLETE_FRAMEWORK
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            protected override void Dispose( bool disposing )
            {
                  base.Dispose( disposing );
            }
#endif
            #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()
            {
                  this.btnOpenFile = new System.Windows.Forms.Button();
                  this.btnReadFile = new System.Windows.Forms.Button();
                  this.textBox1 = new System.Windows.Forms.TextBox();
                  this.btnCloseFile = new System.Windows.Forms.Button();
                  this.btnConfigure = new System.Windows.Forms.Button();
                  this.textBox2 = new System.Windows.Forms.TextBox();
                  this.label1 = new System.Windows.Forms.Label();
                  //
                  // btnOpenFile
                  //
                  this.btnOpenFile.Location = new System.Drawing.Point(77, 36);
                  this.btnOpenFile.Text = "Open Port";
                  this.btnOpenFile.Click += new System.EventHandler(this.btnOpenFile_Click);
                  //
                  // btnReadFile
                  //
                  this.btnReadFile.Location = new System.Drawing.Point(78, 153);
                  this.btnReadFile.Text = "Read Data";
                  this.btnReadFile.Click += new System.EventHandler(this.btnReadFile_Click);
                  //
                  // textBox1
                  //
                  this.textBox1.Location = new System.Drawing.Point(86, 10);
                  this.textBox1.Size = new System.Drawing.Size(57, 20);
                  this.textBox1.Text = "";
                  //
                  // btnCloseFile
                  //
                  this.btnCloseFile.Location = new System.Drawing.Point(77, 246);
                  this.btnCloseFile.Text = "Close Port";
                  this.btnCloseFile.Click += new System.EventHandler(this.btnCloseFile_Click);
                  //
                  // btnConfigure
                  //
                  this.btnConfigure.Location = new System.Drawing.Point(68, 118);
                  this.btnConfigure.Size = new System.Drawing.Size(98, 23);
                  this.btnConfigure.Text = "Configure Baud";
                  this.btnConfigure.Click += new System.EventHandler(this.btnConfigure_Click);
                  //
                  // textBox2
                  //
                  this.textBox2.Location = new System.Drawing.Point(95, 89);
                  this.textBox2.Size = new System.Drawing.Size(38, 20);
                  this.textBox2.Text = "";
                  //
                  // label1
                  //
                  this.label1.Location = new System.Drawing.Point(6, 178);
                  this.label1.Size = new System.Drawing.Size(230, 44);
                  //
                  // Form1
                  //
                  this.ClientSize = new System.Drawing.Size(240, 295);
                  this.Controls.Add(this.label1);
                  this.Controls.Add(this.textBox2);
                  this.Controls.Add(this.btnConfigure);
                  this.Controls.Add(this.btnCloseFile);
                  this.Controls.Add(this.textBox1);
                  this.Controls.Add(this.btnReadFile);
                  this.Controls.Add(this.btnOpenFile);
                  this.Text = "Form1";
                  this.Load += new System.EventHandler(this.Form1_Load);
                  this.Closed += new System.EventHandler(this.Form1_Closed);

            }
            #endregion

            /// <summary>
            /// The main entry point for the application.
            /// </summary>

            static void Main()
            {
                  Application.Run(new Form1());
            }

            #endregion

            int            handleSerialPort      = -1;
            bool      bCycle                        = false;
            string      port                        = "COM4:";
            int            Baudrate                  = 4800;

            # region Structures and Classes
            //[StructLayout(LayoutKind.Sequential, Pack=1)] // for desktop uncomment this line
            public class OVERLAPPED
            {
                  public int Internal;
                  public int InternalHigh;
                  public int Offset;
                  public int OffsetHigh;
                  public int hEvent;
            }

            //[StructLayout(LayoutKind.Sequential, Pack=1)]
            public struct DCB
            {
                  public int DCBlength;                    
                  public int BaudRate;
                  public int fBinary;     ///* Binary Mode (skip EOF check)    
                  public int fParity;     // Enable parity checking          
                  public int fOutxCtsFlow; // CTS handshaking on output      
                  public int fOutxDsrFlow; // DSR handshaking on output      
                  public int fDtrControl;  // DTR Flow control                
                  public int fDsrSensitivity; // DSR Sensitivity              
                  public int fTXContinueOnXoff; //Continue TX when Xoff sent
                  public int fOutX;        //Enable output X-ON/X-OFF        
                  public int fInX;         //Enable input X-ON/X-OFF        
                  public int fErrorChar;   //Enable Err Replacement          
                  public int fNull;        //Enable Null stripping          
                  public int fRtsControl;   //Rts Flow control                
                  public int fAbortOnError;  //Abort all reads and writes on Error
                  public int fDummy;      //Reserved                        
                  public Int16 wReserved;        //Not currently used              
                  public Int16 XonLim;           //Transmit X-ON threshold        
                  public Int16 XoffLim;          //Transmit X-OFF threshold        
                  public byte ByteSize;         //Number of bits/byte, 4-8        
                  public byte Parity;           //0-4=None,Odd,Even,Mark,Space    
                  public byte StopBits;         //0,1,2 = 1, 1.5, 2              
                  public char XonChar;          //Tx and Rx X-ON character        
                  public char XoffChar;         //Tx and Rx X-OFF character      
                  public char ErrorChar;        //Error replacement char          
                  public char EofChar;          //End of Input character          
                  public char EvtChar;          //Received Event character        
                  public Int16 wReserved1;       //Fill for now.

            } // end DCB Struct

            #endregion

            #region DllImports
            [DllImport("coredll.dll")]
            private static extern int SetCommState(int hCommDev, ref DCB lpDCB);

            [DllImport("coredll.dll")]
            private static extern int GetCommState(int hCommDev, ref DCB lpDCB) ;

            [DllImport("coredll.dll")]
            static extern int ReadFile(int hFile, Byte[] Buffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped ) ;

            [DllImport("coredll.dll")]
            static extern int CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, int lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, int hTemplateFile) ;

            [DllImport("coredll.dll")]
            static extern int CloseHandle(int hObject) ;
            #endregion

            private void Form1_Load(object sender, System.EventArgs e)
            {
                  textBox1.Text = port;
                  textBox2.Text = Convert.ToString(Baudrate);
            }

            private void btnOpenFile_Click(object sender, System.EventArgs e)
            {
                  port = textBox1.Text;

                  // Let's try to close the Port if we have a handle
                  CloseComm(ref handleSerialPort, port);
                  
                  handleSerialPort = CreateFile(port, unchecked((int)0x80000000) | 0x40000000, 0, 0, 3, 0, 0);
                  if (handleSerialPort < 1)
                  {
                        label1.Text = "Error: Unable to open port: " + port + " " + Convert.ToString(handleSerialPort);
                        return;
                  }

                  label1.Text = "opened " + port + Convert.ToString(handleSerialPort);
            } // end btnOpenFile_Click

            private void btnReadFile_Click(object sender, System.EventArgs e)
            {
                  int      iRc      = -1;
                  bCycle = true;
                  int            BytesToRead                  = 40;
                  int            BytesActuallyRead      = 0;
                  byte[]      Buffer;

                  if (handleSerialPort != -1)

                  {

                        // Loop and grab data from COM buffer and display in Label control
                        while (bCycle)
                        {
                              Buffer = new Byte[BytesToRead];

                              OVERLAPPED O = new OVERLAPPED();

                              iRc = ReadFile(handleSerialPort, Buffer, BytesToRead, ref BytesActuallyRead, ref O);

                              if (iRc < 1) label1.Text = "Error: Unable to read from " + port + " " + Convert.ToString(iRc);
                              else label1.Text = Encoding.GetEncoding("ASCII").GetString(Buffer,0,BytesToRead);

                              Application.DoEvents();
                        }
                  }
                  else label1.Text = "Error: Comm Port not open";

            } // end btnReadFile_Click

            private void btnConfigure_Click(object sender, System.EventArgs e)
            {

                  if (handleSerialPort != -1)
                  {

                        DCB dcb = new DCB();

                        // Not needed for NETCF
                        //dcb.DCBlength = Marshal.SizeOf(dcb);

                        // Get existing Comm State
                        GetCommState (handleSerialPort, ref dcb); // Get the default port setting information.

                        string oldbaud = dcb.BaudRate.ToString();

                        int newbaud = Baudrate;
                        
                        try { newbaud = Convert.ToInt32(textBox2.Text); }
                        catch{}

                        // Change the DCB structure settings.
                        dcb.BaudRate = newbaud; // Set to Baud rate defined in textbox
                        dcb.fBinary = 1;              // Binary mode; no EOF check
                        dcb.fParity = 1;              // Enable parity checking
                        dcb.fOutxCtsFlow = 0;         // No CTS output flow control
                        dcb.fOutxDsrFlow = 0;         // No DSR output flow control
                        dcb.fDtrControl = 1;          // DTR_CONTROL_ENABLE = 1 // DTR flow control type
                        dcb.fDsrSensitivity = 0;      // DSR sensitivity
                        dcb.fTXContinueOnXoff = 1;    // XOFF continues Tx
                        dcb.fOutX = 0;                // No XON/XOFF out flow control
                        dcb.fInX = 0;                 // No XON/XOFF in flow control
                        dcb.fErrorChar = 0;           // Disable error replacement
                        dcb.fNull = 0;                // Disable null stripping
                        dcb.fRtsControl = 1;              // RTS_CONTROL_ENABLE = 1 // RTS flow control
                        dcb.fAbortOnError = 0;        // Do not abort reads/writes on error
                        dcb.ByteSize = 8;             // Number of bits/byte, 4-8
                        dcb.Parity = 0;               // 0-4=no,odd,even,mark,space
                        dcb.StopBits = 0;             // 0,1,2 = 1, 1.5, 2

                        // Attempt to set new Comm state
                        int result = SetCommState(handleSerialPort, ref dcb);

                        if (result != 0)
                        {
                              //dwError = GetLastError(); // Could not configure the serial port.
                              label1.Text = "Error Setting State. Result: " + result.ToString();
                        }
                        else label1.Text = "was: " + oldbaud + " baud, setting to: " + newbaud.ToString() + " baud.";
                  }
                  else label1.Text = "Error: Comm Port not open";

            } // end btnConfigure_Click

            private void btnCloseFile_Click(object sender, System.EventArgs e)
            {
                  // Try to close Comm Port
                  CloseComm(ref handleSerialPort, port);
            }

            private void Form1_Closed(object sender, System.EventArgs e)
            {
                  // Attempt to close Comm port before exiting.
                  CloseComm(ref handleSerialPort, port);
            }

            private void CloseComm(ref int hComm, string strPort)
            {
                  // stop reading loop
                  bCycle = false;

                  if (hComm != -1 )
                  {
                        int result = CloseHandle(hComm);
                        if (result < 1) label1.Text = "Error: Failed to close " + strPort;
                        else
                        {
                              label1.Text = "Closed " + strPort + " Successfully";
                              hComm = -1;
                        }
                  }
            } // end CloseComm

      }// end class

}// end namespace
0
 
LVL 2

Author Comment

by:egsemsem
ID: 6982105
Sorry for the delay
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
hasOne  challenge 59 92
triangle challenge 4 79
strCount chalenge 3 51
Program to display an alert on Windows Toolbar 2 65
Purpose To explain how to place a textual stamp on a PDF document.  This is commonly referred to as an annotation, or possibly a watermark, but a watermark is generally different in that it is somewhat translucent.  Watermark’s may be text or graph…
Here we come across an interesting topic of coding guidelines while designing automation test scripts. The scope of this article will not be limited to QTP but to an overall extent of using VB Scripting for automation projects. Introduction Now…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now