Wrox Programmer Forums

Need to download code?

View our list of code downloads.

Register | FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read
Visual Studio 2005 For discussing Visual Studio 2005. Please post code questions about a specific language (C#, VB, ASP.NET, etc) in the correct language forum instead.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the Visual Studio 2005 section of the Wrox Programmer to Programmer discussions. This is a community of tens of thousands of software programmers and website developers including Wrox book authors and readers. As a guest, you can read any forum posting. By joining today you can post your own programming questions, respond to other developersí questions, and eliminate the ads that are displayed to guests. Registration is fast, simple and absolutely free .
DRM-free e-books 300x50
Reply
 
Thread Tools Display Modes
  #1 (permalink)  
Old November 15th, 2006, 10:38 PM
Authorized User
 
Join Date: Oct 2006
Location: , , Singapore.
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to poja
Default modem

i have to create a programming on SMS application on Visual Studio.NET can anyone please tell me the coding to initialize the modem and to receive SMS :(

Reply With Quote
  #2 (permalink)  
Old November 15th, 2006, 10:45 PM
Friend of Wrox
Points: 2,376, Level: 20
Points: 2,376, Level: 20 Points: 2,376, Level: 20 Points: 2,376, Level: 20
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: , , Australia.
Posts: 596
Thanks: 1
Thanked 3 Times in 3 Posts
Default

Hi poja,

Its you lucky day, I dont have time to explain how to do it, so here is the code.

Code may vary depending on GSM modem module.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Diagnostics;

namespace SmsManager
{
    class PortUtilities
    {
        public delegate void OnMessageLog(object sender, PortUtilitiesEventArgs e);
        public static event OnMessageLog OnMessageLogged;      

        /// <summary>
        /// Opens the supplied port number is the port is not already open
        /// </summary>
        /// <param name="portName">The Name of the port, "COM?"</param>
        /// <param name="pinNumber">The Pin Number for the GSM Modem SIM Card</param>
        /// <returns>Opened Serial Port Object</returns>
        public static SerialPort OpenPort(string portName, string pinNumber)
        {
            SerialPort serialPort = new SerialPort(portName, 9600, Parity.None, 8, StopBits.One);
            try
            {
                serialPort.Handshake = Handshake.RequestToSend;
                serialPort.ReadTimeout = 5000;
                if (!serialPort.IsOpen) { serialPort.Open(); }
                SendATCommand(serialPort);
                SendCPINCommand(serialPort, pinNumber);
                SendCMGFCommand(serialPort);
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
            }
            return serialPort;
        }
        /// <summary>
        /// Opens the supplied port number is the port is not already open
        /// </summary>
        /// <param name="portName">The Name of the port, "COM?"</param>
        /// <param name="pinNumber">The Pin Number for the GSM Modem SIM Card</param>
        /// <param name="handshake">Handshake setting</param>
        /// <param name="baudRate">BaudRate</param>
        /// <param name="parity">Parity</param>
        /// <param name="dataBits">DataBits</param>
        /// <param name="stopBits">StopBits</param>
        /// <returns></returns>
        public static SerialPort OpenPort(string portName, string pinNumber,Handshake handshake, int baudRate,Parity parity,int dataBits,StopBits stopBits)
        {
            SerialPort serialPort = new SerialPort(portName, baudRate, parity, dataBits, stopBits);
            try
            {
                serialPort.Handshake = handshake;
                serialPort.ReadTimeout = 5000;
                if (!serialPort.IsOpen) { serialPort.Open(); }
                SendATCommand(serialPort);
                SendCPINCommand(serialPort, pinNumber);
                SendCMGFCommand(serialPort);
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
            }
            return serialPort;
        }
        /// <summary>
        /// Send the messge to the supplied mobile number via the supplied serialport
        /// </summary>
        /// <param name="serialPort">Port to use to send message</param>
        /// <param name="mobileNumber">The GSM Modem Phone Number for send the message to,</param>
        /// <param name="message">The message to be sent</param>
        /// <returns>True if successful</returns>
        public static bool SendMSG(SerialPort serialPort, string mobileNumber, string message)
        {
            LogMessage(message, EventLogEntryType.Error);
            if (!SendCMGSCommand(serialPort, mobileNumber)) { return false; }
            if (!SendMessage(serialPort, message)) { return false; }
            if (!sendCTRLZ(serialPort)) { return false; }
            return true;
        }
        /// <summary>
        /// Sends an AT Command to the supplied port
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <returns>True if successful</returns>
        private static bool SendATCommand(SerialPort serialPort)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("AT" + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("AT Command timed out without receiving 'OK'.");
                    }
                }
                while (!buffer.Contains("OK"));
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Sets the Pin for the device is it is not already set.
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <param name="pinNumber">The Pin Number for the GSM Modem SIM Card</param>
        /// <returns>True if successful</returns>
        private static bool SendCPINCommand(SerialPort serialPort, string pinNumber)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            //Check if need to enter PIN
            try
            {
                serialPort.Write("AT+CPIN?" + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("AT+CPIN? Command timed out without receiving 'READY' or 'SIM PIN'.");
                    }
                }
                while ((!buffer.Contains("READY")) && (!buffer.Contains("SIM PIN")));
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
                return false;
            }
            if (buffer.Contains("SIM PIN"))
            { 
                try
                {
                    serialPort.Write("AT+CPIN=\"" + pinNumber + "\"" + (char)13);
                    buffer = "";
                    do
                    {
                        buffer += serialPort.ReadExisting();
                        if (DateTime.Now > timeout)
                        {
                            throw new Exception("AT+CPIN Command timed out without receiving 'OK'.");
                        }
                    }
                    while (!buffer.Contains("OK"));
                }
                catch (Exception ex)
                {
                    LogMessage(ex.Message, EventLogEntryType.Error);
                    return false;
                }
            }
            return true;
        }
        /// <summary>
        /// Sends the CMGFCommand to set the input type
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <returns>True if successful</returns>
        private static bool SendCMGFCommand(SerialPort serialPort)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("AT+CMGF=1" + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("AT+CMGF=1 Command timed out without receiving 'OK'.");
                    }
                }
                while (!buffer.Contains("OK"));
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Initiates the GSM Modem to send a message to the supplied mobile number
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <param name="mobileNumber">The mobile number to send the message to</param>
        /// <returns>True if successful</returns>
        private static bool SendCMGSCommand(SerialPort serialPort, string mobileNumber)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("AT+CMGS=\"" + mobileNumber + "\"" + (char)13);
                buffer = "";

                do                
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("CMGS Command timed out without receiving '>'.");
                    }
                }
                while (!buffer.Contains("\r\n>"));
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Sends the message to the waiting cursor
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <param name="message">The message to be sent</param>
        /// <returns>True if successful</returns>
        private static bool SendMessage(SerialPort serialPort, string message)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write(message + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("Message timed out without receiving '>'.");
                    }
                }
                while (!buffer.Contains(">"));
            }
            catch (Exception ex)
            {
                LogMessage(ex.Message, EventLogEntryType.Error);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Finalises message send routing by sending the messge to the mobile number
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <returns>True if successful</returns>
        private static bool sendCTRLZ(SerialPort serialPort)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("" + (char)26);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("Message timed out without receiving '+CMGS:'.");
                    }
                }
                while (!buffer.Contains("+CMGS:"));
            }
            catch (Exception ex)
            {
                LogMessage("Failed to Send CTRL+Z Command: " + ex.Message, EventLogEntryType.Error);
                return false;
            }
            return true;
        }
        /// <summary>
        /// Sends CGML command to list messages on the GSM Modem
        /// </summary>
        /// <param name="serialPort">Port to use to send command</param>
        /// <param name="messageType">The messges to be read as a string, eg. "ALL", "REC UNREAD"</param>
        /// <returns>The response form the GSM Modem</returns>
        public static string sendCMGL(SerialPort serialPort, string messageType)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("AT+CMGL=\"" + messageType + "\"" + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("CMGL timed out without receiving 'OK'.");
                    }
                }                
                while (!buffer.Contains("\r\nOK\r\n"));
            }
            catch (Exception ex)
            {
                SendATCommand(serialPort);
                LogMessage("Failed to retrieve message from modem: " + ex.Message, EventLogEntryType.Error);
                return string.Empty;
            }
            return buffer;
        }
        public static string sendCMGD_DeleteMessage(SerialPort serialPort, string messageID)
        {
            DateTime timeout = DateTime.Now.AddMinutes(1);
            string buffer = "";
            try
            {
                serialPort.Write("AT+CMGD=" + messageID + (char)13);
                buffer = "";
                do
                {
                    buffer += serialPort.ReadExisting();
                    if (DateTime.Now > timeout)
                    {
                        throw new Exception("CMGD timed out without receiving 'OK'.");
                    }
                }
                while (!buffer.Contains("\r\nOK\r\n"));
            }
            catch (Exception ex)
            {
                SendATCommand(serialPort);
                LogMessage("Failed to retrieve message from modem: " + ex.Message, EventLogEntryType.Error);
                return string.Empty;
            }
            return buffer;
        }
        private static void LogMessage(string message, EventLogEntryType eventLogEntryType)
        {
            PortUtilitiesEventArgs e = new PortUtilitiesEventArgs();
            e.Message = message;
            e.EventLogEntryType = eventLogEntryType;
            if (OnMessageLogged != null)
            {
                OnMessageLogged(new object(), e);
            }        
        }
    }
    public class PortUtilitiesEventArgs : EventArgs
    {
        public string Message;
        public EventLogEntryType EventLogEntryType;
    }
}
======================================
They say, best men are molded out of faults,
And, for the most, become much more the better
For being a little bad.
======================================
Reply With Quote
The Following User Says Thank You to rodmcleay For This Useful Post:
  #3 (permalink)  
