feat(data-plane): implement phase3c gateway
This commit is contained in:
@@ -0,0 +1,38 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
)
|
||||
|
||||
var ErrInputMalformed = errors.New("input event malformed")
|
||||
|
||||
func EncodeInputEvent(event InputEvent) ([]byte, error) {
|
||||
if len(event.Device) == 0 || len(event.Device) > 64 || len(event.Payload) > 1024 {
|
||||
return nil, ErrInputMalformed
|
||||
}
|
||||
encoded := make([]byte, 16+len(event.Device)+len(event.Payload))
|
||||
copy(encoded[:4], "INP1")
|
||||
binary.BigEndian.PutUint32(encoded[4:8], event.Sequence)
|
||||
binary.BigEndian.PutUint32(encoded[8:12], uint32(event.Code))
|
||||
if event.Pressed {
|
||||
encoded[12] = 1
|
||||
}
|
||||
encoded[13] = byte(len(event.Device))
|
||||
binary.BigEndian.PutUint16(encoded[14:16], uint16(len(event.Payload)))
|
||||
copy(encoded[16:16+len(event.Device)], event.Device)
|
||||
copy(encoded[16+len(event.Device):], event.Payload)
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func DecodeInputEvent(data []byte) (InputEvent, error) {
|
||||
if len(data) < 16 || len(data) > 1179 || string(data[:4]) != "INP1" || (data[12] != 0 && data[12] != 1) {
|
||||
return InputEvent{}, ErrInputMalformed
|
||||
}
|
||||
deviceLength := int(data[13])
|
||||
payloadLength := int(binary.BigEndian.Uint16(data[14:16]))
|
||||
if deviceLength == 0 || deviceLength > 64 || payloadLength > 1024 || len(data) != 16+deviceLength+payloadLength {
|
||||
return InputEvent{}, ErrInputMalformed
|
||||
}
|
||||
return InputEvent{Sequence: binary.BigEndian.Uint32(data[4:8]), Code: int32(binary.BigEndian.Uint32(data[8:12])), Pressed: data[12] == 1, Device: string(data[16 : 16+deviceLength]), Payload: append([]byte(nil), data[16+deviceLength:]...)}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user