Files
beatglow/cmd/harmon/scan.go
T
2026-10-29 17:29:41 +01:00

94 lines
1.8 KiB
Go

package main
import (
"context"
"fmt"
"syscall"
"unsafe"
"github.com/go-daq/smbus"
"github.com/urfave/cli/v3"
)
var scanCommand = &cli.Command{
Name: "scan",
Category: "i2c",
Usage: "Scan the I2C bus for active devices",
Action: scanFunc,
Flags: []cli.Flag{
&cli.IntFlag{Name: "bus", Usage: "I²C bus to use", Value: 1},
&cli.IntFlag{Name: "first", Usage: "First address", Value: 0x03},
&cli.IntFlag{Name: "last", Usage: "Last address", Value: 0x77},
&cli.BoolFlag{Name: "error", Usage: "Print errors"},
},
}
func scanFunc(ctx context.Context, cmd *cli.Command) error {
bus, err := smbus.OpenFile(int(cmd.Int("bus")))
if err != nil {
return err
}
defer bus.Close()
var (
first = int(cmd.Int("first"))
last = int(cmd.Int("last"))
errs []error
)
fmt.Println(" 0 1 2 3 4 5 6 7 8 9 a b c d e f")
for i := 0; i < 128; i += 16 {
fmt.Printf("%02x: ", i)
for j := 0; j < 16; j++ {
if i+j < first || i+j > last {
fmt.Print(" ")
continue
}
if err := bus.SetAddr(uint8(i + j)); err != nil {
errs = append(errs, err)
fmt.Print("UU ")
continue
}
useRead := ((i+j >= 0x30 && i+j <= 0x37) || (i+j >= 0x50 && i+j <= 0x5F))
if useRead || true {
_, err = bus.ReadReg(uint8(i+j), 0)
}
if err == nil {
fmt.Printf("%02x ", i+j)
errs = append(errs, nil)
} else {
fmt.Printf("-- ")
errs = append(errs, err)
}
}
fmt.Println()
}
if cmd.Bool("error") {
for i := first; i < last; i++ {
if err := errs[i-first]; err != nil {
fmt.Printf("%02x: %v\n", i, err)
}
}
}
return bus.Close()
}
func ioctl(fd, cmd, arg uintptr) (err error) {
_, _, e1 := syscall.Syscall6(syscall.SYS_IOCTL, fd, cmd, arg, 0, 0, 0)
if e1 != 0 {
err = e1
}
return
}
type i2cCmd struct {
rw uint8
cmd uint8
len uint32
ptr unsafe.Pointer
}