Search code examples
serial-portportopennetcf

What is the necessary call to send data over COM port using OpenNETCF Port class?


I am trying to retrieve a value from a Zebra printer by interrogating it with 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;
        serialPort.Query(); // <= this is new
        byte[] responseBytes = serialPort.Input;
        setting = GetString(responseBytes);
        serialPort.Close();
        return setting;
    }
    catch (Exception x)
    {
        MessageBox.Show(x.ToString());
        return setting;
    }
}

However, I don't see where the Output is actually sent, or how to do that. My best guess was calling the Port.Query() method, but that doesn't work, either - at least there is nothing in setting / the Port.Input value after doing so.

I have successfully passed commands to the printer using the older SerialPort class:

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;
}

...but was advised not to use that due to its longness of tooth.

I would revert back to this snaggletooth if I knew how to read from the old SerialPort class. Does anybody know what I need to do to send sendBytes (and receive responseBytes)?

UPDATE

I tested "COM1" instead of "COM1:" (I used the latter because there is a post that says the colon is necessary (<= not medical advice, although that is doubtless true in that sense, too), but sans the ":" made no noticeable difference.

I then tried "string.Empty" in place of giving it a name, and got, "OpenNETCF.IO.Serial.CommPortException: CreateFileFailed 2 ..."

Onward...or is it Sideward...


Solution

  • FWIW, setting the Output property immediately sends the data on the wire. No additional call is necessary.