在C#中通过串口发送短信,但得到垃圾

时间:2015-02-16 10:56:33

标签: c# serial-port sms at-command

我通过串口发送短信但接收????。请帮我正确地批量接收短信。以下是我的代码:

  
    
      

SmsHandler.SendSMS(“hello world”,phonenumber,“USB Modem”);

    
  
   public static void SendSMS(String smstxt, String PhoneNumber, String DeviceName)
    {
       _serialPort = new SerialPort(Port.getPort(DeviceName), 19200, Parity.None, 8, StopBits.One);
        _serialPort.Handshake = Handshake.None;
        _serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
        _serialPort.ReadTimeout = 2000;
        _serialPort.WriteTimeout = 2000;
        _serialPort.Open();
        try
        {
            if (!_serialPort.IsOpen)
                _serialPort.Open();
            _serialPort.Write("AT+CMGF=1\r\n");
            Thread.Sleep(1000);
            _serialPort.Write("AT+CSCA=SERVICE\r\n");// Service Center  
            Thread.Sleep(1000);
            _serialPort.Write("AT+CMGS=\"" + PhoneNumber + "\"" + Environment.NewLine);
            _serialPort.Write(smstxt + char.ConvertFromUtf32(26) + Environment.NewLine);


            MessageBox.Show("Message Sent");

        }
        catch (Exception ex)
        {
            MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
        }
    }
    static void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        Thread.Sleep(500);
        string data = _serialPort.ReadLine();
        Console.Write(data);
    }

我在接收机手机上收到垃圾。请帮忙解决问题。 Thankx

3 个答案:

答案 0 :(得分:2)

这已经晚了三个月,但它可能会帮助将来读这篇文章。

要通过串口发送短信,您需要将文本转换为信息的十六进制表示,然后发送结果。 例如:

        public partial class Service1 : ServiceBase
        {
            Timer timer1 = new Timer();
            SqlConnection objSqlCon = new  SqlConnection(ConfigurationManager.AppSettings["SqlConnection"].ToString());
            string objRetval = string.Empty;
            public Service1()
            {
                InitializeComponent();
            }
        protected override void OnStart(string[] args)
        {

            timer1.Interval = 600000; //10 mts
            timer1.Enabled = true;
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
            timer1.Enabled = true;
            WriteLog("Test Windows Service");
        }
        private void timer1_Tick(object sender,ElapsedEventArgs e)
        {
            WriteLog("Test Job Done Sucessfully");
            // If Time greater than 11 and if record doesnt exists
            objRetval = RetrieveData(ReportType.Daily.ToString());
            if (objRetval == "1")
            {
                InsertData();
            }
            //OnStop();
        }
        protected override void OnStop()
        {
            timer1.Enabled = false;
            WriteLog("Test Job Stopped Sucessfully");
        }

        public string RetrieveData(string strRptType)
        {
            string strRetVal = string.Empty;
            try
            {
                SqlCommand cmd = new SqlCommand("sp_get_EmailNotificationSentLogExists", objSqlCon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RptType", strRptType);
                if (objSqlCon.State != ConnectionState.Open)
                {
                    objSqlCon.Open();
                }
                strRetVal = Convert.ToString(cmd.ExecuteScalar());
                //l1.WriteLog("Data Inserted Successfully");
            }
            catch (Exception ex)
            {
                //l1.WriteLog(ex.Message.ToString());
                throw ex;
            }
            finally
            {
                objSqlCon.Close();
            }
            return strRetVal;
        }

        void InsertData()
        {
            try
            {
                SqlCommand cmd = new SqlCommand("sp_Insert_EmailNotificationSentLog", objSqlCon);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@RptType", ReportType.Daily.ToString());
                if (objSqlCon.State != ConnectionState.Open)
                {
                    objSqlCon.Open();
                }
                cmd.ExecuteNonQuery();
                WriteLog("Data Inserted Successfully");
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message.ToString());
                throw ex;
            }
            finally
            {
                objSqlCon.Close();
            }
        }

        public void WriteLog(string strMessage)
        {
            string strLogDir = string.Empty, strLogFileName = string.Empty, SstrFilePath = string.Empty;
            strLogDir = ConfigurationManager.AppSettings["LogDirectory"].ToString();
            strLogFileName = ConfigurationManager.AppSettings["Logname"].ToString();
            if (!Directory.Exists(strLogDir))
            {
                Directory.CreateDirectory(strLogDir);
            }
            SstrFilePath = strLogDir + "\\" + strLogFileName;
            if (!File.Exists(SstrFilePath))
            {
                using (StreamWriter sw = File.CreateText(SstrFilePath))
                {
                    sw.WriteLine("================================================================================");
                    sw.WriteLine(" // " + DateTime.Now.ToString());
                    sw.WriteLine("Message \t\t\t: " + strMessage);
                    sw.Close();
                }
            }
            else
            {
                StreamReader sReder = new StreamReader(SstrFilePath);
                string oldText = sReder.ReadToEnd();
                sReder.Close();
                StreamWriter sWriter = new StreamWriter(SstrFilePath);
                sWriter.WriteLine(oldText);
                sWriter.WriteLine("================================================================================");
                sWriter.WriteLine(" // " + DateTime.Now.ToString());
                sWriter.WriteLine("File Name \t\t\t: " + strMessage);
                sWriter.Close();
            }
        }

        enum ReportType {Daily,Monthly,Yearly}

    }

StrToHex方法可以是:

_serialPort.Write(StrToHex(smstxt) + char.ConvertFromUtf32(26) + Environment.NewLine);

答案 1 :(得分:0)

也许这与串口编码有关?

也许尝试不同的编码:

 _serialPort.Encoding = Encoding.GetEncoding("iso-8859-1");

我还建议你研究一下:http://www.scampers.org/steve/sms/libraries.htm - 它具有用于执行AT命令的简单API。

答案 2 :(得分:0)

尝试更改控制台字体,使用Lucida控制台等TrueType字体代替默认的栅格字体,因为第一个字体不支持Uni字符。