p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Visual Studio 2005 (http://p2p.wrox.com/forumdisplay.php?f=140)
-   -   modem (http://p2p.wrox.com/showthread.php?t=50343)

poja November 15th, 2006 11:38 PM

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 :([?]


rodmcleay November 15th, 2006 11:45 PM

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.
======================================

poja November 20th, 2006 05:12 AM

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


rodmcleay November 20th, 2006 05:16 AM

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.
======================================

poja November 20th, 2006 05:49 AM

thank you


nlksg January 27th, 2007 09:04 PM

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;








rodmcleay January 27th, 2007 11:27 PM

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.
======================================

amey.agnihotri March 14th, 2007 05:17 AM

"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?

:)[?]

rodmcleay March 14th, 2007 10:06 AM

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
======================================

subash111a January 4th, 2008 08:56 AM

Will This Work For The USB PORT ALSO



All times are GMT -4. The time now is 05:44 AM.

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