-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfieldspec.go
48 lines (38 loc) · 1.29 KB
/
fieldspec.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package iotc4i
import (
"encoding/binary"
"fmt"
)
// TryDecodeData decodes the given byte slice into a map according to the field specifications.
func TryDecodeData(data []byte, fields []Field) (map[string]interface{}, error) {
result := make(map[string]interface{})
for _, field := range fields {
// Skip processing if the field has no name
if field.Name == "" {
continue
}
if field.StartIdx > field.EndIdx || field.EndIdx >= len(data) {
return nil, fmt.Errorf("invalid index range for field: %s", field.Name)
}
// Extract the bytes for the current field
fieldBytes := data[field.StartIdx : field.EndIdx+1]
// Interpret the fieldBytes as a single integer
if field.Name != "" {
result[field.Name] = ByteListToInteger(fieldBytes, field.IsSigned)
}
}
return result, nil
}
func ParseDataWithSpecification(payload []byte, specData []Field) (map[string]interface{}, error) {
// Decode the message payload using the field specifications
parsed, err := TryDecodeData(payload, specData)
if err != nil {
return nil, err
}
messageSize := len(payload)
hash := binary.LittleEndian.Uint32(payload[messageSize-4 : messageSize])
calculatedHash := CalculateHashWithZerofill(payload, specData)
parsed["DesiredHash"] = hash
parsed["CalculatedHash"] = calculatedHash
return parsed, nil
}