1
0
Fork 0
mirror of https://github.com/kidoman/embd synced 2025-07-03 11:57:38 +02:00

bring in the idea of a hardware abstraction layer

This commit is contained in:
Karan Misra 2014-02-27 04:24:53 +05:30
parent b4de382833
commit b5e2d0acc7
35 changed files with 994 additions and 971 deletions

28
host/describe.go Normal file
View file

@ -0,0 +1,28 @@
package host
import (
"errors"
"github.com/kidoman/embd/gpio"
"github.com/kidoman/embd/host/rpi"
"github.com/kidoman/embd/i2c"
)
type Descriptor interface {
GPIO() gpio.GPIO
I2C() i2c.I2C
}
func Describe() (Descriptor, error) {
host, rev, err := Detect()
if err != nil {
return nil, err
}
switch host {
case RPi:
return rpi.Descriptor(rev), nil
default:
return nil, errors.New("host: invalid host")
}
}

78
host/detect.go Normal file
View file

@ -0,0 +1,78 @@
package host
import (
"fmt"
"os/exec"
"strconv"
"strings"
)
type Host int
const (
Null Host = iota
RPi
BBB
)
func execOutput(name string, arg ...string) (output string, err error) {
var out []byte
if out, err = exec.Command(name, arg...).Output(); err != nil {
return
}
output = string(out)
return
}
func nodeName() (string, error) {
return execOutput("uname", "-n")
}
func kernelVersion() (major, minor, patch int, err error) {
output, err := execOutput("uname", "-r")
if err != nil {
return
}
parts := strings.Split(output, ".")
if major, err = strconv.Atoi(parts[0]); err != nil {
return
}
if minor, err = strconv.Atoi(parts[1]); err != nil {
return
}
if patch, err = strconv.Atoi(parts[2]); err != nil {
return
}
return
}
func Detect() (host Host, rev int, err error) {
major, minor, patch, err := kernelVersion()
if err != nil {
return
}
if major < 3 || (major == 3 && minor < 8) {
err = fmt.Errorf("embd: linux kernel versions lower than 3.8 are not supported. you have %v.%v.%v", major, minor, patch)
return
}
node, err := nodeName()
if err != nil {
return
}
switch node {
case "raspberrypi":
host = RPi
case "beaglebone":
host = BBB
default:
err = fmt.Errorf("embd: your host %q is not supported at this moment. please request support at https://github.com/kidoman/embd/issues", node)
}
return
}

View file

@ -0,0 +1,114 @@
package gpio
import (
"fmt"
"os"
"path"
"github.com/kidoman/embd/gpio"
)
type digitalPin struct {
n int
dir *os.File
val *os.File
activeLow *os.File
edge *os.File
}
func newDigitalPin(n int) (p *digitalPin, err error) {
p = &digitalPin{n: n}
err = p.init()
return
}
func (p *digitalPin) init() (err error) {
if p.dir, err = p.directionFile(); err != nil {
return
}
if p.val, err = p.valueFile(); err != nil {
return
}
if p.activeLow, err = p.activeLowFile(); err != nil {
return
}
return
}
func (p *digitalPin) basePath() string {
return fmt.Sprintf("/sys/class/gpio/gpio%v", p.n)
}
func (p *digitalPin) openFile(path string) (*os.File, error) {
return os.OpenFile(path, os.O_RDWR, os.ModeExclusive)
}
func (p *digitalPin) directionFile() (*os.File, error) {
return p.openFile(path.Join(p.basePath(), "direction"))
}
func (p *digitalPin) valueFile() (*os.File, error) {
return p.openFile(path.Join(p.basePath(), "value"))
}
func (p *digitalPin) activeLowFile() (*os.File, error) {
return p.openFile(path.Join(p.basePath(), "active_low"))
}
func (p *digitalPin) SetDir(dir gpio.Direction) (err error) {
str := "in"
if dir == gpio.Out {
str = "out"
}
_, err = p.dir.WriteString(str)
return
}
func (p *digitalPin) Read() (val int, err error) {
buf := make([]byte, 1)
if _, err = p.val.Read(buf); err != nil {
return
}
val = 0
if buf[0] == '1' {
val = 1
}
return
}
func (p *digitalPin) Write(val int) (err error) {
str := "0"
if val == gpio.High {
str = "1"
}
_, err = p.val.WriteString(str)
return
}
func (p *digitalPin) ActiveLow(b bool) (err error) {
str := "0"
if b {
str = "1"
}
_, err = p.activeLow.WriteString(str)
return
}
func (p *digitalPin) Close() error {
if err := p.dir.Close(); err != nil {
return err
}
if err := p.val.Close(); err != nil {
return err
}
if err := p.activeLow.Close(); err != nil {
return err
}
if err := p.edge.Close(); err != nil {
return err
}
return nil
}