Old November 20th, 2006, 04:12 AM
Authorized User
 
Join Date: Oct 2006
Location: , , Singapore.
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to poja
Default

thank a lot but i would like to know wheather it is java or c#

Reply With Quote
  #4 (permalink)  
Old November 20th, 2006, 04:16 AM
Friend of Wrox
Points: 2,376, Level: 20
Points: 2,376, Level: 20 Points: 2,376, Level: 20 Points: 2,376, Level: 20
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: , , Australia.
Posts: 596
Thanks: 1
Thanked 3 Times in 3 Posts
Default

this is c#

======================================
They say, best men are molded out of faults,
And, for the most, become much more the better
For being a little bad.
======================================
Reply With Quote
  #5 (permalink)  
Old November 20th, 2006, 04:49 AM
Authorized User
 
Join Date: Oct 2006
Location: , , Singapore.
Posts: 12
Thanks: 0
Thanked 0 Times in 0 Posts
Send a message via MSN to poja
Default

thank you

Reply With Quote
  #6 (permalink)  
Old January 27th, 2007, 08:04 PM
Registered User
 
Join Date: Jan 2007
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi all,

I have a question. I am connection to GSM modem from my program and I sent AT command before anyother command to test whether it is really a modem at the end. The problem I am facing was when I send after opening succeful serial port < non modem > the program will hang at that line.
>>serialPort.Write("AT" + (char)13);
If the modem really exited at the port that I open the program will go smoothly and will get reply OK from modem.
How do I overcome this problem?
The user might select any port.
We need to detect whether the port is for GSM modem or not.
The user select non modem port, program crash.

