我怎样才能读取OpenNETCF.IO.Ports.SerialPort字符串? [英] How can I read a string from OpenNETCF.IO.Ports.SerialPort?
问题描述
我写使用OpenNETCF.IO.Ports.SerialPort这种方式带打印机命令:
I write commands to a belt printer using OpenNETCF.IO.Ports.SerialPort this way:
public static bool SendCommandToPrinter(string cmd)
{
bool success; // init'd to false by default
try
{
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd);
serialPort.Close();
success = true;
}
catch // may not need a try/catch block, as success defaults to false
{
success = false;
}
return success;
}
...现在我需要阅读从获得VAL返回的值打电话,但我不知道怎么了,我一直没能找到如何做到这一点。我有以下的开始,但不知道如何填空:
...now I need to read a value returned from a "get val" call, but I don't know how, and I haven't been able to find how, to do that. I have the following start, but don't know how to "fill in the blank":
string getDeviceLang = string.Format("! U1 getvar {0}device.languages{0}", quote);
public static string GetSettingFromPrinter(string cmd)
{
string settingVal = string.Empty;
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd); // do I even need this call to write?
settingVal = serialPort.Read() // ???
serialPort.Close();
return settingVal;
}
OpenNETCF.IO.Ports.SerialPort的Read()方法接受一个字节数组(缓冲),随后通过一个int(偏置)和另一INT(计数),以及返回int。我不知道作为args设置为使用或什么什么,结果INT做。
OpenNETCF.IO.Ports.SerialPort's Read() method takes an array of bytes ("buffer"), followed by an int ("offset") and another int ("count"), and returns an int. I don't know what to use as args or what to do with the result int.
我想这样的:
public static string GetSettingFromPrinter(string cmd)
{
string settingVal = string.Empty;
try
{
SerialPort serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.Open();
serialPort.Write(cmd);
// testing...
settingVal = serialPort.ReadLine();
serialPort.Close();
return settingVal;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return settingVal;
}
}
...但是,奖励我的less-比满意,System.NotSupportedException:尚未在OpenNETCF.IP.Ports.SerialPort.ReadTo(字符串值)......
...but that rewards me with the less-than-satisfactory, "System.NotSupportedException: not yet at OpenNETCF.IP.Ports.SerialPort.ReadTo(String value) at..."
我添加了这个:
serialPort.ReadTimeout = 500;// made no difference
更新3
根据< A HREF =http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.readline%28v=vs.110%29.aspx相对=nofollow>这个,我试图得到它的工作是这样的:
UPDATE 3
Based on this, I tried to get it to work this way:
public class PrintUtils
{
static SerialPort _serialPort;
static bool keepReading = true;
static string settingVal = string.Empty;
. . .
public static string GetSettingFromPrinter(string cmd)
{
Thread readThread = new Thread(ReadSetting());
try
{
_serialPort = new SerialPort();
_serialPort.BaudRate = 19200;
_serialPort.Handshake = Handshake.XOnXOff;
_serialPort.Open();
while (keepReading)
{
_serialPort.WriteLine(cmd);
}
_serialPort.Close();
return settingVal;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return settingVal;
}
}
public static void ReadSetting()
{
while (keepReading)
{
try
{
settingVal = _serialPort.ReadLine();
keepReading = settingVal.Equals(string.Empty);
}
catch (Exception ex) { MessageBox.Show(ex.ToString());}
}
}
...但我得到的方法'PDAClient.PrintUtils.Read()没有括号引用的在这一行:
...but I get, "Method 'PDAClient.PrintUtils.Read()' referenced without parentheses" on this line:
Thread readThread = new Thread(Read);
如果我的不的给它的括号:
If I do give it parens:
Thread readThread = new Thread(ReadSetting());
...它告诉我,参数1:无法从空转换到System.Threading.ThreadStart的
- 和:
的对于System.Threading.Thread.Thread(System.Threading.ThreadStart)的最佳重载的方法匹配'有一些无效参数的
和与此代码:
public static string GetSettingFromPrinter(string cmd)
{
string setting = string.Empty;
byte[] buffer = null;
try
{
SerialPort serialPort = new SerialPort();
serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.ReadTimeout = 500;
serialPort.Open();
serialPort.Write(cmd);
setting = Convert.ToString(serialPort.Read(buffer, 0, buffer.Length));
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
我得到一个NRE。
I get an NRE.
这尝试:
serialPort.WriteLine(cmd);
setting = serialPort.ReadExisting();
...结束很类似地,以第一次更新(System.NotSupportedException。 IP.Ports.SerialPort.ReadExisting()在...)
...ends very similary to the first Update ("System.NotSupportedException: not yet at OpenNETCF.IP.Ports.SerialPort.ReadExisting() at...")
好吧,我注册成立了伪码ctacke的评论,所以现在我有这样的:
Okay, I incorporated the pseudocode in ctacke's comment, and so now I've got this:
const string quote = "\"";
. . .
string getDeviceLang = string.Format("! U1 getvar {0}device.languages{0}", quote);
. . .
String deviceLanguage = PrintUtils.GetSettingFromPrinter(getDeviceLang);
public static string GetSettingFromPrinter(string cmd)
{
string setting = string.Empty;
try
{
SerialPort serialPort = new SerialPort();
serialPort = new SerialPort();
serialPort.BaudRate = 19200;
serialPort.Handshake = Handshake.XOnXOff;
serialPort.ReadTimeout = 500;
serialPort.Open();
serialPort.WriteLine(cmd); // or Write()
// get a synchronous, newline-delimited response
StringBuilder response = new StringBuilder();
char c;
do
{
c = (char)serialPort.ReadByte();
response.Append(c);
} while(c != '\n');
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
...但它挂起 - 似乎有一个无限循环。在do ... while循环
...but it "hangs" - there seems to be an infinite loop in the do...while loop.
我说这个ReadByte之后:
I added this after the "ReadByte":
MessageBox.Show(c.ToString());
......,所有这表明我是什么(有没有内部文本一个MessageBox);我让前弹出32次,我的预热启动装置。
...and all it shows me is nothing (a MessageBox with no "inner text"); I let it pop up 32 times before I warm-booted the device.
好吧,那么,我认错 - 我的不的使用OpenNETCF的SerialPort,因为没有这样的事情。所以,我想和这个基础上提供的伪ctacke。现在我试图使用方法:
Okay, then, I stand corrected - I was not using the OpenNETCF SerialPort, as there is no such thing. So I am trying to and have this, based on the pseudocode ctacke provided. I'm now trying to use:
Port serialPort = new Port();
serialPort.Settings = whateverPortSettingsYouNeed;
serialPort.Open();
serialPort.Send(cmd);
...但我不知道什么是whateverPortSettingsYouNeed应该是,有没有发送的方法,我不知道的地方ReadByte的使用什么()
...but I don't know what "whateverPortSettingsYouNeed" should be, there is not "Send" method, and I don't know what to use in place of ReadByte()
我现在有这样的设置:
BasicPortSettings bps = new BasicPortSettings();
bps.BaudRate = 19200;
//bps.ByteSize = ?;
//bps.Parity = None;
//bps.StopBits = 1;
Port serialPort = new Port();
serialPort.Settings = bps;
...但是,正如你所看到的,我不知道是什么大部分值应。是
...but, as you can see, I don't know what most of the values should be.
这编译:
public static string GetSettingFromPrinter(string cmd)
{
string setting = string.Empty;
try
{
BasicPortSettings bps = new BasicPortSettings();
bps.BaudRate = BaudRates.CBR_19200;
bps.Parity = OpenNETCF.IO.Serial.Parity.none;
bps.StopBits = OpenNETCF.IO.Serial.StopBits.one; //bps.StopBits.one;
Port serialPort = new Port("COM1:", bps);
byte[] outputBytes = System.Text.Encoding.ASCII.GetBytes(cmd);
serialPort.Output = outputBytes;
serialPort.Open();
byte[] bites = serialPort.Input;
setting = bites.ToString();
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
...现在我去看看它实际上工程...
...Now I'll see if it actually works...
我发现(硬盘的方式),我不得不打开设置输出VAL之前端口;它现在是:
I found out (the hard way) that I had to Open the port before setting the Output val; it's now:
serialPort.Open();
byte[] outputBytes = Encoding.ASCII.GetBytes(cmd);
serialPort.Output = outputBytes;
byte[] inputBytes = serialPort.Input;
setting = inputBytes.ToString();
...但读入的设置是System.Byte []
...but what is read into setting is "System.Byte[]"
我需要什么真正得到在inputBytes的价值,而不是仅仅看它的类型的代表性?
What do I need to actually get at the value in inputBytes, rather than just see a representation of its type?
推荐答案
我注意到的第一件事是,你使用了一个名为的SerialPort
类,这意味着你使用的代码SDF 1.x的这红枣在最近到2005年大约。不知道我会过于充满热情有关。我创建了一个只包含端口
类一的开源库>后的代码,但它的工作方式不同 - 这是VB6的串口对象模型为蓝本。老实说,我不记得,即使是谁写在自卫队的1.x代码 - 可能是我,可能没有。我觉得不只是代码风格我见判断。
The first thing I notice is that you're using a class called SerialPort
which means you're using code from SDF 1.x which dates to circa 2005 at the most recent. Not sure I'd be overly enthused about that. I created an open source library that contains just a Port
class after that code but it works way different - it was modeled after the VB6 serial port object model. I honestly don't even recall who wrote the code in SDF 1.x - might have been me, might not have. I think not just judging by the code style I see.
我要问你为什么不直接使用内置的CF系列的东西,但如果你'再使用SDF 1.x中,你很可能使用的是CF版本,预日期列入一个串口的API。
I was going to question why you didn't just use the built-in CF serial stuff, but if you're using SDF 1.x, you're likely using a CF version that pre-dates inclusion of a serial port API.
对于一个你正在使用现在,我想,这一定程度上取决于回来的数据是如何预期,但伪代码将是这个样子:
As for the one you're using now, I would think that it somewhat depends on how the data coming back is expected, but the pseudocode would look something like this:
var port = new SerialPort;
port.Settings = whateverPortSettingsYouNeed;
port.Open();
....
// send the command
port.Send(myCommand);
// get a synchronous, newline-delimited response
var response = new StringBuilder();
char c;
do
{
c = (char)port.ReadByte();
// see if it actually read anything
if(c == '\0')
{
// wait a little bit, then try again - you will want to put in a timeout here
Thread.Sleep(10);
continue;
}
response.Append(c);
// you may want to check for response "reasonableness" here
} while(c != \n');
DoSomethingWithResponse(response);
这篇关于我怎样才能读取OpenNETCF.IO.Ports.SerialPort字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!