View file

@ -0,0 +1,149 @@
package gpio
import (
"fmt"
"os"
"strconv"
"github.com/golang/glog"
"github.com/kidoman/embd/gpio"
)
const (
Normal int = 1 << iota
I2C
UART
SPI
)
type PinDesc struct {
N int
IDs []string
Caps int
}
type PinMap []*PinDesc
func (m PinMap) Lookup(k interface{}) (*PinDesc, bool) {
switch key := k.(type) {
case int:
for i := range m {
if m[i].N == key {
return m[i], true
}
}
case string:
for i := range m {
for j := range m[i].IDs {
if m[i].IDs[j] == key {
return m[i], true
}
}
}
}
return nil, false
}
type GPIO struct {
exporter, unexporter *os.File
initialized bool
pinMap PinMap
initializedPins map[int]*digitalPin
}
func New(pinMap PinMap) *GPIO {
return &GPIO{
pinMap: pinMap,
initializedPins: map[int]*digitalPin{},
}
}
func (io *GPIO) init() (err error) {
if io.initialized {
return
}
if io.exporter, err = os.OpenFile("/sys/class/gpio/export", os.O_WRONLY, os.ModeExclusive); err != nil {
return
}
if io.unexporter, err = os.OpenFile("/sys/class/gpio/unexport", os.O_WRONLY, os.ModeExclusive); err != nil {
return
}
io.initialized = true
return
}
func (io *GPIO) lookupKey(key interface{}) (*PinDesc, bool) {
return io.pinMap.Lookup(key)
}
func (io *GPIO) export(n int) (err error) {
_, err = io.exporter.WriteString(strconv.Itoa(n))
return
}
func (io *GPIO) unexport(n int) (err error) {
_, err = io.unexporter.WriteString(strconv.Itoa(n))
return
}
func (io *GPIO) digitalPin(key interface{}) (p *digitalPin, err error) {
pd, found := io.lookupKey(key)
if !found {
err = fmt.Errorf("gpio: could not find pin matching %q", key)
return
}
n := pd.N
var ok bool
if p, ok = io.initializedPins[n]; ok {
return
}
if pd.Caps&Normal == 0 {
err = fmt.Errorf("gpio: sorry, pin %q cannot be used for GPIO", key)
return
}
if pd.Caps != Normal {
glog.Infof("gpio: pin %q is not a dedicated GPIO pin. please refer to the system reference manual for more details", key)
}
if err = io.export(n); err != nil {
return
}
if p, err = newDigitalPin(n); err != nil {
io.unexport(n)
return
}
io.initializedPins[n] = p
return
}
func (io *GPIO) DigitalPin(key interface{}) (gpio.DigitalPin, error) {
if err := io.init(); err != nil {
return nil, err
}
return io.digitalPin(key)
}
func (io *GPIO) Close() error {
for n := range io.initializedPins {
io.unexport(n)
}
io.exporter.Close()
io.unexporter.Close()
return nil
}

View file

