C#代码使用AT命令使手机通过Visual Studio连接



这是与GSM 900调制解调器建立连接的代码...,代码可完美。但是,当我尝试使我的手机(Micromax Doodle A111-works完美地适合所有命令中的命令)代替GSM 900调制解调器。.它说没有电话连接。为了连接手机,我必须做什么变化。

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);

    }
}

和该代码必须在连接后接收MSG并在屏幕上显示并在TEH消息中访问内容。

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("rn");
                    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("rn");
                   // 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();
        }
    }

    // 

我认为您应该先添加ComboBox,并使用此代码自动检查所有可用端口:

    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);
        }
    }

,您会看到问题所在。谢谢。

相关内容

  • 没有找到相关文章

最新更新