Question

This the code for making connection with the GSM 900 modem... and the code works perfectly.. but when i try to make my mobile(micromax doodle a111-works perfectly for all AT COMMANDS in HYPERTERMINAL) to act instead of GSM 900 modem.. its says NO PHONE CONNECTED.. What changes i have to make in order to connect my mobile..pls help me soon.. thanx in advance...

public partial class frmConnection : Form
{
    public frmConnection()
    {
        InitializeComponent();
    }
 //   private System.ComponentModel.Container components = null;

    private int port;
    private int baudRate;
    private int timeout;

    private void frmConnection_Load(object sender, EventArgs e)
    {
        cboPort.Items.Add("1");
        cboPort.Items.Add("2");
        cboPort.Items.Add("3");
        cboPort.Items.Add("4");
        cboPort.Text = port.ToString();

        cboBaudRate.Items.Add("9600");
        cboBaudRate.Items.Add("19200");
        cboBaudRate.Items.Add("38400");
        cboBaudRate.Items.Add("57600");
        cboBaudRate.Items.Add("115200");
        cboBaudRate.Text = baudRate.ToString();

        cboTimeout.Items.Add("150");
        cboTimeout.Items.Add("300");
        cboTimeout.Items.Add("600");
        cboTimeout.Items.Add("900");
        cboTimeout.Items.Add("1200");
        cboTimeout.Items.Add("1500");
        cboTimeout.Items.Add("1800");
        cboTimeout.Items.Add("2000");
        cboTimeout.Text = timeout.ToString();
    }
    public void SetData(int port, int baudRate, int timeout)
    {
        this.port = port;
        this.baudRate = baudRate;
        this.timeout = timeout;
    }

    public void GetData(out int port, out int baudRate, out int timeout)
    {
        port = this.port;
        baudRate = this.baudRate;
        timeout = this.timeout;
    }