Please help.

>>C# init data<<

SerialPort serialPort = new SerialPort("COM7", 115200, Parity.None, 8, StopBits.One);
           serialPort.Handshake = Handshake.RequestToSend;
           serialPort.ReadTimeout = 5000;







Reply With Quote
  #7 (permalink)  
Old January 27th, 2007, 10:27 PM
Friend of Wrox
Points: 2,376, Level: 20
Points: 2,376, Level: 20 Points: 2,376, Level: 20 Points: 2,376, Level: 20
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: , , Australia.
Posts: 596
Thanks: 1
Thanked 3 Times in 3 Posts
Default

Im not sure if you can expect a response from all devices when you send AT command.
As you cant be sure you should allow the response to time out and then manage that from there.
The function in the code listing above called "SendATCommand" does just that.
It sends AT command and waits for the OK, if the ok is not received in 1 minute it throws an exception which can be handled.
In the code above i was logging the exception, but you might provide a message saying that you cannot connect to a modem on that port.

======================================
They say, best men are molded out of faults,
And, for the most, become much more the better
For being a little bad.
======================================
Reply With Quote
  #8 (permalink)  
Old March 14th, 2007, 05:17 AM
Registered User
 
Join Date: Mar 2007
Location: , , India.
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Default

"DateTime timeout = DateTime.Now.AddMinutes(5);"