@ -0,0 +1,278 @@
package i2c
import (
"fmt"
"os"
"reflect"
"sync"
"syscall"
"time"
"unsafe"
)
const (
delay = 20
slaveCmd = 0x0703 // Cmd to set slave address
rdrwCmd = 0x0707 // Cmd to read/write data together
rd = 0x0001
)
type i2c_msg struct {
addr uint16
flags uint16
len uint16
buf uintptr
}
type i2c_rdwr_ioctl_data struct {
msgs uintptr
nmsg uint32
}
type bus struct {
l byte
file *os.File
addr byte
mu sync.Mutex
}
func newBus(l byte) (*bus, error) {
b := &bus{l: l}
var err error
if b.file, err = os.OpenFile(fmt.Sprintf("/dev/i2c-%v", b.l), os.O_RDWR, os.ModeExclusive); err != nil {
return nil, err
}
return b, nil
}
func (b *bus) Close() error {
b.mu.Lock()
defer b.mu.Unlock()
return b.file.Close()
}
func (b *bus) setAddress(addr byte) (err error) {
if addr != b.addr {
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), slaveCmd, uintptr(addr)); errno != 0 {
err = syscall.Errno(errno)
return
}
b.addr = addr
}
return
}
func (b *bus) ReadByte(addr byte) (value byte, err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
bytes := make([]byte, 1)
n, err := b.file.Read(bytes)
if n != 1 {
err = fmt.Errorf("i2c: Unexpected number (%v) of bytes read", n)
}
value = bytes[0]
return
}
func (b *bus) WriteByte(addr, value byte) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
n, err := b.file.Write([]byte{value})
if n != 1 {
err = fmt.Errorf("i2c: Unexpected number (%v) of bytes written in WriteByte", n)
}
return
}
func (b *bus) WriteBytes(addr byte, value []byte) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return err
}
for i := range value {
n, err := b.file.Write([]byte{value[i]})
if n != 1 {
return fmt.Errorf("i2c: Unexpected number (%v) of bytes written in WriteBytes", n)
}
if err != nil {
return err
}
time.Sleep(delay * time.Millisecond)
}
return nil
}
func (b *bus) ReadFromReg(addr, reg byte, value []byte) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&value))
var messages [2]i2c_msg
messages[0].addr = uint16(addr)
messages[0].flags = 0
messages[0].len = 1
messages[0].buf = uintptr(unsafe.Pointer(&reg))
messages[1].addr = uint16(addr)
messages[1].flags = rd
messages[1].len = uint16(len(value))
messages[1].buf = uintptr(unsafe.Pointer(hdrp.Data))
var packets i2c_rdwr_ioctl_data
packets.msgs = uintptr(unsafe.Pointer(&messages))
packets.nmsg = 2
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 {
return syscall.Errno(errno)
}
return nil
}
func (b *bus) ReadByteFromReg(addr, reg byte) (value byte, err error) {
buf := make([]byte, 1)
if err = b.ReadFromReg(addr, reg, buf); err != nil {
return
}
value = buf[0]
return
}
func (b *bus) ReadWordFromReg(addr, reg byte) (value uint16, err error) {
buf := make([]byte, 2)
if err = b.ReadFromReg(addr, reg, buf); err != nil {
return
}
value = uint16((uint16(buf[0]) << 8) | uint16(buf[1]))
return
}
func (b *bus) WriteToReg(addr, reg byte, value []byte) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
outbuf := append([]byte{reg}, value...)
hdrp := (*reflect.SliceHeader)(unsafe.Pointer(&outbuf))
var message i2c_msg
message.addr = uint16(addr)
message.flags = 0
message.len = uint16(len(outbuf))
message.buf = uintptr(unsafe.Pointer(&hdrp.Data))
var packets i2c_rdwr_ioctl_data
packets.msgs = uintptr(unsafe.Pointer(&message))
packets.nmsg = 1
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 {
err = syscall.Errno(errno)
return
}
return
}
func (b *bus) WriteByteToReg(addr, reg, value byte) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
outbuf := [...]byte{
reg,
value,
}
var message i2c_msg
message.addr = uint16(addr)
message.flags = 0
message.len = uint16(len(outbuf))
message.buf = uintptr(unsafe.Pointer(&outbuf))
var packets i2c_rdwr_ioctl_data
packets.msgs = uintptr(unsafe.Pointer(&message))
packets.nmsg = 1
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 {
err = syscall.Errno(errno)
return
}
return
}
func (b *bus) WriteWordToReg(addr, reg byte, value uint16) (err error) {
b.mu.Lock()
defer b.mu.Unlock()
if err = b.setAddress(addr); err != nil {
return
}
outbuf := [...]byte{
reg,
byte(value >> 8),
byte(value),
}
var messages i2c_msg
messages.addr = uint16(addr)
messages.flags = 0
messages.len = uint16(len(outbuf))
messages.buf = uintptr(unsafe.Pointer(&outbuf))
var packets i2c_rdwr_ioctl_data
packets.msgs = uintptr(unsafe.Pointer(&messages))
packets.nmsg = 1
if _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, b.file.Fd(), rdrwCmd, uintptr(unsafe.Pointer(&packets))); errno != 0 {
err = syscall.Errno(errno)
return
}
return
}

View file

@ -0,0 +1,43 @@
// Package i2c enables gophers i2c speaking ability.
package i2c
import (
"sync"
"github.com/kidoman/embd/i2c"
)
type I2C struct {
busMap map[byte]*bus
busMapLock sync.Mutex
}
func New() *I2C {
return &I2C{
busMap: make(map[byte]*bus),
}
}
func (i *I2C) Bus(l byte) i2c.Bus {
i.busMapLock.Lock()
defer i.busMapLock.Unlock()
var b *bus
if b = i.busMap[l]; b == nil {
b = &bus{l: l}
i.busMap[l] = b
}
return b
}
func (i *I2C) Close() error {
for _, b := range i.busMap {
b.Close()
delete(i.busMap, b.l)
}
return nil
}

45
host/rpi/data.go Normal file
View file

