You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
89 lines
2.3 KiB
Go
89 lines
2.3 KiB
Go
package i2c
|
|
|
|
// file has general wrappers to interact with i2c-tools
|
|
|
|
import (
|
|
"FRMS/internal/pkg/logging"
|
|
"bytes"
|
|
"fmt"
|
|
_ "log"
|
|
"os/exec"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func GetConnected(b int) (map[int]bool, error) {
|
|
// Returns all the connected devices by address
|
|
// might just do this in bash and make it easier
|
|
bus := strconv.Itoa(b)
|
|
devices := make(map[int]bool) // only keys
|
|
cmd := exec.Command("i2cdetect", "-y", "-r", bus)
|
|
var out bytes.Buffer
|
|
var errs bytes.Buffer
|
|
cmd.Stderr = &errs
|
|
cmd.Stdout = &out
|
|
if err := cmd.Run(); err != nil {
|
|
logging.Debug(logging.DError, "I2C error performing scan. %v", errs.String())
|
|
return devices, err
|
|
}
|
|
|
|
outString := out.String()
|
|
// could split by \n too
|
|
split := strings.SplitAfter(outString, ":")
|
|
// 1st entry is garbage headers and ending is always \n##:
|
|
split = split[1:]
|
|
// create empty slice for all the devices
|
|
for i, v := range split {
|
|
lst := strings.Index(v, "\n")
|
|
trimmed := v[:lst]
|
|
trimmed = strings.Trim(trimmed, " ")
|
|
// trimmed now holds just possible sensor addresses
|
|
count := strings.Split(trimmed, " ")
|
|
for j, d := range count {
|
|
// the first row has to be offset by 3 but after its just i*16 + j
|
|
offset := 0
|
|
if i == 0 {
|
|
offset = 3
|
|
}
|
|
addr := i*16 + j + offset
|
|
if !strings.Contains(d, "--") && !strings.Contains(d, "UU") {
|
|
// active
|
|
devices[addr] = true
|
|
}
|
|
}
|
|
}
|
|
return devices, nil
|
|
}
|
|
|
|
func SendCmd(b, addr int, command string) (string, error) {
|
|
// sends an arbituary commnd over specified bus to int
|
|
// might make a base script for this too
|
|
var cmd *exec.Cmd
|
|
bus := strconv.Itoa(b)
|
|
operation := "r20" // default read
|
|
frmt_cmd := "" // empty cmd
|
|
if command != "" {
|
|
// command, do write
|
|
operation = fmt.Sprintf("w%d", len(command)) // write
|
|
// formatting cmd
|
|
for _, char := range command {
|
|
// loop over string
|
|
frmt_cmd += fmt.Sprintf("0x%x", char)
|
|
}
|
|
cmd = exec.Command("i2ctransfer", "-y", bus, fmt.Sprintf("%s@0x%x", operation, addr), frmt_cmd)
|
|
} else {
|
|
// reading
|
|
cmd = exec.Command("i2ctransfer", "-y", bus, fmt.Sprintf("%s@0x%x", operation, addr))
|
|
}
|
|
// exec command
|
|
var out bytes.Buffer
|
|
var errs bytes.Buffer
|
|
cmd.Stderr = &errs
|
|
cmd.Stdout = &out
|
|
if err := cmd.Run(); err != nil {
|
|
logging.Debug(logging.DError, "I2C error getting data! %v", err)
|
|
return "", err
|
|
}
|
|
return out.String(), nil
|
|
}
|