use log.Fatalf

This commit is contained in:
Josh Deprez 2024-11-06 09:26:14 +11:00
parent cb8e380601
commit 1028991b87

View file

@ -29,10 +29,7 @@ import (
"periph.io/x/host/v3"
)
func mainImpl() error {
if _, err := host.Init(); err != nil {
return err
}
func main() {
httpAddr := flag.String("http-address", ":9455", "Listen addr for HTTP handler")
i2cAddress := flag.Int("i2c-address", 0x45, "I²C address")
i2cBus := flag.String("i2c-bus", "", "I²C bus (/dev/i2c-1)")
@ -43,27 +40,27 @@ func mainImpl() error {
resistor, err := parseNanoSI[physic.ElectricResistance](*senseResistor)
if err != nil {
return fmt.Errorf("parsing --sense-resistor: %w", err)
log.Fatalf("parsing --sense-resistor: %w", err)
}
if resistor <= 0 {
return fmt.Errorf("--sense-resistor must be positive")
log.Fatalf("--sense-resistor must be positive")
}
current, err := parseNanoSI[physic.ElectricCurrent](*maxCurrent)
if err != nil {
return fmt.Errorf("parsing --max-current: %w", err)
log.Fatalf("parsing --max-current: %w", err)
}
if current <= 0 {
return fmt.Errorf("--max-current must be positive")
log.Fatalf("--max-current must be positive")
}
if _, err := host.Init(); err != nil {
return err
log.Fatalf("host.Init() error: %v", err)
}
// Open default I²C bus.
bus, err := i2creg.Open(*i2cBus)
if err != nil {
return fmt.Errorf("failed to open I²C: %v", err)
log.Fatalf("i2creg.Open(%v): %v", *i2cBus, err)
}
defer bus.Close()
@ -73,7 +70,7 @@ func mainImpl() error {
MaxCurrent: current,
})
if err != nil {
return fmt.Errorf("failed to open new sensor: %v", err)
log.Fatalf("ina219.New(...): %v", err)
}
constLabels := prometheus.Labels{"i2c_addr": fmt.Sprintf("0x%x", *i2cAddress)}
@ -162,18 +159,18 @@ func mainImpl() error {
case <-everySecond:
p, err := sensor.Sense()
if err != nil {
return fmt.Errorf("sensor reading error: %v", err)
log.Fatalf("sensor.Sense() error: %v", err)
}
// sanity check sensor outputs:
// current = shunt / resistor, but resistor is fixed,
// so if current == 0 if and only if shunt == 0
if (p.Current == 0) != (p.Shunt == 0) {
return fmt.Errorf("current = %v but shunt = %v", p.Current, p.Shunt)
log.Fatalf("Ohm's Law violation: current = %v but shunt = %v", p.Current, p.Shunt)
}
// power = current * voltage, similar logic
if (p.Power == 0) != (p.Current == 0 || p.Voltage == 0) {
return fmt.Errorf("power = %v but current = %v and voltage = %v", p.Power, p.Current, p.Voltage)
log.Fatalf("Joule's First Law violation: power = %v but current = %v and voltage = %v", p.Power, p.Current, p.Voltage)
}
busVolts := float64(p.Voltage) / float64(physic.Volt)
@ -193,18 +190,11 @@ func mainImpl() error {
shuntVoltageSumm.Observe(shuntVolts)
case <-halt:
return nil
return
}
}
}
func main() {
if err := mainImpl(); err != nil {
fmt.Fprintf(os.Stderr, "ina219: %s.\n", err)
return
}
}
var siSmallRE = regexp.MustCompile(`^(\d+)(m|mu|µ|n)?$`)
func parseNanoSI[U ~int64](s string) (U, error) {