-1

I am working on a program that communicates with a device connected through USB. When my program reads in data sent from the device (button presses, for example), it is sent as a byte array. I have key value pairs stored as a dictionary for the button press byte array and a string for the name of the button, which I display whenever it is pressed. This device also has sliders which sends byte arrays, but it has a full range, each slider is a different digit in the array

{ 3, 0, 0, 0, FF, 0, 0, 0 }

The range goes from 00 to FF in hex which I convert to decimal.

byte[] slider1rangeLower = { 3, 0, 0, 0, 00, 0, 0, 0 }
byte[] slider1rangeUpper = { 3, 0, 0, 0, 255, 0, 0, 0 }
byte[] slider2rangeLower = { 3, 0, 0, 00, 0, 0, 0, 0 }
byte[] slider2rangeUpper = { 3, 0, 0, 255, 0, 0, 0, 0 }

I need to know what slider is being used, so every value between 0-255 comes through as "slider1" or whatever the name might be. Is there any way to store a whole range of values for one object, as opposed to making 256 entries per slider?

4

1 回答 1

0

C# 是一种面向对象的语言,我将为设备创建一个具有所有属性的对象。由于我对该设备了解不多,所以我不得不猜测很多,但这是我想出的,它应该很容易扩展到您需要使用它的用途。

public class MyDevice
{
    private const int PayloadIdByte = 0;
    private const int PayloadSliderId = 3;
    private const int PayloadButtonId = 4;
    private const int Button1Byte = 1;
    private const int Button2Byte = 2;
    private const int Button3Byte = 3;
    private const int Slider1Byte = 4;
    private const int Slider2Byte = 3;
    private const int PayloadSize = 8;

    public bool Button1 { get; set; }
    public bool Button2 { get; set; }
    public bool Button3 { get; set; }
    public byte Slider1 { get; set; }
    public byte Slider2 { get; set; }

    public MyDevice()
    {

    }

    public void Update(byte[] payload)
    {
        if (payload.Length != PayloadSize)
            throw new ArgumentException("payload");

        if (payload[PayloadIdByte] == PayloadSliderId)
        {
            Slider1 = payload[Slider1Byte];
            Slider2 = payload[Slider2Byte];
        }

        if (payload[PayloadIdByte] == PayloadButtonId)
        {
            Button1 = payload[Button1Byte] > 0;
            Button2 = payload[Button2Byte] > 0;
            Button3 = payload[Button3Byte] > 0;
        }
    }
}

您可以在对象更新时添加事件、附加功能等。当您从 USB 读取新的有效负载时,只需将其传递给 Update 函数,让该函数将有效负载解析到对象中。

于 2015-04-24T22:45:38.673 回答