package alamo import ( "encoding/hex" "fmt" "math" "strings" ) type gatewayRecord struct { MAC *string `json:"mac"` Power *int `json:"power"` Target *float64 `json:"stemp"` Room *float64 `json:"temp"` Floor *float64 `json:"sensor"` Active *int `json:"ativo"` Locked *int `json:"bloqueio"` } func (r gatewayRecord) state() (State, error) { if r.MAC == nil || r.Power == nil || r.Target == nil || r.Room == nil || r.Floor == nil || r.Active == nil || r.Locked == nil { return State{}, fmt.Errorf("gateway record is incomplete") } mac, err := normalizeMAC(*r.MAC) if err != nil { return State{}, fmt.Errorf("validate record MAC: %w", err) } if !binary(*r.Power) || !binary(*r.Active) || !binary(*r.Locked) { return State{}, fmt.Errorf("gateway flags must be zero or one") } if !finite(*r.Target) || !finite(*r.Room) || !finite(*r.Floor) { return State{}, fmt.Errorf("gateway temperatures must be finite") } return State{ MAC: mac, Power: *r.Power == 1, TargetTemperature: *r.Target, CurrentTemperature: *r.Room, FloorTemperature: *r.Floor, Active: *r.Active == 1, Locked: *r.Locked == 1, }, nil } func normalizeMAC(value string) (string, error) { if len(value) != 12 { return "", fmt.Errorf("MAC must contain twelve hexadecimal digits") } _, err := hex.DecodeString(value) if err != nil { return "", fmt.Errorf("MAC must contain twelve hexadecimal digits") } return strings.ToLower(value), nil } func binary(value int) bool { return value == 0 || value == 1 } func finite(value float64) bool { return !math.IsNaN(value) && !math.IsInf(value, 0) }