1
0
Fork 0
hats/pkg/homeassistant/util.go

84 lines
2.2 KiB
Go
Raw Permalink Normal View History

2023-10-12 17:23:35 +00:00
package homeassistant
import (
2023-10-18 18:35:46 +00:00
"fmt"
2023-11-30 20:36:57 +00:00
"strconv"
2023-10-12 17:23:35 +00:00
"strings"
2023-10-18 18:35:46 +00:00
"time"
2023-10-12 17:23:35 +00:00
)
// StateToBool converts a state string into a boolean
//
2023-11-30 20:36:57 +00:00
// States that return true: "on", "home", "open", "opening", "unlocked", "playing", "active", "good",
// "walking", "charging", "alive", "heat", "heat_cool", "cool", "above_horizon", numbers > 0
2023-10-12 17:23:35 +00:00
// All others return false
func StateToBool(state string) bool {
2023-11-30 20:36:57 +00:00
switch state {
// truthy
case "on", "home", "open", "opening", "unlocked", "playing", "active", "good",
"walking", "charging", "alive", "heat", "heat_cool", "cool", "above_horizon":
return true
// falsey
case "off", "away", "closed", "closing", "locked", "paused", "inactive", "bad",
"discharging", "dead", "below_horizon", "0", "0.0":
return false
}
// number greater than zero
val, err := strconv.ParseFloat(state, 64)
if err == nil && val > 0.0 {
return true
}
// unaccounted for
return false
2023-10-12 17:23:35 +00:00
}
// BoolToService converts a boolean into the appropriate service string
//
// For locks: true becomes "unlock" and false becomes "lock"
// For covers: true becomes "open_cover" and false becomes "close_cover"
// For all others: true becomes "turn_on" and false becomes "turn_off"
func BoolToService(entityId string, desiredState bool) string {
domain := strings.Split(entityId, ".")[0]
switch domain {
case Domains.Lock:
if desiredState {
return Services.Unlock
} else {
return Services.Lock
}
case Domains.Cover:
if desiredState {
return Services.OpenCover
} else {
return Services.CloseCover
}
default:
if desiredState {
return Services.TurnOn
} else {
return Services.TurnOff
}
}
}
2023-10-18 18:35:46 +00:00
// Parse a Home Assistant duration in HH:MM:SS format
func ParseDuration(d string) (time.Duration, error) {
var hour, min, sec int
_, err := fmt.Sscanf(d, "%d:%d:%d", &hour, &min, &sec)
if err != nil {
return 5 * time.Minute, err
}
return time.Duration(hour)*time.Hour + time.Duration(min)*time.Minute + time.Duration(sec)*time.Second, nil
}
// func FormatDuration(d time.Duration) string {
// hours := math.Floor(d.Hours())
// minutes := math.Floor(d.Minutes() - (hours * 60))
// seconds := math.Floor(d.Seconds() - (hours * 60 * 60) - (minutes * 60))
// return fmt.Sprintf("%02.f:%02.f:%02.f", hours, minutes, seconds)
// }