    private bool EnterNewSettings()
    {
        int newPort;
        int newBaudRate;
        int newTimeout;

        try
        {
            newPort = int.Parse(cboPort.Text);
        }
        catch (Exception)
        {
            MessageBox.Show(this, "Invalid port number.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            cboPort.Focus();
            return false;
        }

        try
        {
            newBaudRate = int.Parse(cboBaudRate.Text);
        }
        catch (Exception)
        {
            MessageBox.Show(this, "Invalid baud rate.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            cboBaudRate.Focus();
            return false;
        }

        try
        {
            newTimeout = int.Parse(cboTimeout.Text);
        }
        catch (Exception)
        {
            MessageBox.Show(this, "Invalid timeout value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            cboTimeout.Focus();
            return false;
        }

        SetData(newPort, newBaudRate, newTimeout);

        return true;
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        if (!EnterNewSettings())
            DialogResult = DialogResult.None;


    }

    private void btnTest_Click(object sender, EventArgs e)
    {
        if (!EnterNewSettings())
            return;

        Cursor.Current = Cursors.WaitCursor;
        GsmCommMain comm = new GsmCommMain(port, baudRate, timeout);
        try
        {
            comm.Open();
            while (!comm.IsConnected())
            {
                Cursor.Current = Cursors.Default;
                if (MessageBox.Show(this, "No phone connected.", "Connection setup",
                    MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
                {
                    comm.Close();
                    return;
                }
                Cursor.Current = Cursors.WaitCursor;
            }

            comm.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(this, "Connection error: " + ex.Message, "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            return;
        }
        MessageBox.Show(this, "Successfully connected to the phone.", "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);


    }

}

and this the code that have to receive the msg after the connection and display it on the screen and to access the content in teh message..

public partial class Mainform : Form
{
    SmsSubmitPdu pdu;
    private delegate void SetTextCallback(string text);
    private CommSetting comm_settings = new CommSetting();



    SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=localtrain;Integrated Security=True");
    string mess="";
    private void Mainform_Load(object sender, EventArgs e)
    {
        Control.CheckForIllegalCrossThreadCalls = false;
        // Prompt user for connection settings
        int port = GsmCommMain.DefaultPortNumber;
        int baudRate = 9600; // We Set 9600 as our Default Baud Rate
        int timeout = GsmCommMain.DefaultTimeout;
        timer1.Start();
        timer1.Interval = 10000;
        frmConnection dlg = new frmConnection();
        dlg.StartPosition = FormStartPosition.CenterScreen;
        dlg.SetData(port, baudRate, timeout);


        if (dlg.ShowDialog(this) == DialogResult.OK)
        {
            dlg.GetData(out port, out baudRate, out timeout);
            CommSetting.Comm_Port = port;
            CommSetting.Comm_BaudRate = baudRate;
            CommSetting.Comm_TimeOut = timeout;



        }
        else
        {
            Close();
            return;
        }

        Cursor.Current = Cursors.WaitCursor;
        CommSetting.comm = new GsmCommMain(port, baudRate, timeout);
        Cursor.Current = Cursors.Default;
        CommSetting.comm.PhoneConnected += new EventHandler(comm_PhoneConnected);
        CommSetting.comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);

        bool retry;
        do
        {
            retry = false;
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                CommSetting.comm.Open();
                Cursor.Current = Cursors.Default;
            }
            catch (Exception)
            {
                Cursor.Current = Cursors.Default;
                if (MessageBox.Show(this, "Unable to open the port.", "Error",
                    MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
                    retry = true;
                else
                {
                    Close();
                    return;
                }
            }
        }
        while (retry);
    }


    private delegate void ConnectedHandler(bool connected);

    private void OnPhoneConnectionChange(bool connected)
    {
        lbl_phone_status.Text = "CONNECTED";
    }


    private void comm_MessageReceived(object sender, GsmComm.GsmCommunication.MessageReceivedEventArgs e)
    {
        MessageReceived();
    }

    private void comm_PhoneConnected(object sender, EventArgs e)
    {
        this.Invoke(new ConnectedHandler(OnPhoneConnectionChange), new object[] { true });
    }


    private string GetMessageStorage()
    {
        string storage = string.Empty;
        storage = PhoneStorageType.Sim;

        if (storage.Length == 0)
            throw new ApplicationException("Unknown message storage.");
        else
            return storage;
    }


    private void MessageReceived()
    {
        Cursor.Current = Cursors.WaitCursor;
        string storage = GetMessageStorage();

        DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
        foreach (DecodedShortMessage message in messages)
        {
            Output(string.Format("Message status = {0}, Location = {1}/{2}",
                StatusToString(message.Status), message.Storage, message.Index));
            ShowMessage(message.Data);
            Output("");
        }

        Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
        Output("");
    }


    private string StatusToString(PhoneMessageStatus status)
    {
        // Map a message status to a string
        string ret;
        switch (status)
        {
            case PhoneMessageStatus.All:
                ret = "All";
                break;
            case PhoneMessageStatus.ReceivedRead:
                ret = "Read";
                break;
            case PhoneMessageStatus.ReceivedUnread:
                ret = "Unread";
                break;
            case PhoneMessageStatus.StoredSent:
                ret = "Sent";
                break;
            case PhoneMessageStatus.StoredUnsent:
                ret = "Unsent";
                break;
            default:
                ret = "Unknown (" + status.ToString() + ")";
                break;
        }
        return ret;
    }

    int kl = 0;
    long mobilenumber;
    string message;


    private void Output(string text)
    {
        label1.Text = "Processing....";
        try
        {
            kl = kl + 1;
            if (text != "RECEIVED MESSAGE")
            {
                if (this.txtOutput.InvokeRequired)
                {
                    SetTextCallback stc = new SetTextCallback(Output);
                    this.Invoke(stc, new object[] { text });

                }
                else
                {
                    txtOutput.AppendText(text);
                    txtOutput.AppendText("\r\n");
                    label2.Text = (Convert.ToInt32(label2.Text) + 1).ToString();
                    comboBox1.Items.Add(text);


                    if (label2.Text == "6")
                    {
                        string temps = "ms*tbm*2*";
                        int count;
                        string mob;
                        DateTime dt = new DateTime();
                        string source, dest, temp, tempdate;
                        string source1, dest1, temp1, tempdate1;
                        int tic;
                        mob = comboBox1.Items[1].ToString();
                        mob = mob.Substring(mob.LastIndexOf('+') + 3);
                        mobilenumber = Convert.ToInt64(mob);
                        tempdate = comboBox1.Items[2].ToString();

                        temp = comboBox1.Items[3].ToString();
                        string[] mess1 = temp.Split('*');
                        source1 = mess1[0].ToString();
                        source1 = source1.Substring(source1.IndexOf('$') + 1);
                        dest1 = mess1[1].ToString();
                        tic =Convert.ToInt32(mess1[2].ToString());
                        temp = temp.Substring(temp.LastIndexOf('$')+1);
                        // 
                        //source = temp.Substring(0, temp.IndexOf('*'));
                        //temp = temp.Substring(temp.IndexOf('*') + 1);
                        //dest = temp.Substring(0, temp.IndexOf('*') - 1);
                        //temp = temp.Substring(temp.IndexOf('*') + 1);
                        //count = Convert.ToInt32(temp);

                        ticketing(mobilenumber, source1, dest1, tic);
                    }
                }

            }
            else
            {
                comboBox1.Items.Clear();
                txtOutput.Text = "";
              //  label2.Text = "";
                comboBox1.Items.Add(text);
                if (this.txtOutput.InvokeRequired)
                {
                    SetTextCallback stc = new SetTextCallback(Output);
                    this.Invoke(stc, new object[] { text });
                }
                else
                {
                    txtOutput.AppendText(text);
                    txtOutput.AppendText("\r\n");
                   // label2.Text += "*" + text;
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    private void ShowMessage(SmsPdu pdu)
    {

        if (pdu is SmsSubmitPdu)
        {
            // Stored (sent/unsent) message
            SmsSubmitPdu data = (SmsSubmitPdu)pdu;
            Output("SENT/UNSENT MESSAGE");
            Output("Recipient: " + data.DestinationAddress);
            Output("Message text: " + data.UserDataText);
            Output("-------------------------------------------------------------------");
            return;
        }
        if (pdu is SmsDeliverPdu)
        {
            // Received message
            SmsDeliverPdu data = (SmsDeliverPdu)pdu;
            Output("RECEIVED MESSAGE");
            Output("Sender: -" + data.OriginatingAddress);
            Output("Sent: " + data.SCTimestamp.ToString());
            Output("Message text: $" + data.UserDataText);
            Output("-------------------------------------------------------------------");
           // label2.Text = data.UserDataText;
            return;
        }
        if (pdu is SmsStatusReportPdu)
        {
            // Status report
            SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
            Output("STATUS REPORT");
            Output("Recipient: " + data.RecipientAddress);
            Output("Status: " + data.Status.ToString());
            Output("Timestamp: " + data.DischargeTime.ToString());
            Output("Message ref: " + data.MessageReference.ToString());
            Output("-------------------------------------------------------------------");
            return;
        }
        Output("Unknown message type: " + pdu.GetType().ToString());
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        // Clean up comm object
        if (CommSetting.comm != null)
        {
            // Unregister events
            CommSetting.comm.PhoneConnected -= new EventHandler(comm_PhoneConnected);
            CommSetting.comm.MessageReceived -= new MessageReceivedEventHandler(comm_MessageReceived);

            // Close connection to phone
            if (CommSetting.comm != null && CommSetting.comm.IsOpen())
                CommSetting.comm.Close();

            CommSetting.comm = null;
            this.Close();
        }
    }



    // 
Was it helpful?

Solution

I think you should add combobox first and check all available ports automatically using this code :

    private void comboBox1_DropDown(object sender, EventArgs e)
    {
        comboBox1.Items.Clear();
        try
        {
            #region Display all available COM Ports
            string[] ports = SerialPort.GetPortNames();

            // Add all port names to the combo box:
            foreach (string port in ports)
            {
                this.comboBox1.Items.Add(port);
            }
            #endregion


        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

And you'll see where the problem is . Thank you .

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top