Test / test (push) Failing after 25m47s
Go port of the read path of pybyd 0.0.75 (the client behind jkaberg/hass-byd-vehicle): the bangcle white-box AES envelope, the signing/checkcode layer, login, vehicle list, and realtime readings. Scraping runs on a cron schedule rather than per Prometheus request because each reading wakes the car's T-Box and drains the traction battery; /metrics serves the last result. Every numeric field of the realtime payload becomes a gauge, so the exporter does not need a hand-maintained field list that goes stale when BYD changes the payload. Tests pin the wire format against pybyd byte-for-byte and drive the client end to end against a fake cloud that speaks the real protocol. Co-Authored-By: Claude Opus 5 <[email protected]>
55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
// Package jsonv coerces values out of BYD's loosely typed JSON.
|
|
//
|
|
// The same field arrives as a JSON number in one response and a quoted string
|
|
// in the next, and absent fields arrive as null rather than being omitted, so
|
|
// every read goes through here rather than through a type assertion.
|
|
package jsonv
|
|
|
|
import (
|
|
"fmt"
|
|
"math"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// Str renders a value as a string, mapping nil to "" rather than "<nil>".
|
|
func Str(v any) string {
|
|
switch t := v.(type) {
|
|
case nil:
|
|
return ""
|
|
case string:
|
|
return t
|
|
case float64:
|
|
// JSON has no integers, so ids and codes arrive as float64. Exponent
|
|
// notation would corrupt them ("1.23456789e+09" as a user id), so
|
|
// integral values are rendered as integers.
|
|
if t == math.Trunc(t) && math.Abs(t) < 1e15 {
|
|
return strconv.FormatInt(int64(t), 10)
|
|
}
|
|
return strconv.FormatFloat(t, 'g', -1, 64)
|
|
case bool:
|
|
return strconv.FormatBool(t)
|
|
default:
|
|
return fmt.Sprint(v)
|
|
}
|
|
}
|
|
|
|
// Num coerces a value to a float. It reports false for anything that is not a
|
|
// number, a bool, or a string holding a number.
|
|
func Num(v any) (float64, bool) {
|
|
switch t := v.(type) {
|
|
case float64:
|
|
return t, true
|
|
case bool:
|
|
if t {
|
|
return 1, true
|
|
}
|
|
return 0, true
|
|
case string:
|
|
f, err := strconv.ParseFloat(strings.TrimSpace(t), 64)
|
|
return f, err == nil
|
|
default:
|
|
return 0, false
|
|
}
|
|
}
|