我对 C# 编程有点陌生,但不知何故,我设法找到了一个需要使用 serialPort 进行 GSM (SMS) 通信的高超技能和知识的项目。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace SMSget
{
public partial class SMSLogPanel : UserControl
{
#region default constructor
public SMSLogPanel()
{
InitializeComponent();
serialPort1 = new SerialPort();
serialPort1.DataBits = 8;
serialPort1.DtrEnable = true;
serialPort1.Encoding.Equals("iso-8859-1");
serialPort1.Handshake = Handshake.RequestToSend;
serialPort1.Parity = Parity.None;
serialPort1.WriteTimeout = 300;
serialPort1.StopBits = StopBits.One;
checkLink();
}
#endregion
#region checking communication and setting user controls...
private void checkLink()
{
GetValues value = new GetValues();
string com = value.getPort();
int baud = value.getBaud();
int timeot = value.getTimeout();
serialPort1.PortName = com;
serialPort1.BaudRate = baud;
serialPort1.ReadTimeout = timeot;
serialPort1.Open();
if (serialPort1.IsOpen)
{
label1.Visible = true;
}
else
{
MessageBox.Show("Komunikacija sa modemom se ne može uspostaviti, molimo postavite novu konfiguraciju...!");
this.Controls.Clear();
SMSConfigPanel cfg = new SMSConfigPanel();
cfg.Show();
this.Controls.Add(cfg);
}
serialPort1.Close();
}
#endregion
#region setiranje timer-a...
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Stop();
execCommand();
timer1.Start();
}
#endregion
#region seting handler and executing AT commands
public void execCommand()
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(getResponse);
serialPort1.Open();
//prazni se buffer da se ne pokupe neke vrijednosti koje ne trebaju...
serialPort1.DiscardInBuffer();
if (!serialPort1.IsOpen)
{
MessageBox.Show("Modem nije spojen, molimo provjerite konfiguraciju...!");
timer1.Stop();
}
serialPort1.Write("AT+CMGF=1" + (char)(13));
serialPort1.Write("AT+CMGL=\"ALL\"" + (char)(13));
}
public void getResponse(object sender, SerialDataReceivedEventArgs e)
{
SerialPort serPort = (SerialPort)sender;
string input = serPort.ReadExisting();
if (input.Contains("ERROR"))
{
//textBox2.Text = "";
}
else if (input.Contains("+CMTI:"))
{
serialPort1.Write("AT+CMGF=1" + (char)(13));
serialPort1.Write("AT+CMGL=\"ALL\"" + (char)(13));
}
else if (input.Contains("+CMGL:"))
{
textBox1.Text = input;
}
else
{
return;
}
serialPort1.Close();
}
#endregion
}
}
我认为不知何故我设法在这些区域中创建错误(不打开/关闭serialPort1端口,getResponse(object sender,SerialDataReceivedEventArgs e)中的输入数据,由于跨线程问题,无法将使用单独线程的输入数据传递到textBox1......,以及读取已收到的未读消息的 AT 命令可能是错误的......)
如果有人可以帮助我解决这个问题,我将不胜感激......
感谢你并致以真诚的问候。