forked from OpenPDU/openpdu
86 lines
1.6 KiB
Go
86 lines
1.6 KiB
Go
package main
|
|
|
|
import (
|
|
"errors"
|
|
"log"
|
|
|
|
"periph.io/x/periph/conn/i2c"
|
|
"periph.io/x/periph/conn/i2c/i2creg"
|
|
"periph.io/x/periph/host"
|
|
)
|
|
|
|
// I2CBoard bla
|
|
type I2CBoard struct {
|
|
i2cdev i2c.Dev
|
|
channels uint
|
|
data []byte
|
|
inverted bool
|
|
}
|
|
|
|
// MyBoard bla
|
|
var MyBoard = I2CBoard{
|
|
channels: 8,
|
|
inverted: true,
|
|
}
|
|
|
|
func (b I2CBoard) channelStatus(ch uint) (bool, error) {
|
|
if b.channels <= 0 {
|
|
return false, errors.New("Board without channels")
|
|
}
|
|
if ch >= b.channels {
|
|
return false, errors.New("Invalid channel")
|
|
}
|
|
write := []byte{0x0A}
|
|
b.data = make([]byte, 2)
|
|
err := b.i2cdev.Tx(write, b.data)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
byteToConsider := ch / b.channels
|
|
value := (b.data[byteToConsider] >> ch & 1) == 1
|
|
if b.inverted {
|
|
value = !value
|
|
}
|
|
return value, nil
|
|
}
|
|
|
|
func initI2C() {
|
|
// Make sure periph is initialized.
|
|
if _, err := host.Init(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
// Use i2creg I²C bus registry to find the first available I²C bus.
|
|
mybus, err := i2creg.Open("/dev/i2c-0")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
// defer mybus.Close()
|
|
|
|
// bus 0
|
|
// Dev is a valid conn.Conn.
|
|
mydevice := &i2c.Dev{Addr: 0x27, Bus: mybus}
|
|
|
|
// Send a command 0x10 and expect a 5 bytes reply.
|
|
// write := []byte{0x10}
|
|
write := []byte{0x0}
|
|
// read := make([]byte, 5)
|
|
// if err := d.Tx(write, read); err != nil {
|
|
if _, err := mydevice.Write(write); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
MyBoard.i2cdev = *mydevice
|
|
|
|
go func() {
|
|
var i uint
|
|
for i = 0; i < 8; i++ {
|
|
v, err := MyBoard.channelStatus(i)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
log.Printf("Channel %d status: %v", i, v)
|
|
}
|
|
}()
|
|
}
|