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.
86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
2 years ago
|
package device
|
||
|
|
||
|
import (
|
||
|
"FRMS/internal/pkg/i2c"
|
||
|
"encoding/hex"
|
||
|
"errors"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
// atlas helpers to fulfill sensor manager functions
|
||
|
|
||
|
type Atlas struct {
|
||
|
// delays passed by caller
|
||
|
CalDelay int
|
||
|
ReadDelay int
|
||
|
}
|
||
|
|
||
|
func (a *Atlas) Calibrate(bus, addr int, cal string) error {
|
||
|
// calibrate sensor
|
||
|
if a.CalDelay == 0 {
|
||
|
return errors.New("Cal delay unset, please check config")
|
||
|
}
|
||
|
if _, err := i2c.SendCmd(bus, addr, cal); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
time.Sleep(time.Duration(a.CalDelay) * time.Millisecond) // sleep
|
||
|
|
||
|
_, err := i2c.SendCmd(bus, addr, "") // read for success
|
||
|
// return the err if there is any
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
var ErrReadFail = errors.New("atlas read failure")
|
||
|
|
||
|
func (a *Atlas) TakeReading(bus, addr int) (float64, error) {
|
||
|
// take reading function
|
||
|
if _, err := i2c.SendCmd(bus, addr, "R"); err != nil {
|
||
|
// read command
|
||
|
return 0, err
|
||
|
}
|
||
|
if a.ReadDelay == 0 {
|
||
|
return 0, errors.New("Read Delay unset, please check config")
|
||
|
}
|
||
|
sleep := time.Duration(a.ReadDelay) * time.Millisecond
|
||
|
time.Sleep(sleep) // sleep between reads
|
||
|
data, err := i2c.SendCmd(bus, addr, "")
|
||
|
if err != nil {
|
||
|
return 0, ErrReadFail
|
||
|
}
|
||
|
|
||
|
// fmt data from 0x... to proper
|
||
|
var final string
|
||
|
split := strings.Split(data, " ")
|
||
|
for i, v := range split {
|
||
|
// loop over chars
|
||
|
if i == 0 && v != "0x01" {
|
||
|
// reading failed
|
||
|
return 0, ErrReadFail
|
||
|
}
|
||
|
// trimming bs
|
||
|
trimmed := strings.TrimLeft(v, "0x ")
|
||
|
trimmed = strings.TrimRight(trimmed, " \n")
|
||
|
if trimmed != "ff" && i != 0 {
|
||
|
final += trimmed
|
||
|
}
|
||
|
}
|
||
|
// return as a float
|
||
|
var b []byte
|
||
|
if b, err = hex.DecodeString(final); err != nil {
|
||
|
return 0, err
|
||
|
}
|
||
|
return strconv.ParseFloat(string(b), 32)
|
||
|
}
|
||
|
|
||
|
// for config
|
||
|
func (a *Atlas) GetCalDelay() int {
|
||
|
return a.CalDelay
|
||
|
}
|
||
|
|
||
|
func (a *Atlas) GetReadDelay() int {
|
||
|
return a.ReadDelay
|
||
|
}
|