Where would be the best place to validate a CRC8 sum of the HID response?
I Have a HidController script that reads values from custom HID as well as binds InputActions to events. These events should not be fired in case of wrong HID response (wrong CRC8).
Implement IInputStateCallbackReceiver. Inspect the event when you get it in OnStateEvent, and don’t commit it via InputState.Change if the CRC is wrong.
Thanks for the reply! It looks like the correct approach, but I still need a help: How to get the bytes of the response from the InputEventPtr? Should I use unsafe mode?
Most likely yes. If you have a struct that defines the state for your devices, you can get it from the event like this
var state = StateEvent.GetState<MyStateStruct>(eventPtr);
But for computing a CRC this will likely not be of much use. StateEvent.From (or FromUnchecked if you already know it’s a state event) gives you a StateEvent. From there you get to the state via the state property.
You can compute a CRC directly from that memory or, if you need a byte[ ] array for a managed method, set aside a buffer you use over and over and just copy into.
private byte[] m_Buffer;
public unsafe void OnStateEvent(InputEventPtr eventPtr)
{
var stateEventPtr = StateEvent.FromUnchecked(eventPtr);
var stateSize = (int)stateEventPtr->stateSizeInBytes;
if (m_Buffer == null)
m_Buffer = new byte[stateSize];
fixed (byte* bufferPtr = m_Buffer)
UnsafeUtility.Memcpy(bufferPtr, stateEventPtr->state, stateSize);
var crc = MyCRCMethod(m_Buffer);
public void OnStateEvent(InputEventPtr eventPtr)
{
var o = (byte[])this.ReadValueFromEventAsObject(eventPtr);
var crc = Crc8.Calculate(o);
if (crc == 0)
InputState.Change(this, eventPtr);
else
Debug.LogWarning("CRC Failed!");
}
And I am it testing now.
But
var state = StateEvent.GetState<MyStateStruct>(eventPtr);
One thing I just caught, note that you also need to commit the new state yourself via InputState.Change. OnStateEvent basically says “if there’s a state event for me, don’t handle it; I’ll handle it myself”.