I am trying to send a "getvar" command to a printer over the serial port, and receive the response, but all I'm getting when trying to verify what I'm sending, and what is received is: "System.Byte[]"
Here is my code:
const string quote = "\"";
. . .
string getDeviceLang = string.Format("! U1 getvar {0}device.languages{0}", quote);
. . .
String deviceLanguage = PrintUtils.GetSettingFromPrinter(getDeviceLang);
. . .
MessageBox.Show(deviceLanguage); // <= this shows "System.Byte[]"
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;
Port serialPort = new Port("COM1:", bps);
serialPort.Open();
byte[] outputBytes = Encoding.ASCII.GetBytes(cmd);
MessageBox.Show(Convert.ToString(outputBytes)); // <= this shows "System.Byte[]"
serialPort.Output = outputBytes;
byte[] inputBytes = serialPort.Input;
setting = Convert.ToString(inputBytes);
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
What do I need to do to actually see the string I'm passing and receiving, rather than just a string representation of the data type?
UPDATE
Does this look right:
setting = System.Text.Encoding.ASCII.GetString(
inputBytes, 0, inputBytes.Length);
? It at least compiles, but...
UPDATE 2
Okay, this code:
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;
Port serialPort = new Port("COM1:", bps);
serialPort.Open();
byte[] sendBytes = Encoding.ASCII.GetBytes(cmd);
MessageBox.Show(Encoding.ASCII.GetString(sendBytes, 0,
sendBytes.Length));
serialPort.Output = sendBytes;
byte[] receiveBytes = serialPort.Input;
setting = GetString(receiveBytes);
serialPort.Close();
return setting;
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
return setting;
}
}
...does return the expected val (! U1 getvar "device.language") here:
MessageBox.Show(Encoding.ASCII.GetString(sendBytes, 0, sendBytes.Length));
...but still an empty string here:
String deviceLanguage = PrintUtils.GetSettingFromPrinter(getDeviceLang);
MessageBox.Show(deviceLanguage);
// Helper function, from http://stackoverflow.com/questions/472906/converting-a-string-to-byte-array
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / 2];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
Maybe the "sendBytes" simply aren't being sent, and that's why there's no response/nothing in receiveBytes...