Stuart1044
Stuart1044

Reputation: 444

C# Telephone Number Receiver

I am trying to build a simply app that returns the number calling via a modem, however I only seem to be getting the first line of the data received from the modem.

When I run HyperTerminal and pass through the AT#CID=1 command, ring the number, I get a full output of :

OK

DATE=0314

TIME=1111

NMBR=4936

NAME=Stuart E

RING

In my app i only seem to receive the first section containing the "OK" part. Any help on what i am doing wrong or am missing?

Code:

 public partial class Form1 : Form
 {
    public SerialPort port = new SerialPort("COM3", 115200,Parity.None,8,StopBits.One);
    public String sReadData = "";
    public String sNumberRead = "";
    public String sData = "AT#CID=1";

    public Form1()
    {
        InitializeComponent();
    }

    private void btnRun_Click(object sender, EventArgs e)
    {
        SetModem();

        ReadModem();

        MessageBox.Show(sReadData);
    }

 public void SetModem()
    {

        if (port.IsOpen == false)
        {
            port.Open();
        }

        port.WriteLine(sData + System.Environment.NewLine);
        port.BaudRate = iBaudRate;
        port.DtrEnable = true;
        port.RtsEnable = true;

    }

    public string ReadModem()
    {

        try
        {
            sReadData = port.ReadExisting().ToString();

            return (sReadData);
        }
        catch (Exception ex)
        {
            String errorMessage;
            errorMessage = "Error in Reading: ";
            errorMessage = String.Concat(errorMessage, ex.Message);
            errorMessage = String.Concat(errorMessage, " Line: ");
            errorMessage = String.Concat(errorMessage, ex.Source);

            MessageBox.Show(errorMessage, "Error");
            return "";
        }
    }

    private void btnExit_Click(object sender, EventArgs e)
    {
        port.Close();
        Close();
    }
}
}

Upvotes: 1

Views: 1706

Answers (2)

Marshal
Marshal

Reputation: 6651

You are just reading the Modem once after setting it. You need to subscribe the DataReceivedEvent on serialPort to continuously get data from the port.

public void SetModem()
    {

        if (port.IsOpen == false)
        {
            port.Open();
        }

        port.WriteLine(sData + System.Environment.NewLine);
        port.BaudRate = iBaudRate;
        port.DtrEnable = true;
        port.RtsEnable = true;

        port.DataReceived += port_DataReceived;

    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
            //For e.g. display your incoming data in RichTextBox
            richTextBox1.Text += this.serialPort1.ReadLine();           

           //OR
           ReadModem();
    }

Upvotes: 1

ellak
ellak

Reputation: 2561

In ReadModem() try to use port.ReadLine() in a loop instead and loop until you get a line saying RING (if that is the final line you are expecting).

Upvotes: 1

Related Questions