Please correct me if I'm wrong, but I think the code sample that u posted, to initialize a modem and receive SMS, assumes a random time as the time needed to generate all the responses for that particular AT command. Is there any way to wait till all the responses for a command are received, without using a random response time?

:)
Reply With Quote
  #9 (permalink)  
Old March 14th, 2007, 10:06 AM
Friend of Wrox
Points: 2,376, Level: 20
Points: 2,376, Level: 20 Points: 2,376, Level: 20 Points: 2,376, Level: 20
Activity: 0%
Activity: 0% Activity: 0% Activity: 0%
 
Join Date: Jun 2003
Location: , , Australia.
Posts: 596
Thanks: 1
Thanked 3 Times in 3 Posts
Default

Hi,
There is no need to know when the response will end as the loop will stop automatically when all the response is received. ie The 'OK' is received.

I put the timeout in just as a backstop incase there is something wrong, a way out for the loop.
In reality the response time is more immediate on the modems I am using.

I think my final code had this at one minute, 10 seconds might be plenty.

Also, it would be an advantage to put a few second thread sleep in between loops as this code puts the CPU in a bit of a spin if there is a problem and you have to wait for the timeout.

The five/one minute fallback should never be reached if all is going well, and the loop/process will stop as soon as the OK is received.

I am not aware of a definative way to tell in advance what response time the modem will give, and I would imagine that it will vary form modem to modem and depending on how many messages there are.
I suggest logging the datetime when you send the command and again when you receive the OK a few times to work out the most appropriate time for you.

Also, my final code had the timeout value set from the config file so it can be improved if needed.

If you improve on this code please post it here.

Hope this helps
Rod


======================================
"They say, best men are molded out of faults,
And, for the most, become much more the better
For being a little bad."
--Shakespeare
======================================
Reply With Quote
  #10 (permalink)  
Old January 4th, 2008, 07:56 AM
Registered User
 
Join Date: Jan 2008
Location: , , .
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Will This Work For The USB PORT ALSO

Reply With Quote
Reply


Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off
Trackbacks are Off
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
modem driver angelboy Linux 1 October 5th, 2007 03:27 PM
Modem poja Pro Visual Basic 2005 0 November 15th, 2006 10:34 PM
Voting system for gsm modem sime_tyres VB How-To 0 August 8th, 2006 10:50 AM
Phone and Modem options abelmirma Access VBA 0 March 3rd, 2005 11:29 AM
Unable to detect internal modem management_guru Linux 4 March 27th, 2004 11:49 AM



All times are GMT -4. The time now is 11:43 PM.


Powered by vBulletin® Version 3.7.0
Copyright ©2000 - 2014, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.