使用ATCommand将串行端口的编码更改为utf-8 [英] changing encoding to utf-8 for serial port using ATCommand
本文介绍了使用ATCommand将串行端口的编码更改为utf-8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究通过ATCommand发送和接收短信的示例.问题是我想发送波斯短信.我将串行端口的编码更改为"utf-8",但文本未正确发送.我该怎么办?
编辑-从答案移到
I''m working on a sample that sends and receives sms via ATCommand. The problem is i want to send farsi sms. I changed the encoding of my serial port to "utf-8" but my text hasn''t been sent correctly. What can I do?
EDIT - Moved from Answer
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO.Ports;
using System.Threading;
using System.Text.RegularExpressions;
namespace SMSapplication
{
public class clsSMS
{
#region Open and Close Ports
//Open Port
public SerialPort OpenPort(string p_strPortName, int p_uBaudRate, int p_uDataBits, int p_uReadTimeout, int p_uWriteTimeout)
{
receiveNow = new AutoResetEvent(false);
SerialPort port = new SerialPort();
try
{
port.PortName = p_strPortName; //COM1
port.BaudRate = p_uBaudRate; //9600
port.DataBits = p_uDataBits; //8
port.StopBits = StopBits.One; //1
port.Parity = Parity.None; //None
port.ReadTimeout = p_uReadTimeout; //300
port.WriteTimeout = p_uWriteTimeout; //300
port.Encoding = Encoding.GetEncoding("utf-8");
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
}
catch (Exception ex)
{
throw ex;
}
return port;
}
//Close Port
public void ClosePort(SerialPort port)
{
try
{
port.Close();
port.DataReceived -= new SerialDataReceivedEventHandler(port_DataReceived);
port = null;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
//Execute AT Command
public string ExecCommand(SerialPort port,string command, int responseTimeout, string errorMessage)
{
try
{
port.DiscardOutBuffer();
port.DiscardInBuffer();
receiveNow.Reset();
port.Write(command + "\r");
string input = ReadResponse(port, responseTimeout);
if ((input.Length == 0) || ((!input.EndsWith("\r\n> ")) && (!input.EndsWith("\r\nOK\r\n"))))
throw new ApplicationException("No success message was received.");
return input;
}
catch (Exception ex)
{
throw ex;
}
}
//Receive data from port
public void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (e.EventType == SerialData.Chars)
{
receiveNow.Set();
}
}
catch (Exception ex)
{
throw ex;
}
}
public string ReadResponse(SerialPort port,int timeout)
{
string buffer = string.Empty;
try
{
do
{
if (receiveNow.WaitOne(timeout, false))
{
string t = port.ReadExisting();
buffer += t;
}
else
{
if (buffer.Length > 0)
throw new ApplicationException("Response received is incomplete.");
else
throw new ApplicationException("No data received from phone.");
}
}
while (!buffer.EndsWith("\r\nOK\r\n") && !buffer.EndsWith("\r\n> ") && !buffer.EndsWith("\r\nERROR\r\n"));
}
catch (Exception ex)
{
throw ex;
}
return buffer;
}
#region Count SMS
public int CountSMSmessages(SerialPort port)
{
int CountTotalMessages = 0;
try
{
#region Execute Command
string recievedData = ExecCommand(port, "AT", 300, "No phone connected at ");
recievedData = ExecCommand(port, "AT+CMGF=1", 300, "Failed to set message format.");
String command = "AT+CPMS?";
recievedData = ExecCommand(port, command, 1000, "Failed to count SMS message");
int uReceivedDataLength = recievedData.Length;
#endregion
#region If command is executed successfully
if ((recievedData.Length >= 45) && (recievedData.StartsWith("AT+CPMS?")))
{
#region Parsing SMS
string[] strSplit = recievedData.Split(',');
string strMessageStorageArea1 = strSplit[0]; //SM
string strMessageExist1 = strSplit[1]; //Msgs exist in SM
#endregion
#region Count Total Number of SMS In SIM
CountTotalMessages = Convert.ToInt32(strMessageExist1);
#endregion
}
#endregion
#region If command is not executed successfully
else if (recievedData.Contains("ERROR"))
{
#region Error in Counting total number of SMS
string recievedError = recievedData;
recievedError = recievedError.Trim();
recievedData = "Following error occured while counting the message" + recievedError;
#endregion
}
#endregion
return CountTotalMessages;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Read SMS
public AutoResetEvent receiveNow;
public ShortMessageCollection ReadSMS(SerialPort port, string p_strCommand)
{
// Set up the phone and read the messages
ShortMessageCollection messages = null;
try
{
#region Execute Command
// Check connection
ExecCommand(port,"AT", 300, "No phone connected");
// Use message format "Text mode"
ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.");
// Use character set "PCCP437"
ExecCommand(port,"AT+CSCS=\"PCCP437\"", 300, "Failed to set character set.");
// Select SIM storage
ExecCommand(port,"AT+CPMS=\"SM\"", 300, "Failed to select message storage.");
// Read the messages
string input = ExecCommand(port, p_strCommand, 5000, "Failed to read the messages.");
#endregion
#region Parse messages
messages = ParseMessages(input);
#endregion
}
catch (Exception ex)
{
throw ex;
}
if (messages != null)
return messages;
else
return null;
}
public ShortMessageCollection ParseMessages(string input)
{
ShortMessageCollection messages = new ShortMessageCollection();
try
{
Regex r = new Regex(@"\+CMGL: (\d+),""(.+)"",""(.+)"",(.*),""(.+)""\r\n(.+)\r\n");
Match m = r.Match(input);
while (m.Success)
{
ShortMessage msg = new ShortMessage();
//msg.Index = int.Parse(m.Groups[1].Value);
msg.Index = m.Groups[1].Value;
msg.Status = m.Groups[2].Value;
msg.Sender = m.Groups[3].Value;
msg.Alphabet = m.Groups[4].Value;
msg.Sent = m.Groups[5].Value;
msg.Message = m.Groups[6].Value;
messages.Add(msg);
m = m.NextMatch();
}
}
catch (Exception ex)
{
throw ex;
}
return messages;
}
#endregion
#region Send SMS
static AutoResetEvent readNow = new AutoResetEvent(false);
public bool sendMsg(SerialPort port, string PhoneNo, string Message)
{
bool isSend = false;
try
{
string recievedData = ExecCommand(port,"AT", 300, "No phone connected");
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.");
String command = "AT+CMGS=\"" + PhoneNo + "\"";
recievedData = ExecCommand(port,command, 300, "Failed to accept phoneNo");
command = Message + char.ConvertFromUtf32(26) + "\r";
recievedData = ExecCommand(port,command, 3000, "Failed to send message"); //3 seconds
if (recievedData.EndsWith("\r\nOK\r\n"))
{
isSend = true;
}
else if (recievedData.Contains("ERROR"))
{
isSend = false;
}
return isSend;
}
catch (Exception ex)
{
throw ex;
}
}
static void DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (e.EventType == SerialData.Chars)
readNow.Set();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Delete SMS
public bool DeleteMsg(SerialPort port , string p_strCommand)
{
bool isDeleted = false;
try
{
#region Execute Command
string recievedData = ExecCommand(port,"AT", 300, "No phone connected");
recievedData = ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.");
String command = p_strCommand;
recievedData = ExecCommand(port,command, 300, "Failed to delete message");
#endregion
if (recievedData.EndsWith("\r\nOK\r\n"))
{
isDeleted = true;
}
if (recievedData.Contains("ERROR"))
{
isDeleted = false;
}
return isDeleted;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
我不想在串行端口上写ro read.我想在命令中使用串行端口.
I don''t want to write ro read on serial port. i want to use serial port for at command.
推荐答案
编码与字节数组(而不是字符串)有关,因为.NET字符串在内部使用UTF-16编码.尝试使用System.IO.Ports.SerialPort.Write(Byte[], Int32, Int32)
,而不是Write(String)
并阅读Read(Byte[], Int32, Int32)
.请参阅 http://msdn.microsoft.com/en-us/library/system .io.ports.serialport.aspx [ ^ ].
现在,要获取字节数组,请使用System.Text.Encoding.GetBytes(String)
和System.Text.Encoding.GetChars(Byte[])
初始化字节数组中的字符串.请参阅 http://msdn.microsoft.com/en-us/library/system.text .encoding.aspx [ ^ ].对于您的编码实例,请使用System.Text.UTF8Encoding
.
另请参见:
http://unicode.org/ [ ^ ],
http://unicode.org/faq/utf_bom.html [
Encoding is something related to array of bytes, not strings, as .NET strings internally use encoding UTF-16. Try to useSystem.IO.Ports.SerialPort.Write(Byte[], Int32, Int32)
, notWrite(String)
and readRead(Byte[], Int32, Int32)
. See http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx[^].
Now, to get array of bytes, useSystem.Text.Encoding.GetBytes(String)
andSystem.Text.Encoding.GetChars(Byte[])
to initialize the string from array of bytes; see http://msdn.microsoft.com/en-us/library/system.text.encoding.aspx[^]. For your encoding instance, useSystem.Text.UTF8Encoding
.
See also:
http://unicode.org/[^],
http://unicode.org/faq/utf_bom.html[^].
If it does not help, make a code sample and post it — the problem could be somewhere else.
—SA
这篇关于使用ATCommand将串行端口的编码更改为utf-8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文