Skip to content
This repository has been archived by the owner on Sep 20, 2023. It is now read-only.

Commit

Permalink
i2c: Adds i2c.Addr type and flag.Value interface. (#362)
Browse files Browse the repository at this point in the history
* i2c: Adds i2c.Addr type and flag.Value interface.

Add i2c.Addr
Add i2c.Addr Set()
Add Tests.
  • Loading branch information
NeuralSpaz authored Dec 21, 2018
1 parent e8fdbe0 commit 5bdec8d
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
18 changes: 17 additions & 1 deletion conn/i2c/i2c.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
package i2c

import (
"errors"
"io"
"strconv"

Expand Down Expand Up @@ -109,6 +110,21 @@ func (d *Dev) Duplex() conn.Duplex {
return conn.Half
}

//
// Addr is an I²C slave address.
type Addr uint16

// Set sets the Addr to a value represented by the string s. Values maybe in
// decimal or hexadecimal form. Set implements the flag.Value interface.
func (a *Addr) Set(s string) error {
// Allow for only maximum of 10 bits for i2c addresses.
u, err := strconv.ParseUint(s, 0, 10)
if err != nil {
return errI2CSetError
}
*a = Addr(u)
return nil
}

var errI2CSetError = errors.New("invalid i2c address")

var _ conn.Conn = &Dev{}
24 changes: 24 additions & 0 deletions conn/i2c/i2c_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,27 @@ func (f *fakeBus) SetSpeed(freq physic.Frequency) error {
f.freq = freq
return f.err
}

func TestAddr_Set(t *testing.T) {
tests := []struct {
str string
want Addr
err error
}{
{"0x18", 0x18, nil},
{"24", 24, nil},
{"0x3ff", 0x3ff, nil},
{"0x400", 0, errI2CSetError},
{"-1", 0, errI2CSetError},
}

for _, tt := range tests {
var a Addr
if err := a.Set(tt.str); err != tt.err {
t.Errorf("i2cAddr.Set(%s) error %v", tt.str, err)
}
if tt.err == nil && a != tt.want {
t.Errorf("i2cAddr.Set(%s) expected %d but got %d", tt.str, tt.want, a)
}
}
}

0 comments on commit 5bdec8d

Please sign in to comment.