@ -0,0 +1,45 @@
package rpi
import (
"github.com/kidoman/embd/host/generic/linux/gpio"
)
var rev1Pins = gpio.PinMap{
&gpio.PinDesc{0, []string{"P1_3", "GPIO_0", "SDA", "I2C0_SDA"}, gpio.Normal | gpio.I2C},
&gpio.PinDesc{1, []string{"P1_5", "GPIO_1", "SCL", "I2C0_SCL"}, gpio.Normal | gpio.I2C},
&gpio.PinDesc{4, []string{"P1_7", "GPIO_4", "GPCLK0"}, gpio.Normal},
&gpio.PinDesc{14, []string{"P1_8", "GPIO_14", "TXD", "UART0_TXD"}, gpio.Normal | gpio.UART},
&gpio.PinDesc{15, []string{"P1_10", "GPIO_15", "RXD", "UART0_RXD"}, gpio.Normal | gpio.UART},
&gpio.PinDesc{17, []string{"P1_11", "GPIO_17"}, gpio.Normal},
&gpio.PinDesc{18, []string{"P1_12", "GPIO_18", "PCM_CLK"}, gpio.Normal},
&gpio.PinDesc{21, []string{"P1_13", "GPIO_21"}, gpio.Normal},
&gpio.PinDesc{22, []string{"P1_15", "GPIO_22"}, gpio.Normal},
&gpio.PinDesc{23, []string{"P1_16", "GPIO_23"}, gpio.Normal},
&gpio.PinDesc{24, []string{"P1_18", "GPIO_24"}, gpio.Normal},
&gpio.PinDesc{10, []string{"P1_19", "GPIO_10", "MOSI", "SPI0_MOSI"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{9, []string{"P1_21", "GPIO_9", "MISO", "SPI0_MISO"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{25, []string{"P1_22", "GPIO_25"}, gpio.Normal},
&gpio.PinDesc{11, []string{"P1_23", "GPIO_11", "SCLK", "SPI0_SCLK"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{8, []string{"P1_24", "GPIO_8", "CE0", "SPI0_CE0_N"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{7, []string{"P1_26", "GPIO_7", "CE1", "SPI0_CE1_N"}, gpio.Normal | gpio.SPI},
}
var rev2Pins = gpio.PinMap{
&gpio.PinDesc{2, []string{"P1_3", "GPIO_2", "SDA", "I2C1_SDA"}, gpio.Normal | gpio.I2C},
&gpio.PinDesc{3, []string{"P1_5", "GPIO_3", "SCL", "I2C1_SCL"}, gpio.Normal | gpio.I2C},
&gpio.PinDesc{4, []string{"P1_7", "GPIO_4", "GPCLK0"}, gpio.Normal},
&gpio.PinDesc{14, []string{"P1_8", "GPIO_14", "TXD", "UART0_TXD"}, gpio.Normal | gpio.UART},
&gpio.PinDesc{15, []string{"P1_10", "GPIO_15", "RXD", "UART0_RXD"}, gpio.Normal | gpio.UART},
&gpio.PinDesc{17, []string{"P1_11", "GPIO_17"}, gpio.Normal},
&gpio.PinDesc{18, []string{"P1_12", "GPIO_18", "PCM_CLK"}, gpio.Normal},
&gpio.PinDesc{27, []string{"P1_13", "GPIO_27"}, gpio.Normal},
&gpio.PinDesc{22, []string{"P1_15", "GPIO_22"}, gpio.Normal},
&gpio.PinDesc{23, []string{"P1_16", "GPIO_23"}, gpio.Normal},
&gpio.PinDesc{24, []string{"P1_18", "GPIO_24"}, gpio.Normal},
&gpio.PinDesc{10, []string{"P1_19", "GPIO_10", "MOSI", "SPI0_MOSI"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{9, []string{"P1_21", "GPIO_9", "MISO", "SPI0_MISO"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{25, []string{"P1_22", "GPIO_25"}, gpio.Normal},
&gpio.PinDesc{11, []string{"P1_23", "GPIO_11", "SCLK", "SPI0_SCLK"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{8, []string{"P1_24", "GPIO_8", "CE0", "SPI0_CE0_N"}, gpio.Normal | gpio.SPI},
&gpio.PinDesc{7, []string{"P1_26", "GPIO_7", "CE1", "SPI0_CE1_N"}, gpio.Normal | gpio.SPI},
}

29
host/rpi/descriptor.go Normal file
View file

@ -0,0 +1,29 @@
package rpi
import (
"github.com/kidoman/embd/gpio"
lgpio "github.com/kidoman/embd/host/generic/linux/gpio"
li2c "github.com/kidoman/embd/host/generic/linux/i2c"
"github.com/kidoman/embd/i2c"
)
type descriptor struct {
rev int
}
func (d *descriptor) GPIO() gpio.GPIO {
var pins = rev1Pins
if d.rev > 1 {
pins = rev2Pins
}
return lgpio.New(pins)
}
func (d *descriptor) I2C() i2c.I2C {
return li2c.New()
}
func Descriptor(rev int) *descriptor {
return &descriptor{rev}
}