Pregunta

So, I'm attempting to communicate with a device over a serialport object in C#. The device is looking for a mask value to be sent to it as a part of a command string. For example, one of the strings will be something like "SETMASK:{}", where {} is the unsigned 8-bit mask.

When I use a terminal (such as BRAY) to communicate with the device, I can get the device to work. For example, in BRAY terminal, the string SETMASK:$FF will set the mask to 0xFF. However, I can't for the life of me figure out how to do this in C#.

I've already tried the following function, where Data is the mask value and CMD is the surrounding string ("SETMASK:" in this case"). Where am I going wrong?

public static string EmbedDataInString(string Cmd, byte Data)
    {
        byte[] ConvertedToByteArray = new byte[(Cmd.Length * sizeof(char)) + 2];
        System.Buffer.BlockCopy(Cmd.ToCharArray(), 0, ConvertedToByteArray, 0, ConvertedToByteArray.Length - 2);

        ConvertedToByteArray[ConvertedToByteArray.Length - 2] = Data;

        /*Add on null terminator*/
        ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00;

        Cmd = System.Text.Encoding.Unicode.GetString(ConvertedToByteArray);

        return Cmd;
    }
¿Fue útil?

Solución

Can't be certain, but I'll bet your device is expecting 1-byte chars, but the C# char is 2 bytes. Try converting your string into a byte array with Encoding.ASCII.GetBytes(). You'll probably also need to return the byte[] array instead of a string, since you'll end up converting it back to 2 byte chars.

using System.Text;

// ...

public static byte[] EmbedDataInString(string Cmd, byte Data)
{
    byte[] ConvertedToByteArray = new byte[Cmd.Length + 2];
    System.Buffer.BlockCopy(Encoding.ASCII.GetBytes(Cmd), 0, ConvertedToByteArray, 0, ConvertedToByteArray.Length - 2);

    ConvertedToByteArray[ConvertedToByteArray.Length - 2] = Data;

    /*Add on null terminator*/
    ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00;

    return ConvertedToByteArray;
}

If your device accepts some other character encoding, swap out ASCII for the appropriate one.

Otros consejos

Problem solved, the System.Buffer.BlockCopy() command was embedding zeroes after each character in the string. This works:

public static byte[] EmbedDataInString(string Cmd, byte Data)
    {
        byte[] ConvertedToByteArray = new byte[(Cmd.Length * sizeof(byte)) + 3];
        char[] Buffer = Cmd.ToCharArray();

        for (int i = 0; i < Buffer.Length; i++)
        {
            ConvertedToByteArray[i] = (byte)Buffer[i];
        }

        ConvertedToByteArray[ConvertedToByteArray.Length - 3] = Data;
        ConvertedToByteArray[ConvertedToByteArray.Length - 2] = (byte)0x0A;
        /*Add on null terminator*/
        ConvertedToByteArray[ConvertedToByteArray.Length - 1] = (byte)0x00;

        return ConvertedToByteArray;
    }
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top