54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
package common
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
type Device int
|
|
|
|
const (
|
|
Unknown Device = iota
|
|
TRex
|
|
HMI
|
|
Mobile
|
|
Service
|
|
)
|
|
|
|
// Key returns formatting for websockets, kafka, redis given an ID
|
|
// ex: TRex.Key("FISKER123") returns "1:FISKER123"
|
|
func (d Device) Key(id string) string {
|
|
return fmt.Sprintf("%d:%s", d, id)
|
|
}
|
|
|
|
func (d Device) String() string {
|
|
return [...]string{"unknown", "trex", "hmi", "mobile", "service"}[d]
|
|
}
|
|
|
|
func (d Device) EnumIndex() int {
|
|
return int(d)
|
|
}
|
|
|
|
// ParseDeviceKey is a generic parser for keys from websockets, kafka, redis
|
|
// If unable to parse string correctly, will return device type Unknown
|
|
// ex: "1:FISKER123" returns (TRex, "FISKER123")
|
|
// ex: "-1:FISKER123" returns (Unknown, "FISKER123")
|
|
// ex: "FISKER123" returns (Unknown, "FISKER123")
|
|
func ParseDeviceKey(key string) (Device, string) {
|
|
keys := strings.Split(key, ":")
|
|
|
|
if len(keys) == 1 {
|
|
return Unknown, keys[0]
|
|
} else if len(keys) != 2 {
|
|
return Unknown, ""
|
|
}
|
|
|
|
i, err := strconv.Atoi(keys[0])
|
|
if err != nil {
|
|
return Unknown, keys[1]
|
|
}
|
|
|
|
return Device(i), keys[1]
|
|
}
|