diff --git a/.golangci.yml b/.golangci.yml index c1b5f1f2e..4466f95f4 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -31,9 +31,10 @@ run: linters: # currently active linters: # - #INFO [lintersdb] Active 35 linters: [asasalint asciicheck bidichk contextcheck decorder depguard durationcheck errcheck exportloopref - # gocheckcompilerdirectives gomoddirectives gomodguard goprintffuncname gosimple govet grouper ineffassign makezero mirror musttag - # nilerr nilnil nolintlint nosprintfhostport prealloc reassign revive staticcheck tagalign tenv testableexamples tparallel typecheck unused wastedassign] + #INFO [lintersdb] Active 42 linters: [asasalint asciicheck bidichk contextcheck decorder depguard dupword durationcheck errcheck exportloopref + # gocheckcompilerdirectives gofmt gofumpt goimports gomoddirectives gomodguard goprintffuncname gosec gosimple govet grouper ineffassign makezero mirror + # misspell musttag nilerr nilnil nolintlint nosprintfhostport prealloc reassign revive staticcheck tagalign tenv testableexamples tparallel unconvert unparam + # unused wastedassign] enable-all: true @@ -60,7 +61,6 @@ linters: - godot # not used (seems to be counting peas) - godox # not used (we have many TODOs, so not useful) - goerr113 # not used (we allow error creation at return statement) - - gofumpt # not used (we use "go fmt" or "gofmt" not gofumpt" - gosmopolitan # not needed (report i18n/l10n anti-patterns) - importas # not needed (there is no alias rule at the moment) - ireturn # not used (we allow return interfaces) @@ -73,23 +73,19 @@ linters: - wrapcheck # not needed (we allow errors from interface methods) - zerologlint # not needed (related to zerolog package) # important to have - - gofmt # important to prevent "format tsunami" ("gofmt -s -w" missed), disabled due to "https://github.com/golangci/golangci-lint-action/issues/535" + - errorlint # useful (reduce bugs), but suppress the "Use `%w` to format errors" check + - forcetypeassert # useful (reduce bugs) - nakedret # very useful together with "nonamedreturns" (reduce bugs) - nonamedreturns # very useful (reduce bugs) - - unconvert # very useful (reduce bugs, simplify code) - - unparam # very useful (reduce bugs, simplify code) # useful for the future - bodyclose # maybe useful (reduce bugs), exclusions for tests needed - containedctx # useful (structs are not for context wrapping) - cyclop # useful with some tweeks (better understandable code), see also gocyclo - dogsled # useful with some tweeks (e.g. exclude tests) - dupl # useful with some tweeks (reduce bugs and lines of code) - - dupword # useful with some tweeks, but not important - errchkjson # useful (reduce bugs) - errname # useful for common style - - errorlint # useful (reduce bugs), but suppress the "Use `%w` to format errors" check - exhaustruct # useful with some exclusions for existing code (e.g. mavlink/common/common.go) - - forcetypeassert # useful (reduce bugs) - funlen # useful with some tweeks (reduce bugs, simplify code, better understandable code) - gci # useful (improve readability) - gochecknoinits # useful (reduce bugs, simplify bug catching) @@ -98,13 +94,10 @@ linters: - gocritic # useful with some exclusions for existing code (e.g. mavlink/common/common.go) - gocyclo # useful with some tweeks (better understandable code) - goheader # useful, if we introduce a common header (e.g. for copyright) - - goimports # useful (common style), but not important - gomnd # useful with some exclusions for existing code (e.g. mavlink.go) - - gosec # useful (security) - interfacebloat # useful with some exclusions at usage of external packages - lll # useful with some exclusions for existing code (e.g. mavlink/common/common.go) - maintidx # useful with some tweeks (better understandable code), maybe use instead "gocyclo", "gocognit" , "cyclop" - - misspell # useful (better understandable code), but not important - nestif # useful (reduce bugs, simplify code, better understandable code) - nlreturn # more common style, but could become annoying - noctx # maybe good (show used context explicit) @@ -141,6 +134,15 @@ linters-settings: - pkg: "github.com/pkg/errors" desc: Should be replaced by standard lib errors package + dupword: + # Keywords for detecting duplicate words. + # If this list is not empty, only the words defined in this list will be detected. + # Default: [] + keywords: + - "the" + - "and" + - "a" + nolintlint: # Enable to require an explanation of nonzero length after each nolint directive. # Default: false diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ae735ac17..ea1f095ed 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -41,7 +41,7 @@ Descriptions for each of these will eventually be provided below. from time to time but they can complicate merges and should be done separately. * Take care to maintain the existing coding style. * `golangci-lint` your code, see [instruction for local installation](https://golangci-lint.run/usage/install/#local-installation) -* `go fmt` your code (with the go version of go.mod) +* `gofumpt` your code (the go version will be automatically obtained from go.mod), see [instructions](https://github.com/mvdan/gofumpt/blob/master/README.md) * Add unit tests for any new or changed functionality. * All pull requests should be "fast forward" * If there are commits after yours use “git rebase -i ” diff --git a/Makefile b/Makefile index 7454c03ba..b83504e45 100644 --- a/Makefile +++ b/Makefile @@ -50,14 +50,14 @@ version_check: echo "go: $${gv}.*, go.mod: $${mv}" ; \ if [ "$${gv}" != "$${mv}" ]; then exit 50; fi ; \ -# Check for bad code style and other issues +# Check for bad code style and other issues (gofumpt and gofmt check is activated for the linter) fmt_check: - gofmt -l -s . golangci-lint run -v -# Fix bad code style (will only be executed, on version match) -fmt_fix: version_check - gofmt -l -s -w . +# Fix bad code style (the go version will be automatically obtained from go.mod) +fmt_fix: + $(MAKE) version_check || true + gofumpt -l -w . examples: $(EXAMPLES) diff --git a/adaptor.go b/adaptor.go index ef7d4e42c..596332642 100644 --- a/adaptor.go +++ b/adaptor.go @@ -109,7 +109,6 @@ type PWMPinnerProvider interface { // Data (8 bits): A plain data byte. DataLow and DataHigh represent the low and high byte of a 16 bit word. // Count (8 bits): A data byte containing the length of a block operation. // [..]: Data sent by I2C device, as opposed to data sent by the host adapter. -// type I2cSystemDevicer interface { // ReadByte must be implemented as the sequence: // "S Addr Rd [A] [Data] NA P" diff --git a/api/api.go b/api/api.go index 365d59e8f..448f2f8e2 100644 --- a/api/api.go +++ b/api/api.go @@ -8,6 +8,7 @@ import ( "net/http" "net/http/httptest" "strings" + "time" "github.com/bmizerany/pat" "gobot.io/x/gobot/v2" @@ -35,16 +36,20 @@ func NewAPI(m *gobot.Master) *API { start: func(a *API) { log.Println("Initializing API on " + a.Host + ":" + a.Port + "...") http.Handle("/", a) + server := &http.Server{ + Addr: a.Host + ":" + a.Port, + ReadHeaderTimeout: 30 * time.Second, + } go func() { if a.Cert != "" && a.Key != "" { - if err := http.ListenAndServeTLS(a.Host+":"+a.Port, a.Cert, a.Key, nil); err != nil { + if err := server.ListenAndServeTLS(a.Cert, a.Key); err != nil { panic(err) } } else { log.Println("WARNING: API using insecure connection. " + "We recommend using an SSL certificate with Gobot.") - if err := http.ListenAndServe(a.Host+":"+a.Port, nil); err != nil { + if err := server.ListenAndServe(); err != nil { panic(err) } } @@ -313,7 +318,6 @@ func (a *API) robotConnections(res http.ResponseWriter, req *http.Request) { } else { a.writeJSON(map[string]interface{}{"error": "No Robot found with the name " + req.URL.Query().Get(":robot")}, res) } - } // robotConnection returns connection route handler @@ -369,7 +373,6 @@ func (a *API) executeCommand(f func(map[string]interface{}) interface{}, res http.ResponseWriter, req *http.Request, ) { - body := make(map[string]interface{}) if err := json.NewDecoder(req.Body).Decode(&body); err != nil { panic(err) diff --git a/api/api_test.go b/api/api_test.go index e8f4ffa53..477bb298c 100644 --- a/api/api_test.go +++ b/api/api_test.go @@ -333,7 +333,6 @@ func TestExecuteRobotDeviceCommand(t *testing.T) { _ = json.NewDecoder(response.Body).Decode(&body) assert.Equal(t, "No Device found with the name UnknownDevice1", body.(map[string]interface{})["error"]) - } func TestRobotConnections(t *testing.T) { diff --git a/api/doc.go b/api/doc.go index afc267915..a8e04d3b1 100644 --- a/api/doc.go +++ b/api/doc.go @@ -3,35 +3,35 @@ Package api provides a webserver to interact with your Gobot program over the ne Example: - package main + package main - import ( - "fmt" + import ( + "fmt" - "gobot.io/x/gobot/v2" - "gobot.io/x/gobot/v2/api" - ) + "gobot.io/x/gobot/v2" + "gobot.io/x/gobot/v2/api" + ) - func main() { - gbot := gobot.NewMaster() + func main() { + gbot := gobot.NewMaster() - // Starts the API server on default port 3000 - api.NewAPI(gbot).Start() + // Starts the API server on default port 3000 + api.NewAPI(gbot).Start() - // Accessible via http://localhost:3000/api/commands/say_hello - gbot.AddCommand("say_hello", func(params map[string]interface{}) interface{} { - return "Master says hello!" - }) + // Accessible via http://localhost:3000/api/commands/say_hello + gbot.AddCommand("say_hello", func(params map[string]interface{}) interface{} { + return "Master says hello!" + }) - hello := gbot.AddRobot(gobot.NewRobot("Eve")) + hello := gbot.AddRobot(gobot.NewRobot("Eve")) - // Accessible via http://localhost:3000/api/robots/Eve/commands/say_hello - hello.AddCommand("say_hello", func(params map[string]interface{}) interface{} { - return fmt.Sprintf("%v says hello!", hello.Name) - }) + // Accessible via http://localhost:3000/api/robots/Eve/commands/say_hello + hello.AddCommand("say_hello", func(params map[string]interface{}) interface{} { + return fmt.Sprintf("%v says hello!", hello.Name) + }) - gbot.Start() - } + gbot.Start() + } It follows Common Protocol for Programming Physical Input and Output (CPPP-IO) spec: https://gobot.io/x/cppp-io diff --git a/api/helpers_test.go b/api/helpers_test.go index 0a3336870..7e77d10f6 100644 --- a/api/helpers_test.go +++ b/api/helpers_test.go @@ -64,8 +64,10 @@ type testAdaptor struct { port string } -var testAdaptorConnect = func() (err error) { return } -var testAdaptorFinalize = func() (err error) { return } +var ( + testAdaptorConnect = func() (err error) { return } + testAdaptorFinalize = func() (err error) { return } +) func (t *testAdaptor) Finalize() (err error) { return testAdaptorFinalize() } func (t *testAdaptor) Connect() (err error) { return testAdaptorConnect() } diff --git a/api/robeaux/robeaux.go b/api/robeaux/robeaux.go index 59b5242b1..aeff2c806 100644 --- a/api/robeaux/robeaux.go +++ b/api/robeaux/robeaux.go @@ -86,18 +86,23 @@ type bindataFileInfo struct { func (fi bindataFileInfo) Name() string { return fi.name } + func (fi bindataFileInfo) Size() int64 { return fi.size } + func (fi bindataFileInfo) Mode() os.FileMode { return fi.mode } + func (fi bindataFileInfo) ModTime() time.Time { return fi.modTime } + func (fi bindataFileInfo) IsDir() bool { return false } + func (fi bindataFileInfo) Sys() interface{} { return nil } @@ -916,11 +921,13 @@ var _bindata = map[string]func() (*asset, error){ // directory embedded in the file by go-bindata. // For example if you run go-bindata on data/... and data contains the // following hierarchy: -// data/ -// foo.txt -// img/ -// a.png -// b.png +// +// data/ +// foo.txt +// img/ +// a.png +// b.png +// // then AssetDir("data") would return []string{"foo.txt", "img"} // AssetDir("data/img") would return []string{"a.png", "b.png"} // AssetDir("foo.txt") and AssetDir("notexist") would return an error @@ -1009,7 +1016,7 @@ func RestoreAsset(dir, name string) error { if err != nil { return err } - err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0755)) + err = os.MkdirAll(_filePath(dir, filepath.Dir(name)), os.FileMode(0o755)) if err != nil { return err } diff --git a/doc.go b/doc.go index 0d3f92674..ada79dd42 100644 --- a/doc.go +++ b/doc.go @@ -9,124 +9,124 @@ It provides a simple, yet powerful way to create solutions that incorporate mult Here is a "Classic Gobot" program that blinks an LED using an Arduino: - package main + package main - import ( - "time" + import ( + "time" - "gobot.io/x/gobot/v2" - "gobot.io/x/gobot/v2/drivers/gpio" - "gobot.io/x/gobot/v2/platforms/firmata" - ) + "gobot.io/x/gobot/v2" + "gobot.io/x/gobot/v2/drivers/gpio" + "gobot.io/x/gobot/v2/platforms/firmata" + ) - func main() { - firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") - led := gpio.NewLedDriver(firmataAdaptor, "13") + func main() { + firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0") + led := gpio.NewLedDriver(firmataAdaptor, "13") - work := func() { - gobot.Every(1*time.Second, func() { - led.Toggle() - }) - } + work := func() { + gobot.Every(1*time.Second, func() { + led.Toggle() + }) + } - robot := gobot.NewRobot("bot", - []gobot.Connection{firmataAdaptor}, - []gobot.Device{led}, - work, - ) + robot := gobot.NewRobot("bot", + []gobot.Connection{firmataAdaptor}, + []gobot.Device{led}, + work, + ) - robot.Start() - } + robot.Start() + } # Metal Gobot You can also use Metal Gobot and pick and choose from the various Gobot packages to control hardware with nothing but pure idiomatic Golang code. For example: - package main + package main - import ( - "gobot.io/x/gobot/v2/drivers/gpio" - "gobot.io/x/gobot/v2/platforms/intel-iot/edison" - "time" - ) + import ( + "gobot.io/x/gobot/v2/drivers/gpio" + "gobot.io/x/gobot/v2/platforms/intel-iot/edison" + "time" + ) - func main() { - e := edison.NewAdaptor() - e.Connect() + func main() { + e := edison.NewAdaptor() + e.Connect() - led := gpio.NewLedDriver(e, "13") - led.Start() + led := gpio.NewLedDriver(e, "13") + led.Start() - for { - led.Toggle() - time.Sleep(1000 * time.Millisecond) - } - } + for { + led.Toggle() + time.Sleep(1000 * time.Millisecond) + } + } # Master Gobot Finally, you can use Master Gobot to add the complete Gobot API or control swarms of Robots: - package main - - import ( - "fmt" - "time" - - "gobot.io/x/gobot/v2" - "gobot.io/x/gobot/v2/api" - "gobot.io/x/gobot/v2/platforms/sphero" - ) - - func NewSwarmBot(port string) *gobot.Robot { - spheroAdaptor := sphero.NewAdaptor(port) - spheroDriver := sphero.NewSpheroDriver(spheroAdaptor) - spheroDriver.SetName("Sphero" + port) - - work := func() { - spheroDriver.Stop() - - spheroDriver.On(sphero.Collision, func(data interface{}) { - fmt.Println("Collision Detected!") - }) - - gobot.Every(1*time.Second, func() { - spheroDriver.Roll(100, uint16(gobot.Rand(360))) - }) - gobot.Every(3*time.Second, func() { - spheroDriver.SetRGB(uint8(gobot.Rand(255)), - uint8(gobot.Rand(255)), - uint8(gobot.Rand(255)), - ) - }) - } - - robot := gobot.NewRobot("sphero", - []gobot.Connection{spheroAdaptor}, - []gobot.Device{spheroDriver}, - work, - ) - - return robot - } - - func main() { - master := gobot.NewMaster() - api.NewAPI(master).Start() - - spheros := []string{ - "/dev/rfcomm0", - "/dev/rfcomm1", - "/dev/rfcomm2", - "/dev/rfcomm3", - } - - for _, port := range spheros { - master.AddRobot(NewSwarmBot(port)) - } - - master.Start() - } + package main + + import ( + "fmt" + "time" + + "gobot.io/x/gobot/v2" + "gobot.io/x/gobot/v2/api" + "gobot.io/x/gobot/v2/platforms/sphero" + ) + + func NewSwarmBot(port string) *gobot.Robot { + spheroAdaptor := sphero.NewAdaptor(port) + spheroDriver := sphero.NewSpheroDriver(spheroAdaptor) + spheroDriver.SetName("Sphero" + port) + + work := func() { + spheroDriver.Stop() + + spheroDriver.On(sphero.Collision, func(data interface{}) { + fmt.Println("Collision Detected!") + }) + + gobot.Every(1*time.Second, func() { + spheroDriver.Roll(100, uint16(gobot.Rand(360))) + }) + gobot.Every(3*time.Second, func() { + spheroDriver.SetRGB(uint8(gobot.Rand(255)), + uint8(gobot.Rand(255)), + uint8(gobot.Rand(255)), + ) + }) + } + + robot := gobot.NewRobot("sphero", + []gobot.Connection{spheroAdaptor}, + []gobot.Device{spheroDriver}, + work, + ) + + return robot + } + + func main() { + master := gobot.NewMaster() + api.NewAPI(master).Start() + + spheros := []string{ + "/dev/rfcomm0", + "/dev/rfcomm1", + "/dev/rfcomm2", + "/dev/rfcomm3", + } + + for _, port := range spheros { + master.AddRobot(NewSwarmBot(port)) + } + + master.Start() + } Copyright (c) 2013-2018 The Hybrid Group. Licensed under the Apache 2.0 license. */ diff --git a/drivers/aio/aio.go b/drivers/aio/aio.go index 4b8bd9638..a8d5b339a 100644 --- a/drivers/aio/aio.go +++ b/drivers/aio/aio.go @@ -4,11 +4,9 @@ import ( "errors" ) -var ( - // ErrAnalogReadUnsupported is error resulting when a driver attempts to use - // hardware capabilities which a connection does not support - ErrAnalogReadUnsupported = errors.New("AnalogRead is not supported by this platform") -) +// ErrAnalogReadUnsupported is error resulting when a driver attempts to use +// hardware capabilities which a connection does not support +var ErrAnalogReadUnsupported = errors.New("AnalogRead is not supported by this platform") const ( // Error event @@ -23,12 +21,12 @@ const ( // AnalogReader interface represents an Adaptor which has AnalogRead capabilities type AnalogReader interface { - //gobot.Adaptor + // gobot.Adaptor AnalogRead(pin string) (val int, err error) } // AnalogWriter interface represents an Adaptor which has AnalogWrite capabilities type AnalogWriter interface { - //gobot.Adaptor + // gobot.Adaptor AnalogWrite(pin string, val int) (err error) } diff --git a/drivers/aio/analog_actuator_driver_test.go b/drivers/aio/analog_actuator_driver_test.go index ced579586..3508fe720 100644 --- a/drivers/aio/analog_actuator_driver_test.go +++ b/drivers/aio/analog_actuator_driver_test.go @@ -45,7 +45,7 @@ func TestAnalogActuatorDriverWithScaler(t *testing.T) { } func TestAnalogActuatorDriverLinearScaler(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { fromMin float64 fromMax float64 input float64 diff --git a/drivers/aio/analog_sensor_driver.go b/drivers/aio/analog_sensor_driver.go index fb8aaf2ab..450265955 100644 --- a/drivers/aio/analog_sensor_driver.go +++ b/drivers/aio/analog_sensor_driver.go @@ -77,8 +77,8 @@ func (a *AnalogSensorDriver) Start() (err error) { // cyclic reading deactivated return } - var oldRawValue = 0 - var oldValue = 0.0 + oldRawValue := 0 + oldValue := 0.0 go func() { timer := time.NewTimer(a.interval) timer.Stop() diff --git a/drivers/aio/analog_sensor_driver_test.go b/drivers/aio/analog_sensor_driver_test.go index 12e94dc2f..1b6a048a7 100644 --- a/drivers/aio/analog_sensor_driver_test.go +++ b/drivers/aio/analog_sensor_driver_test.go @@ -56,7 +56,7 @@ func TestAnalogSensorDriver(t *testing.T) { func TestAnalogSensorDriverWithLinearScaler(t *testing.T) { // the input scales per default from 0...255 - var tests = map[string]struct { + tests := map[string]struct { toMin float64 toMax float64 input int diff --git a/drivers/aio/grove_temperature_sensor_driver.go b/drivers/aio/grove_temperature_sensor_driver.go index 2998b9811..78304a110 100644 --- a/drivers/aio/grove_temperature_sensor_driver.go +++ b/drivers/aio/grove_temperature_sensor_driver.go @@ -27,8 +27,8 @@ type GroveTemperatureSensorDriver struct { // "ReadValue" - See AnalogDriverSensor.ReadValue func NewGroveTemperatureSensorDriver(a AnalogReader, pin string, v ...time.Duration) *GroveTemperatureSensorDriver { t := NewTemperatureSensorDriver(a, pin, v...) - ntc := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3975} //Ohm, R25=10k - t.SetNtcScaler(1023, 10000, false, ntc) //Ohm, reference value: 1023, series R: 10k + ntc := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3975} // Ohm, R25=10k + t.SetNtcScaler(1023, 10000, false, ntc) // Ohm, reference value: 1023, series R: 10k d := &GroveTemperatureSensorDriver{ TemperatureSensorDriver: t, diff --git a/drivers/aio/grove_temperature_sensor_driver_test.go b/drivers/aio/grove_temperature_sensor_driver_test.go index 2fe8f75e3..c7a3a3070 100644 --- a/drivers/aio/grove_temperature_sensor_driver_test.go +++ b/drivers/aio/grove_temperature_sensor_driver_test.go @@ -21,7 +21,7 @@ func TestGroveTemperatureSensorDriver(t *testing.T) { } func TestGroveTemperatureSensorDriverScaling(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { input int want float64 }{ diff --git a/drivers/aio/temperature_sensor_driver.go b/drivers/aio/temperature_sensor_driver.go index f410e5c31..55c5484c0 100644 --- a/drivers/aio/temperature_sensor_driver.go +++ b/drivers/aio/temperature_sensor_driver.go @@ -126,7 +126,7 @@ func (n *TemperatureSensorNtcConf) getTemp(rntc float64) float64 { func (n *TemperatureSensorNtcConf) initialize() { n.t0 = float64(n.TC0) + kelvinOffset if n.B <= 0 { - //B=[ln(R0)-ln(R1)]/(1/T0-1/T1) + // B=[ln(R0)-ln(R1)]/(1/T0-1/T1) T1 := float64(n.TC1) + kelvinOffset n.B = (1/n.t0 - 1/T1) n.B = (math.Log(n.R0) - math.Log(n.R1)) / n.B // 2000K...5000K diff --git a/drivers/aio/temperature_sensor_driver_test.go b/drivers/aio/temperature_sensor_driver_test.go index 0610364e1..1ae246e8f 100644 --- a/drivers/aio/temperature_sensor_driver_test.go +++ b/drivers/aio/temperature_sensor_driver_test.go @@ -19,7 +19,7 @@ func TestTemperatureSensorDriver(t *testing.T) { } func TestTemperatureSensorDriverNtcScaling(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { input int want float64 }{ @@ -36,8 +36,8 @@ func TestTemperatureSensorDriverNtcScaling(t *testing.T) { } a := newAioTestAdaptor() d := NewTemperatureSensorDriver(a, "4") - ntc1 := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3950} //Ohm, R25=10k, B=3950 - d.SetNtcScaler(255, 1000, true, ntc1) //Ohm, reference value: 3300, series R: 1k + ntc1 := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3950} // Ohm, R25=10k, B=3950 + d.SetNtcScaler(255, 1000, true, ntc1) // Ohm, reference value: 3300, series R: 1k for name, tt := range tests { t.Run(name, func(t *testing.T) { // arrange @@ -55,7 +55,7 @@ func TestTemperatureSensorDriverNtcScaling(t *testing.T) { } func TestTemperatureSensorDriverLinearScaling(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { input int want float64 }{ @@ -93,8 +93,8 @@ func TestTempSensorPublishesTemperatureInCelsius(t *testing.T) { sem := make(chan bool, 1) a := newAioTestAdaptor() d := NewTemperatureSensorDriver(a, "1") - ntc := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3975} //Ohm, R25=10k - d.SetNtcScaler(1023, 10000, false, ntc) //Ohm, reference value: 1023, series R: 10k + ntc := TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3975} // Ohm, R25=10k + d.SetNtcScaler(1023, 10000, false, ntc) // Ohm, reference value: 1023, series R: 10k a.TestAdaptorAnalogRead(func() (val int, err error) { val = 585 @@ -168,7 +168,7 @@ func TestTempDriverSetName(t *testing.T) { } func TestTempDriver_initialize(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { input TemperatureSensorNtcConf want TemperatureSensorNtcConf }{ diff --git a/drivers/common/mfrc522/mfrc522_pcd.go b/drivers/common/mfrc522/mfrc522_pcd.go index 34ace2574..a6cad3495 100644 --- a/drivers/common/mfrc522/mfrc522_pcd.go +++ b/drivers/common/mfrc522/mfrc522_pcd.go @@ -20,8 +20,10 @@ type busConnection interface { WriteByteData(reg byte, data byte) error } -var versions = map[uint8]string{0x12: "Counterfeit", 0x88: "FM17522", 0x89: "FM17522E", - 0x90: "MFRC522 0.0", 0x91: "MFRC522 1.0", 0x92: "MFRC522 2.0", 0xB2: "FM17522 1"} +var versions = map[uint8]string{ + 0x12: "Counterfeit", 0x88: "FM17522", 0x89: "FM17522E", + 0x90: "MFRC522 0.0", 0x91: "MFRC522 1.0", 0x92: "MFRC522 2.0", 0xB2: "FM17522 1", +} // MFRC522Common is the Gobot Driver for MFRC522 RFID. // datasheet: @@ -155,7 +157,8 @@ func (d *MFRC522Common) stopCrypto1() error { } func (d *MFRC522Common) communicateWithPICC(command uint8, sendData []byte, backData []byte, txLastBits uint8, - checkCRC bool) error { + checkCRC bool, +) error { irqEn := 0x00 waitIRq := uint8(0x00) switch command { diff --git a/drivers/common/mfrc522/mfrc522_pcd_register.go b/drivers/common/mfrc522/mfrc522_pcd_register.go index 416f6ff3e..042e145aa 100644 --- a/drivers/common/mfrc522/mfrc522_pcd_register.go +++ b/drivers/common/mfrc522/mfrc522_pcd_register.go @@ -12,8 +12,8 @@ const ( commandRegCalcCRC = 0x03 // activates the CRC coprocessor or performs a self-test commandRegTransmit = 0x04 // transmits data from the FIFO buffer // 0x05, 0x06 not used - //commandRegNoCmdChange = 0x07 // no command change, can be used to modify the Command register bits without - //commandRegReceive = 0x08 // activates the receiver circuits + // commandRegNoCmdChange = 0x07 // no command change, can be used to modify the Command register bits without + // commandRegReceive = 0x08 // activates the receiver circuits // 0x09..0x0B not used commandRegTransceive = 0x0C // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission // 0x0D reserved @@ -57,10 +57,10 @@ const ( comIrqRegErrIRq1anyBit = 0x02 // bit 1: error bit in the Error register is set, if 1 // Status1 register’s LoAlert bit is set in opposition to the LoAlert bit, the LoAlertIRq bit stores this event and // can only be reset as indicated by the Set1 bit in this register - //comIrqRegLoAlertIRqBit = 0x04 // bit 2: if 1, see above + // comIrqRegLoAlertIRqBit = 0x04 // bit 2: if 1, see above // the Status1 register’s HiAlert bit is set in opposition to the HiAlert bit, the HiAlertIRq bit stores this event // and can only be reset as indicated by the Set1 bit in this register - //comIrqRegHiAlertIRqBit = 0x08 // bit 3: if 1, see above + // comIrqRegHiAlertIRqBit = 0x08 // bit 3: if 1, see above // If a command terminates, for example, when the Command register changes its value from any command to Idle command. // If an unknown command is started, the Command register Command[3:0] value changes to the idle state and the // IdleIRq bit is set. The microcontroller starting the Idle command does not set the IdleIRq bit. @@ -71,28 +71,28 @@ const ( comIrqRegTxIRqBit = 0x40 // bit 6: set to 1, immediately after the last bit of the transmitted data was sent out // 1: indicates that the marked bits in the register are set // 0: indicates that the marked bits in the register are cleared - //comIrqRegSet1Bit = 0x80 // bit 7: see above + // comIrqRegSet1Bit = 0x80 // bit 7: see above ) const ( regDivIrq = 0x05 // diverse interrupt request bits // ------------ values -------------------- - //divIrqRegReset = 0x00 // see table 31 of data sheet - //divIrqRegReserved01 = 0x03 + // divIrqRegReset = 0x00 // see table 31 of data sheet + // divIrqRegReserved01 = 0x03 divIrqRegCRCIRqBit = 0x04 // bit 2: the CalcCRC command is active and all data is processed - //divIrqRegReservedBit3 = 0x08 + // divIrqRegReservedBit3 = 0x08 // this interrupt is set when either a rising or falling signal edge is detected - //divIrqRegMfinActIRqBit = 0x10 // bit 4: MFIN is active; see above - //divIrqRegReserved56 = 0x60 + // divIrqRegMfinActIRqBit = 0x10 // bit 4: MFIN is active; see above + // divIrqRegReserved56 = 0x60 // 1: indicates that the marked bits in the register are set // 0: indicates that the marked bits in the register are cleared - //divIrqRegSet2Bit = 0x80 // bit 7: see above + // divIrqRegSet2Bit = 0x80 // bit 7: see above ) const ( regError = 0x06 // error bits showing the error status of the last command executed // ------------ values -------------------- - //errorRegReset = 0x00 // see table 33 of data sheet + // errorRegReset = 0x00 // see table 33 of data sheet // set to logic 1 if the SOF is incorrect automatically cleared during receiver start-up phase bit is only valid for // 106 kBd; during the MFAuthent command, the ProtocolErr bit is set to logic 1 if the number of bytes received in one // data stream is incorrect @@ -105,10 +105,10 @@ const ( // cleared automatically at receiver start-up phase; only valid during the bitwise anticollision at 106 kBd; always // set to logic 0 during communication protocols at 212 kBd, 424 kBd and 848 kBd errorRegCollErrBit = 0x08 // bit 3: a bit-collision is detected, see above - //the host or a MFRC522’s internal state machine (e.g. receiver) tries to write data to the FIFO buffer even though + // the host or a MFRC522’s internal state machine (e.g. receiver) tries to write data to the FIFO buffer even though // it is already full errorRegBufferOvflBit = 0x10 // bit 4: FIFO is full, see above - //errorRegReservedBit5 = 0x20 + // errorRegReservedBit5 = 0x20 // the antenna drivers are automatically switched off errorRegTempErrBit = 0x40 // bit 6: internal temperature sensor detects overheating, see above // data is written into the FIFO buffer by the host during the MFAuthent command or if data is written into the FIFO @@ -125,25 +125,25 @@ const ( const ( regStatus2 = 0x08 // receiver and transmitter status bits // ------------ values -------------------- - //status2RegReset = 0x00 // see table 37 of data sheet + // status2RegReset = 0x00 // see table 37 of data sheet // bit 0..2 shows the state of the transmitter and receiver state machines - //status2RegModemStateIdle = 0x00 // idle - //status2RegModemStateWait = 0x01 // wait for the BitFraming register’s StartSend bit + // status2RegModemStateIdle = 0x00 // idle + // status2RegModemStateWait = 0x01 // wait for the BitFraming register’s StartSend bit // the minimum time for TxWait is defined by the TxWait register - //status2RegModemStateTxWait = 0x02 // wait until RF field is present if the TMode register’s TxWaitRF bit is set to logic 1 - //status2RegModemStateTransmitting = 0x03 + // status2RegModemStateTxWait = 0x02 // wait until RF field is present if the TMode register’s TxWaitRF bit is set to logic 1 + // status2RegModemStateTransmitting = 0x03 // the minimum time for RxWait is defined by the RxWait register - //status2RegModemStateRxWait = 0x04 // wait until RF field is present if the TMode register’s TxWaitRF bit is set to logic 1 - //status2RegModemStateWaitForData = 0x05 - //status2RegModemStateReceiving = 0x06 + // status2RegModemStateRxWait = 0x04 // wait until RF field is present if the TMode register’s TxWaitRF bit is set to logic 1 + // status2RegModemStateWaitForData = 0x05 + // status2RegModemStateReceiving = 0x06 // all data communication with the card is encrypted; can only be set to logic 1 by a successful execution of the // MFAuthent command; only valid in Read/Write mode for MIFARE standard cards; this bit is cleared by software status2RegMFCrypto1OnBit = 0x08 // bit 3: indicates that the MIFARE Crypto1 unit is switched on and, see above - //status2RegReserved45 = 0x30 + // status2RegReserved45 = 0x30 // 1: the I2C-bus input filter is set to the High-speed mode independent of the I2C-bus protocol // 0: the I2C-bus input filter is set to the I2C-bus protocol used - //status2RegI2cForceHSBit = 0x40 // I2C-bus input filter settings, see above - //status2RegTempSensClear1Bit = 0x80 // clears the temperature error if the temperature is below the alarm limit of 125C + // status2RegI2cForceHSBit = 0x40 // I2C-bus input filter settings, see above + // status2RegTempSensClear1Bit = 0x80 // clears the temperature error if the temperature is below the alarm limit of 125C ) const ( @@ -153,10 +153,10 @@ const ( const ( regFIFOLevel = 0x0A // number of bytes stored in the FIFO buffer // ------------ values -------------------- - //fifoLevelRegReset = 0x00 // see table 41 of data sheet + // fifoLevelRegReset = 0x00 // see table 41 of data sheet // indicates the number of bytes stored in the FIFO buffer writing to the FIFOData register increments and reading // decrements the FIFOLevel value - //fifoLevelRegValue = 0x7F // bit 0..6: see above + // fifoLevelRegValue = 0x7F // bit 0..6: see above // immediately clears the internal FIFO buffer’s read and write pointer and Error register’s BufferOvfl bit reading // this bit always returns 0 fifoLevelRegFlushBufferBit = 0x80 // bit 7: see above @@ -170,13 +170,13 @@ const ( const ( regControl = 0x0C // miscellaneous control registers // ------------ values -------------------- - //controlRegReset = 0x10 // see table 45 of data sheet + // controlRegReset = 0x10 // see table 45 of data sheet // indicates the number of valid bits in the last received byte // if this value is 000b, the whole byte is valid controlRegRxLastBits = 0x07 // bit 0..2: see above - //controlRegReserved3to5 = 0x38 - //controlRegTStartNowBit = 0x40 // bit 6: timer starts immediately, if 1; reading always returns logic 0 - //controlRegTStopNow = 0x80 // bit 7: timer stops immediately, if 1; reading always returns logic 0 + // controlRegReserved3to5 = 0x38 + // controlRegTStartNowBit = 0x40 // bit 6: timer starts immediately, if 1; reading always returns logic 0 + // controlRegTStopNow = 0x80 // bit 7: timer stops immediately, if 1; reading always returns logic 0 ) const ( @@ -186,7 +186,7 @@ const ( // used for transmission of bit oriented frames: defines the number of bits of the last byte that will be transmitted // 000b indicates that all bits of the last byte will be transmitted bitFramingRegTxLastBits = 0x07 // bit 0..2: see above - //bitFramingRegReservedBit3 = 0x08 + // bitFramingRegReservedBit3 = 0x08 // used for reception of bit-oriented frames: defines the bit position for the first bit received to be stored in the // FIFO buffer, example: // 0: LSB of the received bit is stored at bit position 0, the second received bit is stored at bit position 1 @@ -194,8 +194,8 @@ const ( // 7: LSB of the received bit is stored at bit position 7, the second received bit is stored in the next byte that // follows at bit position 0 // These bits are only to be used for bitwise anticollision at 106 kBd, for all other modes they are set to 0 - //bitFramingRegRxAlign = 0x70 // bit 4..6: see above - //starts the transmission of data, only valid in combination with the Transceive command + // bitFramingRegRxAlign = 0x70 // bit 4..6: see above + // starts the transmission of data, only valid in combination with the Transceive command bitFramingRegStartSendBit = 0x80 // bit 7: see above ) @@ -207,10 +207,10 @@ const ( // 01: indicates a bit-collision in the 1st bit // 08: indicates a bit-collision in the 8th bit // These bits will only be interpreted if the CollPosNotValid bit is set to logic 0 - //collRegCollPos = 0x1F // bit 0..4: read-only, see above + // collRegCollPos = 0x1F // bit 0..4: read-only, see above // no collision detected or the position of the collision is out of the range of CollPos[4:0], if set to 1 - //collRegCollPosNotValidBit = 0x20 // bit 5: read-only, see above - //collRegReservedBit6 = 0x40 + // collRegCollPosNotValidBit = 0x20 // bit 5: read-only, see above + // collRegReservedBit6 = 0x40 // all received bits will be cleared after a collision only used during bitwise anticollision at 106 kBd, otherwise it // is set to logic 1 collRegValuesAfterCollBit = 0x80 // bit 7: see above @@ -223,7 +223,7 @@ const ( const ( regMode = 0x11 // defines general modes for transmitting and receiving // ------------ values -------------------- - //modeRegReset = 0x3F // see table 55 of data sheet + // modeRegReset = 0x3F // see table 55 of data sheet // bit 0..1: defines the preset value for the CRC coprocessor for the CalcCRC command; Remark: during any // communication, the preset values are selected automatically according to the definition of bits in the rxModeReg // and TxMode registers @@ -231,16 +231,16 @@ const ( modeRegCRCPreset6363 = 0x01 // 0x6363 modeRegCRCPresetA671 = 0x10 // 0xA671 modeRegCRCPresetFFFF = 0x11 // 0xFFFF - //modeRegReservedBit2 = 0x04 + // modeRegReservedBit2 = 0x04 // defines the polarity of pin MFIN; Remark: the internal envelope signal is encoded active LOW, changing this bit // generates a MFinActIRq event modeRegPolMFinBit = 0x08 // bit 3: polarity of pin MFIN is active HIGH, is set to 1 - //modeRegReservedBit4 = 0x10 + // modeRegReservedBit4 = 0x10 modeRegTxWaitRFBit = 0x20 // bit 5: transmitter can only be started if an RF field is generated, if set to 1 - //modeRegReservedBit6 = 0x40 + // modeRegReservedBit6 = 0x40 // CRC coprocessor calculates the CRC with MSB first 0 in the CRCResult register the values for the CRCResultMSB[7:0] // bits and the CRCResultLSB[7:0] bits are bit reversed; Remark: during RF communication this bit is ignored - //modeRegMSBFirstBit = 0x80 // bit 7: see above, if set to 1 + // modeRegMSBFirstBit = 0x80 // bit 7: see above, if set to 1 ) const ( @@ -248,8 +248,8 @@ const ( regRxMode = 0x13 // defines reception data rate and framing // ------------ values -------------------- rxtxModeRegReset = 0x00 - //txModeRegReserved = 0x07 // bit 0..2 reserved for TX - //rxModeRegReserved = 0x03 // bit 0,1 reserved for RX + // txModeRegReserved = 0x07 // bit 0..2 reserved for TX + // rxModeRegReserved = 0x03 // bit 0,1 reserved for RX // 0: receiver is deactivated after receiving a data frame // 1: able to receive more than one data frame; only valid for data rates above 106 kBd in order to handle the // polling command; after setting this bit the Receive and Transceive commands will not terminate automatically. @@ -260,60 +260,60 @@ const ( // version 1.0 the CRC status is reflected in the signal CRCErr. // rxModeRegRxMultipleBit = 0x04 // an invalid received data stream (less than 4 bits received) will be ignored and the receiver remains active -//rxModeRegRxNoErrBit = 0x08 // bit 3 -//txModeRegInvModBit = 0x08 // bit 3: modulation of transmitted data is inverted, if 1 +// rxModeRegRxNoErrBit = 0x08 // bit 3 +// txModeRegInvModBit = 0x08 // bit 3: modulation of transmitted data is inverted, if 1 // bit 4..6: defines the bit rate during data transmission; the handles transfer speeds up to 848 kBd -//rxtxModeRegSpeed106kBd = 0x00 //106 kBd -//rxtxModeRegSpeed212kBd = 0x10 //212 kBd -//rxtxModeRegSpeed424kBd = 0x20 //424 kBd -//rxtxModeRegSpeed848kBd = 0x30 //848 kBd -//rxtxModeRegSpeedRes1 = 0x40 //reserved -//rxtxModeRegSpeedRes2 = 0x50 //reserved -//rxtxModeRegSpeedRes3 = 0x60 //reserved -//rxtxModeRegSpeedRes4 = 0x70 //reserved +// rxtxModeRegSpeed106kBd = 0x00 //106 kBd +// rxtxModeRegSpeed212kBd = 0x10 //212 kBd +// rxtxModeRegSpeed424kBd = 0x20 //424 kBd +// rxtxModeRegSpeed848kBd = 0x30 //848 kBd +// rxtxModeRegSpeedRes1 = 0x40 //reserved +// rxtxModeRegSpeedRes2 = 0x50 //reserved +// rxtxModeRegSpeedRes3 = 0x60 //reserved +// rxtxModeRegSpeedRes4 = 0x70 //reserved // RX: enables the CRC calculation during reception // TX: enables CRC generation during data transmission -//rxtxModeRegTxCRCEnBit = 0x80 // bit 7: can only be set to logic 0 at 106 kBd +// rxtxModeRegTxCRCEnBit = 0x80 // bit 7: can only be set to logic 0 at 106 kBd ) const ( regTxControl = 0x14 // controls the logical behavior of the antenna driver pins TX1 and TX2 // ------------ values -------------------- - //regtxControlRegReset = 0x80 // see table 61 of data sheet + // regtxControlRegReset = 0x80 // see table 61 of data sheet // signal on pin TX1 delivers the 13.56 MHz energy carrier modulated by the transmission data txControlRegTx1RFEn1outputBit = 0x01 // bit 0: see above // signal on pin TX2 delivers the 13.56 MHz energy carrier modulated by the transmission data txControlRegTx2RFEn1outputBit = 0x02 // bit 1: see above - //txControlRegReservedBit2 = 0x04 + // txControlRegReservedBit2 = 0x04 // signal on pin TX2 continuously delivers the unmodulated 13.56 MHz energy carrier0Tx2CW bit is enabled to modulate // the 13.56 MHz energy carrier - //txControlRegTx2CW1outputBit = 0x08 // bit 3: see above - //txControlRegInvTx1RFOffBit = 0x10 // bit 4: output signal on pin TX1 inverted if driver TX1 is disabled, if 1 - //txControlRegInvTx2RFOffBit = 0x20 // bit 5: output signal on pin TX2 inverted if driver TX2 is disabled, if 1 - //txControlRegInvTx1RFOnBit = 0x40 // bit 6: output signal on pin TX1 inverted if driver TX1 is enabled, if 1 - //txControlRegInvTx2RFOnBit = 0x80 // bit 7: output signal on pin TX2 inverted if driver TX2 is enabled, if 1 + // txControlRegTx2CW1outputBit = 0x08 // bit 3: see above + // txControlRegInvTx1RFOffBit = 0x10 // bit 4: output signal on pin TX1 inverted if driver TX1 is disabled, if 1 + // txControlRegInvTx2RFOffBit = 0x20 // bit 5: output signal on pin TX2 inverted if driver TX2 is disabled, if 1 + // txControlRegInvTx1RFOnBit = 0x40 // bit 6: output signal on pin TX1 inverted if driver TX1 is enabled, if 1 + // txControlRegInvTx2RFOnBit = 0x80 // bit 7: output signal on pin TX2 inverted if driver TX2 is enabled, if 1 ) const ( regTxASK = 0x15 // controls the setting of the transmission modulation // ------------ values -------------------- - //txASKRegReset = 0x00 // see table 63 of data sheet - //txASKRegReserved = 0x3F // bit 0..5 + // txASKRegReset = 0x00 // see table 63 of data sheet + // txASKRegReserved = 0x3F // bit 0..5 txASKRegForce100ASKBit = 0x40 // bit 6: forces a 100 % ASK modulation independent of the ModGsP register - //txASKRegReservedBit7 = 0x80 + // txASKRegReservedBit7 = 0x80 ) const ( - //regTxSel = 0x16 // selects the internal sources for the antenna driver - //regRxSel = 0x17 // selects internal receiver settings - //regRxThreshold = 0x18 // selects thresholds for the bit decoder - //regDemod = 0x19 // defines demodulator settings + // regTxSel = 0x16 // selects the internal sources for the antenna driver + // regRxSel = 0x17 // selects internal receiver settings + // regRxThreshold = 0x18 // selects thresholds for the bit decoder + // regDemod = 0x19 // defines demodulator settings // 0x1A // reserved for future use // 0x1B // reserved for future use - //regMfTx = 0x1C // controls some MIFARE communication transmit parameters - //regMfRx = 0x1D // controls some MIFARE communication receive parameters + // regMfTx = 0x1C // controls some MIFARE communication transmit parameters + // regMfRx = 0x1D // controls some MIFARE communication receive parameters // 0x1E // reserved for future use - //regSerialSpeed = 0x1F // selects the speed of the serial UART interface + // regSerialSpeed = 0x1F // selects the speed of the serial UART interface // Page 2: Configuration // 0x20 // reserved for future use @@ -333,8 +333,8 @@ const ( const ( regRFCfg = 0x26 // configures the receiver gain // ------------ values -------------------- - //rfcCfgRegReset = 0x48 // see table 97 of data sheet - //rfcCfgRegReserved03 = 0x07 + // rfcCfgRegReset = 0x48 // see table 97 of data sheet + // rfcCfgRegReserved03 = 0x07 // bit 4..6: defines the receiver’s signal voltage gain factor rfcCfgRegRxGain18dB = 0x00 rfcCfgRegRxGain23dB = 0x10 @@ -344,22 +344,22 @@ const ( rfcCfgRegRxGain38dB = 0x50 rfcCfgRegRxGain43dB = 0x60 rfcCfgRegRxGain48dB = 0x70 - //rfcCfgRegReserved7 = 0x80 + // rfcCfgRegReserved7 = 0x80 ) const ( // ------------ unused commands -------------------- -//regGsN = 0x27 // selects the conductance of the antenna driver pins TX1 and TX2 for modulation -//regCWGsP = 0x28 // defines the conductance of the p-driver output during periods of no modulation -//regModGsP = 0x29 // defines the conductance of the p-driver output during periods of modulation - +// regGsN = 0x27 // selects the conductance of the antenna driver pins TX1 and TX2 for modulation +// regCWGsP = 0x28 // defines the conductance of the p-driver output during periods of no modulation +// regModGsP = 0x29 // defines the conductance of the p-driver output during periods of modulation ) + const ( regTMode = 0x2A // defines settings for the internal timer regTPrescaler = 0x2B // the lower 8 bits of the TPrescaler value. The 4 high bits are in tModeReg. // ------------ values -------------------- - //tModeRegReset = 0x00 // see table 105 of data sheet - //tPrescalerRegReset = 0x00 // see table 107 of data sheet + // tModeRegReset = 0x00 // see table 105 of data sheet + // tPrescalerRegReset = 0x00 // see table 107 of data sheet // timer starts automatically at the end of the transmission in all communication modes at all speeds; if the // RxMode register’s RxMultiple bit is not set, the timer stops immediately after receiving the 5th bit (1 start // bit, 4 data bits); if the RxMultiple bit is set to logic 1 the timer never stops, in which case the timer can be @@ -368,22 +368,22 @@ const ( // bit 6,5: indicates that the timer is not influenced by the protocol; internal timer is running in // gated mode; Remark: in gated mode, the Status1 register’s TRunning bit is logic 1 when the timer is enabled by // the TMode register’s TGated bits; this bit does not influence the gating signal - //tModeRegTGatedNon = 0x00 // non-gated mode - //tModeRegTGatedMFIN = 0x20 // gated by pin MFIN - //tModeRegTGatedAUX1 = 0x40 // gated by pin AUX1 + // tModeRegTGatedNon = 0x00 // non-gated mode + // tModeRegTGatedMFIN = 0x20 // gated by pin MFIN + // tModeRegTGatedAUX1 = 0x40 // gated by pin AUX1 // 1: timer automatically restarts its count-down from the 16-bit timer reload value instead of counting down to zero // 0: timer decrements to 0 and the ComIrq register’s TimerIRq bit is set to logic 1 - //tModeRegTAutoRestartBit = 0x10 // bit 4, see above + // tModeRegTAutoRestartBit = 0x10 // bit 4, see above // defines the higher 4 bits of the TPrescaler value; The following formula is used to calculate the timer // frequency if the Demod register’s TPrescalEven bit in Demot register’s set to logic 0: // ftimer = 13.56 MHz / (2*TPreScaler+1); TPreScaler = [tPrescalerRegHi:tPrescalerRegLo] // TPrescaler value on 12 bits) (Default TPrescalEven bit is logic 0) // The following formula is used to calculate the timer frequency if the Demod register’s TPrescalEven bit is set // to logic 1: ftimer = 13.56 MHz / (2*TPreScaler+2). - //tModeRegtPrescalerRegValue25us = 0x0A9 // 169 => fRegtimer=40kHz, timer period of 25μs. - //tModeRegtPrescalerRegValue38us = 0x0FF // 255 => fRegtimer=26kHz, timer period of 38μs. - //tModeRegtPrescalerRegValue500us = 0xD3E // 3390 => fRegtimer= 2kHz, timer period of 500us. - //tModeRegtPrescalerRegValue604us = 0xFFF // 4095 => fRegtimer=1.65kHz, timer period of 604us. + // tModeRegtPrescalerRegValue25us = 0x0A9 // 169 => fRegtimer=40kHz, timer period of 25μs. + // tModeRegtPrescalerRegValue38us = 0x0FF // 255 => fRegtimer=26kHz, timer period of 38μs. + // tModeRegtPrescalerRegValue500us = 0xD3E // 3390 => fRegtimer= 2kHz, timer period of 500us. + // tModeRegtPrescalerRegValue604us = 0xFFF // 4095 => fRegtimer=1.65kHz, timer period of 604us. ) const ( @@ -399,8 +399,8 @@ const ( const ( // ------------ unused commands -------------------- - //regTCounterValueH = 0x2E // shows the 16-bit timer value - //regTCounterValueL = 0x2F + // regTCounterValueH = 0x2E // shows the 16-bit timer value + // regTCounterValueL = 0x2F // Page 3: Test Registers // 0x30 // reserved for future use diff --git a/drivers/common/mfrc522/mfrc522_pcd_test.go b/drivers/common/mfrc522/mfrc522_pcd_test.go index bf217a859..045c0e4f4 100644 --- a/drivers/common/mfrc522/mfrc522_pcd_test.go +++ b/drivers/common/mfrc522/mfrc522_pcd_test.go @@ -86,7 +86,7 @@ func Test_getVersion(t *testing.T) { } func Test_switchAntenna(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { target bool simRead byte wantWritten []byte diff --git a/drivers/common/mfrc522/mfrc522_picc.go b/drivers/common/mfrc522/mfrc522_picc.go index 3723181dc..32d2bae2f 100644 --- a/drivers/common/mfrc522/mfrc522_picc.go +++ b/drivers/common/mfrc522/mfrc522_picc.go @@ -36,16 +36,20 @@ const ( piccCommandMFRegTRANSFER = 0xB0 // Writes the contents of the internal data register to a block. // The commands used for MIFARE Ultralight (from http://www.nxp.com/documents/dataRegsheet/MF0ICU1.pdf, Section 8.6) // The piccCommandMFRegREAD and piccCommandMFRegWRITE can also be used for MIFARE Ultralight. - //piccCommandULRegWRITE = 0xA2 // Writes one 4 byte page to the PICC. + // piccCommandULRegWRITE = 0xA2 // Writes one 4 byte page to the PICC. ) const piccReadWriteAuthBlock = uint8(11) -var piccKey = []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} -var piccUserBlockAddresses = []byte{8, 9, 10} +var ( + piccKey = []byte{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF} + piccUserBlockAddresses = []byte{8, 9, 10} +) -var piccCardFromSak = map[uint8]string{0x08: "Classic 1K, Plus 2K-SE-1K(SL1)", 0x18: "Classic 4K, Plus 4K(SL1)", - 0x10: "Plus 2K(SL2)", 0x11: "Plus 4K(SL2)", 0x20: "Plus 2K-SE-1K(SL3), Plus 4K(SL3)"} +var piccCardFromSak = map[uint8]string{ + 0x08: "Classic 1K, Plus 2K-SE-1K(SL1)", 0x18: "Classic 4K, Plus 4K(SL1)", + 0x10: "Plus 2K(SL2)", 0x11: "Plus 4K(SL2)", 0x20: "Plus 2K-SE-1K(SL3), Plus 4K(SL3)", +} // IsCardPresent is used to poll for a card in range. After an successful request, the card is halted. func (d *MFRC522Common) IsCardPresent() error { diff --git a/drivers/gpio/buzzer_driver_test.go b/drivers/gpio/buzzer_driver_test.go index 94af0cc8f..4b16758fd 100644 --- a/drivers/gpio/buzzer_driver_test.go +++ b/drivers/gpio/buzzer_driver_test.go @@ -57,7 +57,6 @@ func TestBuzzerDriverOnError(t *testing.T) { return errors.New("write error") }) - //assert.Errorf(t, d.On(), "write error") assert.Errorf(t, d.On(), "write error") } diff --git a/drivers/gpio/grove_drivers.go b/drivers/gpio/grove_drivers.go index 80f1ab377..017fa7338 100644 --- a/drivers/gpio/grove_drivers.go +++ b/drivers/gpio/grove_drivers.go @@ -12,6 +12,7 @@ type GroveRelayDriver struct { // NewGroveRelayDriver return a new GroveRelayDriver given a DigitalWriter and pin. // // Adds the following API Commands: +// // "Toggle" - See RelayDriver.Toggle // "On" - See RelayDriver.On // "Off" - See RelayDriver.Off @@ -29,6 +30,7 @@ type GroveLedDriver struct { // NewGroveLedDriver return a new GroveLedDriver given a DigitalWriter and pin. // // Adds the following API Commands: +// // "Brightness" - See LedDriver.Brightness // "Toggle" - See LedDriver.Toggle // "On" - See LedDriver.On @@ -62,7 +64,8 @@ type GroveButtonDriver struct { // 10 Milliseconds given a DigitalReader and pin. // // Optionally accepts: -// time.Duration: Interval at which the ButtonDriver is polled for new information +// +// time.Duration: Interval at which the ButtonDriver is polled for new information func NewGroveButtonDriver(a DigitalReader, pin string, v ...time.Duration) *GroveButtonDriver { return &GroveButtonDriver{ ButtonDriver: NewButtonDriver(a, pin, v...), @@ -79,7 +82,8 @@ type GroveTouchDriver struct { // 10 Milliseconds given a DigitalReader and pin. // // Optionally accepts: -// time.Duration: Interval at which the ButtonDriver is polled for new information +// +// time.Duration: Interval at which the ButtonDriver is polled for new information func NewGroveTouchDriver(a DigitalReader, pin string, v ...time.Duration) *GroveTouchDriver { return &GroveTouchDriver{ ButtonDriver: NewButtonDriver(a, pin, v...), @@ -96,7 +100,8 @@ type GroveMagneticSwitchDriver struct { // 10 Milliseconds given a DigitalReader, name and pin. // // Optionally accepts: -// time.Duration: Interval at which the ButtonDriver is polled for new information +// +// time.Duration: Interval at which the ButtonDriver is polled for new information func NewGroveMagneticSwitchDriver(a DigitalReader, pin string, v ...time.Duration) *GroveMagneticSwitchDriver { return &GroveMagneticSwitchDriver{ ButtonDriver: NewButtonDriver(a, pin, v...), diff --git a/drivers/gpio/helpers_test.go b/drivers/gpio/helpers_test.go index 959ba7c65..b7031cab8 100644 --- a/drivers/gpio/helpers_test.go +++ b/drivers/gpio/helpers_test.go @@ -25,21 +25,25 @@ func (t *gpioTestAdaptor) TestAdaptorDigitalWrite(f func(pin string, val byte) ( defer t.mtx.Unlock() t.testAdaptorDigitalWrite = f } + func (t *gpioTestAdaptor) TestAdaptorServoWrite(f func(pin string, val byte) (err error)) { t.mtx.Lock() defer t.mtx.Unlock() t.testAdaptorServoWrite = f } + func (t *gpioTestAdaptor) TestAdaptorPwmWrite(f func(pin string, val byte) (err error)) { t.mtx.Lock() defer t.mtx.Unlock() t.testAdaptorPwmWrite = f } + func (t *gpioTestAdaptor) TestAdaptorAnalogRead(f func(pin string) (val int, err error)) { t.mtx.Lock() defer t.mtx.Unlock() t.testAdaptorAnalogRead = f } + func (t *gpioTestAdaptor) TestAdaptorDigitalRead(f func(pin string) (val int, err error)) { t.mtx.Lock() defer t.mtx.Unlock() @@ -51,21 +55,25 @@ func (t *gpioTestAdaptor) ServoWrite(pin string, val byte) (err error) { defer t.mtx.Unlock() return t.testAdaptorServoWrite(pin, val) } + func (t *gpioTestAdaptor) PwmWrite(pin string, val byte) (err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorPwmWrite(pin, val) } + func (t *gpioTestAdaptor) AnalogRead(pin string) (val int, err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorAnalogRead(pin) } + func (t *gpioTestAdaptor) DigitalRead(pin string) (val int, err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorDigitalRead(pin) } + func (t *gpioTestAdaptor) DigitalWrite(pin string, val byte) (err error) { t.mtx.Lock() defer t.mtx.Unlock() diff --git a/drivers/gpio/led_driver_test.go b/drivers/gpio/led_driver_test.go index 9e02e5a9b..4cbeef303 100644 --- a/drivers/gpio/led_driver_test.go +++ b/drivers/gpio/led_driver_test.go @@ -48,7 +48,6 @@ func TestLedDriver(t *testing.T) { err = d.Command("Brightness")(map[string]interface{}{"level": 100.0}) assert.Errorf(t, err.(error), "pwm error") - } func TestLedDriverStart(t *testing.T) { diff --git a/drivers/gpio/motor_driver_test.go b/drivers/gpio/motor_driver_test.go index b81ad5742..749cba7b8 100644 --- a/drivers/gpio/motor_driver_test.go +++ b/drivers/gpio/motor_driver_test.go @@ -17,8 +17,8 @@ func initTestMotorDriver() *MotorDriver { func TestMotorDriver(t *testing.T) { d := NewMotorDriver(newGpioTestAdaptor(), "1") assert.NotNil(t, d.Connection()) - } + func TestMotorDriverStart(t *testing.T) { d := initTestMotorDriver() assert.Nil(t, d.Start()) diff --git a/drivers/gpio/servo_driver.go b/drivers/gpio/servo_driver.go index 53a560bf8..461b842f7 100644 --- a/drivers/gpio/servo_driver.go +++ b/drivers/gpio/servo_driver.go @@ -43,7 +43,6 @@ func NewServoDriver(a ServoWriter, pin string) *ServoDriver { }) return s - } // Name returns the ServoDrivers name diff --git a/drivers/gpio/stepper_driver.go b/drivers/gpio/stepper_driver.go index 25a3d2c20..1a9469a33 100644 --- a/drivers/gpio/stepper_driver.go +++ b/drivers/gpio/stepper_driver.go @@ -19,21 +19,21 @@ var StepperModes = struct { DualPhaseStepping [][4]byte HalfStepping [][4]byte }{ - //1 cycle = 4 steps with lesser torque + // 1 cycle = 4 steps with lesser torque SinglePhaseStepping: [][4]byte{ {1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}, }, - //1 cycle = 4 steps with higher torque and current + // 1 cycle = 4 steps with higher torque and current DualPhaseStepping: [][4]byte{ {1, 0, 0, 1}, {1, 1, 0, 0}, {0, 1, 1, 0}, {0, 0, 1, 1}, }, - //1 cycle = 8 steps with lesser torque than full stepping + // 1 cycle = 8 steps with lesser torque than full stepping HalfStepping: [][4]byte{ {1, 0, 0, 1}, {1, 0, 0, 0}, @@ -110,7 +110,7 @@ func (s *StepperDriver) Start() error { return nil } // Run continuously runs the stepper func (s *StepperDriver) Run() error { - //halt if already moving + // halt if already moving if s.moving { if err := s.Halt(); err != nil { return err @@ -196,7 +196,7 @@ func (s *StepperDriver) Move(stepsToMove int) error { } if s.moving { - //stop previous motion + // stop previous motion if err := s.Halt(); err != nil { return err } @@ -228,7 +228,7 @@ func (s *StepperDriver) Move(stepsToMove int) error { // getDelayPerStep gives the delay per step func (s *StepperDriver) getDelayPerStep() time.Duration { - //Do not remove *1000 and change duration to time.Millisecond. It has been done for a reason + // Do not remove *1000 and change duration to time.Millisecond. It has been done for a reason return time.Duration(60000*1000/(s.stepsPerRev*s.speed)) * time.Microsecond } @@ -239,7 +239,7 @@ func (s *StepperDriver) GetCurrentStep() int { // GetMaxSpeed gives the max RPM of motor func (s *StepperDriver) GetMaxSpeed() uint { - //considering time for 1 rev as no of steps per rev * 1.5 (min time req between each step) + // considering time for 1 rev as no of steps per rev * 1.5 (min time req between each step) return uint(60000 / (float64(s.stepsPerRev) * 1.5)) } diff --git a/drivers/gpio/tm1638_driver.go b/drivers/gpio/tm1638_driver.go index 4b23bb360..588671433 100644 --- a/drivers/gpio/tm1638_driver.go +++ b/drivers/gpio/tm1638_driver.go @@ -2,7 +2,6 @@ package gpio import ( "math" - "strings" "gobot.io/x/gobot/v2" @@ -62,7 +61,6 @@ func NewTM1638Driver(a gobot.Connection, clockPin string, dataPin string, strobe // Start initializes the tm1638, it uses a SPI-like communication protocol func (t *TM1638Driver) Start() error { - if err := t.pinStrobe.On(); err != nil { return err } diff --git a/drivers/i2c/adafruit1109_driver.go b/drivers/i2c/adafruit1109_driver.go index 7bd4afa7c..feae2530f 100644 --- a/drivers/i2c/adafruit1109_driver.go +++ b/drivers/i2c/adafruit1109_driver.go @@ -79,7 +79,7 @@ func NewAdafruit1109Driver(a Connector, options ...func(Config)) *Adafruit1109Dr D7: d.dataPinD7.String(), } - //rwPin := "B_6" not mapped in HD44780 driver + // rwPin := "B_6" not mapped in HD44780 driver // at test initialization, there seems rows and columns be switched // but inside the driver the row is used as row and col as column rows := 2 diff --git a/drivers/i2c/adafruit1109_driver_test.go b/drivers/i2c/adafruit1109_driver_test.go index f2c901374..ae7cb92de 100644 --- a/drivers/i2c/adafruit1109_driver_test.go +++ b/drivers/i2c/adafruit1109_driver_test.go @@ -91,7 +91,7 @@ func TestAdafruit1109Halt(t *testing.T) { } func TestAdafruit1109DigitalRead(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 wantReg uint8 }{ @@ -138,7 +138,7 @@ func TestAdafruit1109DigitalRead(t *testing.T) { } func TestAdafruit1109SelectButton(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 want uint8 }{ @@ -168,7 +168,7 @@ func TestAdafruit1109SelectButton(t *testing.T) { } func TestAdafruit1109UpButton(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 want uint8 }{ @@ -198,7 +198,7 @@ func TestAdafruit1109UpButton(t *testing.T) { } func TestAdafruit1109DownButton(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 want uint8 }{ @@ -228,7 +228,7 @@ func TestAdafruit1109DownButton(t *testing.T) { } func TestAdafruit1109LeftButton(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 want uint8 }{ @@ -258,7 +258,7 @@ func TestAdafruit1109LeftButton(t *testing.T) { } func TestAdafruit1109RightButton(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { read uint8 want uint8 }{ diff --git a/drivers/i2c/adafruit_driver.go b/drivers/i2c/adafruit_driver.go index 1d534ebfd..3db354005 100644 --- a/drivers/i2c/adafruit_driver.go +++ b/drivers/i2c/adafruit_driver.go @@ -111,12 +111,16 @@ func NewAdafruitMotorHatDriver(conn Connector, options ...func(Config)) *Adafrui switch { case i == 0: dc = append(dc, adaFruitDCMotor{pwmPin: 8, in1Pin: 10, in2Pin: 9}) - st = append(st, adaFruitStepperMotor{pwmPinA: 8, pwmPinB: 13, - ain1: 10, ain2: 9, bin1: 11, bin2: 12, revSteps: 200, secPerStep: 0.1}) + st = append(st, adaFruitStepperMotor{ + pwmPinA: 8, pwmPinB: 13, + ain1: 10, ain2: 9, bin1: 11, bin2: 12, revSteps: 200, secPerStep: 0.1, + }) case i == 1: dc = append(dc, adaFruitDCMotor{pwmPin: 13, in1Pin: 11, in2Pin: 12}) - st = append(st, adaFruitStepperMotor{pwmPinA: 2, pwmPinB: 7, - ain1: 4, ain2: 3, bin1: 5, bin2: 6, revSteps: 200, secPerStep: 0.1}) + st = append(st, adaFruitStepperMotor{ + pwmPinA: 2, pwmPinB: 7, + ain1: 4, ain2: 3, bin1: 5, bin2: 6, revSteps: 200, secPerStep: 0.1, + }) case i == 2: dc = append(dc, adaFruitDCMotor{pwmPin: 2, in1Pin: 4, in2Pin: 3}) case i == 3: @@ -249,10 +253,10 @@ func (a *AdafruitMotorHatDriver) Halt() (err error) { return } func (a *AdafruitMotorHatDriver) setPWM(conn Connection, pin byte, on, off int32) (err error) { // register and values to be written to that register regVals := make(map[int][]byte) - regVals[0] = []byte{byte(_LedZeroOnL + 4*pin), byte(on & 0xff)} - regVals[1] = []byte{byte(_LedZeroOnH + 4*pin), byte(on >> 8)} - regVals[2] = []byte{byte(_LedZeroOffL + 4*pin), byte(off & 0xff)} - regVals[3] = []byte{byte(_LedZeroOffH + 4*pin), byte(off >> 8)} + regVals[0] = []byte{_LedZeroOnL + 4*pin, byte(on & 0xff)} + regVals[1] = []byte{_LedZeroOnH + 4*pin, byte(on >> 8)} + regVals[2] = []byte{_LedZeroOffL + 4*pin, byte(off & 0xff)} + regVals[3] = []byte{_LedZeroOffH + 4*pin, byte(off >> 8)} for i := 0; i < len(regVals); i++ { if _, err = conn.Write(regVals[i]); err != nil { return @@ -363,7 +367,6 @@ func (a *AdafruitMotorHatDriver) SetDCMotorSpeed(dcMotor int, speed int32) (err // RunDCMotor will set the appropriate pins to run the specified DC motor for // the given direction func (a *AdafruitMotorHatDriver) RunDCMotor(dcMotor int, dir AdafruitDirection) (err error) { - switch { case dir == AdafruitForward: if err = a.setPin(a.motorHatConnection, a.dcMotors[dcMotor].in2Pin, 0); err != nil { @@ -460,13 +463,13 @@ func (a *AdafruitMotorHatDriver) oneStep(motor int, dir AdafruitDirection, style pwmA = stepperMicrostepCurve[currStep-stepperMicrosteps*3] pwmB = stepperMicrostepCurve[stepperMicrosteps*4-currStep] } - } //switch + } // switch - //go to next 'step' and wrap around + // go to next 'step' and wrap around a.stepperMotors[motor].currentStep += stepperMicrosteps * 4 a.stepperMotors[motor].currentStep %= stepperMicrosteps * 4 - //only really used for microstepping, otherwise always on! + // only really used for microstepping, otherwise always on! if err = a.setPWM(a.motorHatConnection, a.stepperMotors[motor].pwmPinA, 0, int32(pwmA*16)); err != nil { return } diff --git a/drivers/i2c/ads1x15_driver.go b/drivers/i2c/ads1x15_driver.go index 1645f20ec..487dcb16e 100644 --- a/drivers/i2c/ads1x15_driver.go +++ b/drivers/i2c/ads1x15_driver.go @@ -1,13 +1,12 @@ package i2c import ( + "fmt" "log" "math" "sort" "strconv" "time" - - "fmt" ) const ads1x15DefaultAddress = 0x48 diff --git a/drivers/i2c/ads1x15_driver_1015_test.go b/drivers/i2c/ads1x15_driver_1015_test.go index ef882fa39..2e23bce0f 100644 --- a/drivers/i2c/ads1x15_driver_1015_test.go +++ b/drivers/i2c/ads1x15_driver_1015_test.go @@ -177,7 +177,7 @@ func TestADS1015_rawRead(t *testing.T) { // * read config register (16 bit, MSByte first) and wait for bit 15 is set // * read conversion register (16 bit, MSByte first) for the value // * apply two's complement converter, relates to one digit resolution (1/2^15), voltage multiplier - var tests = map[string]struct { + tests := map[string]struct { input []uint8 gain int dataRate int diff --git a/drivers/i2c/ads1x15_driver_1115_test.go b/drivers/i2c/ads1x15_driver_1115_test.go index 5b3e5559c..c1fd7d0e3 100644 --- a/drivers/i2c/ads1x15_driver_1115_test.go +++ b/drivers/i2c/ads1x15_driver_1115_test.go @@ -177,7 +177,7 @@ func TestADS1115_rawRead(t *testing.T) { // * read config register (16 bit, MSByte first) and wait for bit 15 is set // * read conversion register (16 bit, MSByte first) for the value // * apply two's complement converter, relates to one digit resolution (1/2^15), voltage multiplier - var tests = map[string]struct { + tests := map[string]struct { input []uint8 gain int dataRate int diff --git a/drivers/i2c/ads1x15_driver_test.go b/drivers/i2c/ads1x15_driver_test.go index d842367f9..9d93f770f 100644 --- a/drivers/i2c/ads1x15_driver_test.go +++ b/drivers/i2c/ads1x15_driver_test.go @@ -15,7 +15,7 @@ var _ gobot.Driver = (*ADS1x15Driver)(nil) // that supports the AnalogReader interface var _ aio.AnalogReader = (*ADS1x15Driver)(nil) -func initTestADS1x15DriverWithStubbedAdaptor() (*ADS1x15Driver, *i2cTestAdaptor) { +func initTestADS1x15DriverWithStubbedAdaptor() (*ADS1x15Driver, *i2cTestAdaptor) { //nolint:unparam // keep for tests a := newI2cTestAdaptor() const defaultDataRate = 3 dataRates := map[int]uint16{defaultDataRate: 0x0003} diff --git a/drivers/i2c/adxl345_driver.go b/drivers/i2c/adxl345_driver.go index 61df38e0b..5084bd2a6 100644 --- a/drivers/i2c/adxl345_driver.go +++ b/drivers/i2c/adxl345_driver.go @@ -15,8 +15,10 @@ const ( adxl345DefaultAddress = 0x53 ) -type ADXL345RateConfig uint8 -type ADXL345FsRangeConfig uint8 +type ( + ADXL345RateConfig uint8 + ADXL345FsRangeConfig uint8 +) const ( // registers are named according to the datasheet diff --git a/drivers/i2c/adxl345_driver_test.go b/drivers/i2c/adxl345_driver_test.go index c74f8104e..eb2bc7333 100644 --- a/drivers/i2c/adxl345_driver_test.go +++ b/drivers/i2c/adxl345_driver_test.go @@ -143,7 +143,7 @@ func TestADXL345RawXYZ(t *testing.T) { // * apply two's complement converter // // arrange - var tests = map[string]struct { + tests := map[string]struct { inputX []uint8 inputY []uint8 inputZ []uint8 @@ -210,7 +210,7 @@ func TestADXL345RawXYZError(t *testing.T) { func TestADXL345XYZ(t *testing.T) { // arrange - var tests = map[string]struct { + tests := map[string]struct { inputX []uint8 inputY []uint8 inputZ []uint8 diff --git a/drivers/i2c/bh1750_driver.go b/drivers/i2c/bh1750_driver.go index 0eee86c03..a2bbe9c2b 100644 --- a/drivers/i2c/bh1750_driver.go +++ b/drivers/i2c/bh1750_driver.go @@ -20,7 +20,6 @@ const ( ) // BH1750Driver is a driver for the BH1750 digital Ambient Light Sensor IC for I²C bus interface. -// type BH1750Driver struct { *Driver mode byte @@ -28,12 +27,13 @@ type BH1750Driver struct { // NewBH1750Driver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewBH1750Driver(c Connector, options ...func(Config)) *BH1750Driver { h := &BH1750Driver{ Driver: NewDriver(c, "BH1750", bh1750DefaultAddress), @@ -51,7 +51,6 @@ func NewBH1750Driver(c Connector, options ...func(Config)) *BH1750Driver { // RawSensorData returns the raw value from the bh1750 func (h *BH1750Driver) RawSensorData() (level int, err error) { - buf := []byte{0, 0} bytesRead, err := h.connection.Read(buf) if bytesRead != 2 { @@ -68,7 +67,6 @@ func (h *BH1750Driver) RawSensorData() (level int, err error) { // Lux returns the adjusted value from the bh1750 func (h *BH1750Driver) Lux() (lux int, err error) { - lux, err = h.RawSensorData() lux = int(float64(lux) / 1.2) diff --git a/drivers/i2c/bh1750_driver_test.go b/drivers/i2c/bh1750_driver_test.go index a914d4407..c2cbf9745 100644 --- a/drivers/i2c/bh1750_driver_test.go +++ b/drivers/i2c/bh1750_driver_test.go @@ -1,12 +1,11 @@ package i2c import ( + "bytes" "errors" "strings" "testing" - "bytes" - "github.com/stretchr/testify/assert" "gobot.io/x/gobot/v2" ) diff --git a/drivers/i2c/blinkm_driver.go b/drivers/i2c/blinkm_driver.go index 525331343..ef8711639 100644 --- a/drivers/i2c/blinkm_driver.go +++ b/drivers/i2c/blinkm_driver.go @@ -14,12 +14,13 @@ type BlinkMDriver struct { // NewBlinkMDriver creates a new BlinkMDriver. // // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewBlinkMDriver(c Connector, options ...func(Config)) *BlinkMDriver { b := &BlinkMDriver{ Driver: NewDriver(c, "BlinkM", blinkmDefaultAddress), diff --git a/drivers/i2c/blinkm_driver_test.go b/drivers/i2c/blinkm_driver_test.go index 519931a25..e3a00e73b 100644 --- a/drivers/i2c/blinkm_driver_test.go +++ b/drivers/i2c/blinkm_driver_test.go @@ -154,7 +154,6 @@ func TestBlinkMColor(t *testing.T) { _, err := d.Color() assert.Errorf(t, err, "write error") - } func TestBlinkMFade(t *testing.T) { @@ -165,7 +164,6 @@ func TestBlinkMFade(t *testing.T) { err := d.Fade(100, 100, 100) assert.Errorf(t, err, "write error") - } func TestBlinkMRGB(t *testing.T) { @@ -176,5 +174,4 @@ func TestBlinkMRGB(t *testing.T) { err := d.Rgb(100, 100, 100) assert.Errorf(t, err, "write error") - } diff --git a/drivers/i2c/bme280_driver.go b/drivers/i2c/bme280_driver.go index a42a1851c..d3767cdc1 100644 --- a/drivers/i2c/bme280_driver.go +++ b/drivers/i2c/bme280_driver.go @@ -213,7 +213,6 @@ func (d *BME280Driver) initHumidity() error { } return d.connection.WriteByteData(bmp280RegCtrl, cmr) - } func (d *BME280Driver) rawHumidity() (uint32, error) { diff --git a/drivers/i2c/bmp180_driver.go b/drivers/i2c/bmp180_driver.go index 2d52a063e..a4cd1c085 100644 --- a/drivers/i2c/bmp180_driver.go +++ b/drivers/i2c/bmp180_driver.go @@ -160,7 +160,6 @@ func (d *BMP180Driver) initialization() error { return err } return binary.Read(buf, binary.BigEndian, &d.calCoeffs.md) - } func (d *BMP180Driver) rawTemp() (int16, error) { diff --git a/drivers/i2c/bmp180_driver_test.go b/drivers/i2c/bmp180_driver_test.go index 35056977b..de26fdfaa 100644 --- a/drivers/i2c/bmp180_driver_test.go +++ b/drivers/i2c/bmp180_driver_test.go @@ -201,8 +201,8 @@ func TestBMP180_initialization(t *testing.T) { } func TestBMP180_bmp180PauseForReading(t *testing.T) { - assert.Equal(t, time.Duration(5*time.Millisecond), bmp180PauseForReading(BMP180UltraLowPower)) - assert.Equal(t, time.Duration(8*time.Millisecond), bmp180PauseForReading(BMP180Standard)) - assert.Equal(t, time.Duration(14*time.Millisecond), bmp180PauseForReading(BMP180HighResolution)) - assert.Equal(t, time.Duration(26*time.Millisecond), bmp180PauseForReading(BMP180UltraHighResolution)) + assert.Equal(t, 5*time.Millisecond, bmp180PauseForReading(BMP180UltraLowPower)) + assert.Equal(t, 8*time.Millisecond, bmp180PauseForReading(BMP180Standard)) + assert.Equal(t, 14*time.Millisecond, bmp180PauseForReading(BMP180HighResolution)) + assert.Equal(t, 26*time.Millisecond, bmp180PauseForReading(BMP180UltraHighResolution)) } diff --git a/drivers/i2c/bmp280_driver.go b/drivers/i2c/bmp280_driver.go index cea919de4..ebf5207d0 100644 --- a/drivers/i2c/bmp280_driver.go +++ b/drivers/i2c/bmp280_driver.go @@ -13,9 +13,11 @@ const bmp280Debug = true // this is also true for bme280 (which using this address as well) const bmp280DefaultAddress = 0x77 -type BMP280PressureOversampling uint8 -type BMP280TemperatureOversampling uint8 -type BMP280IIRFilter uint8 +type ( + BMP280PressureOversampling uint8 + BMP280TemperatureOversampling uint8 + BMP280IIRFilter uint8 +) const ( bmp280RegCalib00 = 0x88 // 12 x 16 bit calibration data (T1..T3, P1..P9) @@ -245,7 +247,7 @@ func (d *BMP280Driver) initialization() error { return err } - ctrlReg := uint8(d.ctrlPwrMode) | uint8(d.ctrlPressOversamp)<<2 | uint8(d.ctrlTempOversamp)<<5 + ctrlReg := d.ctrlPwrMode | uint8(d.ctrlPressOversamp)<<2 | uint8(d.ctrlTempOversamp)<<5 if err := d.connection.WriteByteData(bmp280RegCtrl, ctrlReg); err != nil { return err } diff --git a/drivers/i2c/bmp388_driver.go b/drivers/i2c/bmp388_driver.go index d7bf2f30b..a5dda145a 100644 --- a/drivers/i2c/bmp388_driver.go +++ b/drivers/i2c/bmp388_driver.go @@ -14,8 +14,10 @@ const bmp388Debug = false const bmp388DefaultAddress = 0x77 // BMP388Accuracy accuracy type -type BMP388Accuracy uint8 -type BMP388IIRFilter uint8 +type ( + BMP388Accuracy uint8 + BMP388IIRFilter uint8 +) const ( bmp388ChipID = 0x50 @@ -136,7 +138,7 @@ func (d *BMP388Driver) Temperature(accuracy BMP388Accuracy) (temp float32, err e var rawT int32 - mode := uint8(d.ctrlPwrMode)<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit + mode := d.ctrlPwrMode<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit if err = d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { return 0, err } @@ -160,7 +162,7 @@ func (d *BMP388Driver) Pressure(accuracy BMP388Accuracy) (press float32, err err var rawT, rawP int32 - mode := uint8(d.ctrlPwrMode)<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit + mode := d.ctrlPwrMode<<4 | bmp388PWRCTRLPressEnableBit | bmp388PWRCTRLTempEnableBit if err = d.connection.WriteByteData(bmp388RegPWRCTRL, mode); err != nil { return 0, err } @@ -194,7 +196,6 @@ func (d *BMP388Driver) Altitude(accuracy BMP388Accuracy) (alt float32, err error // initialization reads the calibration coefficients. func (d *BMP388Driver) initialization() error { - chipID, err := d.connection.ReadByteData(bmp388RegChipID) if err != nil { return err diff --git a/drivers/i2c/ccs811_driver.go b/drivers/i2c/ccs811_driver.go index 1d50e6b4f..8434d770d 100644 --- a/drivers/i2c/ccs811_driver.go +++ b/drivers/i2c/ccs811_driver.go @@ -20,33 +20,33 @@ const ( const ( - //the default I2C address for the ccs811 applies for ADDR to GND, for ADDR to VDD it will be 0x5B + // the default I2C address for the ccs811 applies for ADDR to GND, for ADDR to VDD it will be 0x5B ccs811DefaultAddress = 0x5A - //Registers, all definitions have been taken from the datasheet - //Single byte read only register which indicates if a device is active, if new data is available or if an error occurred. + // Registers, all definitions have been taken from the datasheet + // Single byte read only register which indicates if a device is active, if new data is available or if an error occurred. ccs811RegStatus = 0x00 - //This is Single byte register, which is used to enable sensor drive mode and interrupts. + // This is Single byte register, which is used to enable sensor drive mode and interrupts. ccs811RegMeasMode = 0x01 - //This multi-byte read only register contains the calculated eCO2 (ppm) and eTVOC (ppb) values followed by the STATUS register, ERROR_ID register and the RAW_DATA register. + // This multi-byte read only register contains the calculated eCO2 (ppm) and eTVOC (ppb) values followed by the STATUS register, ERROR_ID register and the RAW_DATA register. ccs811RegAlgResultData = 0x02 - //Two byte read only register which contains the latest readings from the sensor. - //ccs811RegRawData = 0x03 - //A multi-byte register that can be written with the current Humidity and Temperature values if known. - //ccs811RegEnvData = 0x05 - //Register that holds the NTC value used for temperature calcualtions + // Two byte read only register which contains the latest readings from the sensor. + // ccs811RegRawData = 0x03 + // A multi-byte register that can be written with the current Humidity and Temperature values if known. + // ccs811RegEnvData = 0x05 + // Register that holds the NTC value used for temperature calculations ccs811RegNtc = 0x06 - //Asserting the SW_RESET will restart the CCS811 in Boot mode to enable new application firmware to be downloaded. + // Asserting the SW_RESET will restart the CCS811 in Boot mode to enable new application firmware to be downloaded. ccs811RegSwReset = 0xFF - //Single byte read only register which holds the HW ID which is 0x81 for this family of CCS81x devices. + // Single byte read only register which holds the HW ID which is 0x81 for this family of CCS81x devices. ccs811RegHwID = 0x20 - //Single byte read only register that contains the hardware version. The value is 0x1X + // Single byte read only register that contains the hardware version. The value is 0x1X ccs811RegHwVersion = 0x21 - //Two byte read only register which contain the version of the firmware bootloader stored in the CCS811 in the format Major.Minor.Trivial + // Two byte read only register which contain the version of the firmware bootloader stored in the CCS811 in the format Major.Minor.Trivial ccs811RegFwBootVersion = 0x23 - //Two byte read only register which contain the version of the firmware application stored in the CCS811 in the format Major.Minor.Trivial + // Two byte read only register which contain the version of the firmware application stored in the CCS811 in the format Major.Minor.Trivial ccs811RegFwAppVersion = 0x24 - //To change the mode of the CCS811 from Boot mode to running the application, a single byte write of 0xF4 is required. + // To change the mode of the CCS811 from Boot mode to running the application, a single byte write of 0xF4 is required. ccs811RegAppStart = 0xF4 // Constants @@ -54,21 +54,19 @@ const ( ccs811HwIDCode = 0x81 ) -var ( - // The sequence of bytes needed to do a software reset - ccs811SwResetSequence = []byte{0x11, 0xE5, 0x72, 0x8A} -) +// The sequence of bytes needed to do a software reset +var ccs811SwResetSequence = []byte{0x11, 0xE5, 0x72, 0x8A} // CCS811Status represents the current status of the device defined by the ccs811RegStatus. // The following definitions were taken from https://ams.com/documents/20143/36005/CCS811_DS000459_6-00.pdf/c7091525-c7e5-37ac-eedb-b6c6828b0dcf#page=15 type CCS811Status struct { - //There is some sort of error on the i2c bus or there is an error with the internal sensor + // There is some sort of error on the i2c bus or there is an error with the internal sensor HasError byte - //A new data sample is ready in ccs811RegAlgResultData + // A new data sample is ready in ccs811RegAlgResultData DataReady byte - //Valid application firmware loaded + // Valid application firmware loaded AppValid byte - //Firmware is in application mode. CCS811 is ready to take sensor measurements + // Firmware is in application mode. CCS811 is ready to take sensor measurements FwMode byte } @@ -86,12 +84,12 @@ func NewCCS811Status(data uint8) *CCS811Status { // The following definitions were taken from the bit fields of the ccs811RegMeasMode defined in // https://ams.com/documents/20143/36005/CCS811_DS000459_6-00.pdf/c7091525-c7e5-37ac-eedb-b6c6828b0dcf#page=16 type CCS811MeasMode struct { - //If intThresh is 1 a data measurement will only be taken when the sensor value meets the threshold constraint. - //The threshold value is set in the threshold register (0x10) + // If intThresh is 1 a data measurement will only be taken when the sensor value meets the threshold constraint. + // The threshold value is set in the threshold register (0x10) intThresh uint8 - //If intDataRdy is 1, the nINT signal (pin 3 of the device) will be driven low when new data is available. + // If intDataRdy is 1, the nINT signal (pin 3 of the device) will be driven low when new data is available. intDataRdy uint8 - //driveMode represents the sampling rate of the sensor. If the value is 0, the measurement process is idle. + // driveMode represents the sampling rate of the sensor. If the value is 0, the measurement process is idle. driveMode CCS811DriveMode } @@ -123,7 +121,7 @@ func NewCCS811Driver(c Connector, options ...func(Config)) *CCS811Driver { d := &CCS811Driver{ Driver: NewDriver(c, "CCS811", ccs811DefaultAddress), measMode: NewCCS811MeasMode(), - //Recommended resistance value is 100,000 + // Recommended resistance value is 100,000 ntcResistanceValue: 100000, } d.afterStart = d.initialize @@ -205,7 +203,7 @@ func (d *CCS811Driver) GetStatus() (*CCS811Status, error) { return cs, nil } -// GetTemperature returns the device temperature in celcius. +// GetTemperature returns the device temperature in celsius. // If you do not have an NTC resistor installed, this function should not be called func (d *CCS811Driver) GetTemperature() (float32, error) { d.mutex.Lock() @@ -319,7 +317,7 @@ func (d *CCS811Driver) resetDevice() error { // startApp starts the app code in the device. This operation has to be done after a // software reset to start taking sensor measurements. func (d *CCS811Driver) startApp() error { - //Write without data is needed to start the app code + // Write without data is needed to start the app code _, err := d.connection.Write([]byte{ccs811RegAppStart}) return err } diff --git a/drivers/i2c/ccs811_driver_test.go b/drivers/i2c/ccs811_driver_test.go index 956821443..8ac004940 100644 --- a/drivers/i2c/ccs811_driver_test.go +++ b/drivers/i2c/ccs811_driver_test.go @@ -42,11 +42,11 @@ func TestCCS811Options(t *testing.T) { func TestCCS811WithCCS811MeasMode(t *testing.T) { d := NewCCS811Driver(newI2cTestAdaptor(), WithCCS811MeasMode(CCS811DriveMode10Sec)) - assert.Equal(t, CCS811DriveMode(CCS811DriveMode10Sec), d.measMode.driveMode) + assert.Equal(t, CCS811DriveMode10Sec, d.measMode.driveMode) } func TestCCS811GetGasData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { readReturn func([]byte) (int, error) eco2 uint16 tvoc uint16 @@ -99,7 +99,7 @@ func TestCCS811GetGasData(t *testing.T) { } func TestCCS811GetTemperature(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { readReturn func([]byte) (int, error) temp float32 err error @@ -155,7 +155,7 @@ func TestCCS811GetTemperature(t *testing.T) { } func TestCCS811HasData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { readReturn func([]byte) (int, error) result bool err error diff --git a/drivers/i2c/drv2605l_driver.go b/drivers/i2c/drv2605l_driver.go index 24877a5ad..5adbbaf17 100644 --- a/drivers/i2c/drv2605l_driver.go +++ b/drivers/i2c/drv2605l_driver.go @@ -65,10 +65,9 @@ const ( // // Basic use: // -// haptic := i2c.NewDRV2605Driver(adaptor) -// haptic.SetSequence([]byte{1, 13}) -// haptic.Go() -// +// haptic := i2c.NewDRV2605Driver(adaptor) +// haptic.SetSequence([]byte{1, 13}) +// haptic.Go() type DRV2605LDriver struct { *Driver } @@ -76,12 +75,13 @@ type DRV2605LDriver struct { // NewDRV2605LDriver creates a new driver for the DRV2605L device. // // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewDRV2605LDriver(c Connector, options ...func(Config)) *DRV2605LDriver { d := &DRV2605LDriver{ Driver: NewDriver(c, "DRV2605L", drv2605DefaultAddress), diff --git a/drivers/i2c/grove_drivers.go b/drivers/i2c/grove_drivers.go index a5459951e..f54ff16fb 100644 --- a/drivers/i2c/grove_drivers.go +++ b/drivers/i2c/grove_drivers.go @@ -15,12 +15,13 @@ type GroveAccelerometerDriver struct { // NewGroveLcdDriver creates a new driver with specified i2c interface. // Params: -// conn Connector - the Adaptor to use with this Driver +// +// conn Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewGroveLcdDriver(a Connector, options ...func(Config)) *GroveLcdDriver { lcd := &GroveLcdDriver{ JHD1313M1Driver: NewJHD1313M1Driver(a), @@ -35,12 +36,13 @@ func NewGroveLcdDriver(a Connector, options ...func(Config)) *GroveLcdDriver { // NewGroveAccelerometerDriver creates a new driver with specified i2c interface // Params: -// conn Connector - the Adaptor to use with this Driver +// +// conn Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewGroveAccelerometerDriver(a Connector, options ...func(Config)) *GroveAccelerometerDriver { mma := &GroveAccelerometerDriver{ MMA7660Driver: NewMMA7660Driver(a), diff --git a/drivers/i2c/grove_drivers_test.go b/drivers/i2c/grove_drivers_test.go index eff163972..19f755897 100644 --- a/drivers/i2c/grove_drivers_test.go +++ b/drivers/i2c/grove_drivers_test.go @@ -8,8 +8,10 @@ import ( "gobot.io/x/gobot/v2" ) -var _ gobot.Driver = (*GroveLcdDriver)(nil) -var _ gobot.Driver = (*GroveAccelerometerDriver)(nil) +var ( + _ gobot.Driver = (*GroveLcdDriver)(nil) + _ gobot.Driver = (*GroveAccelerometerDriver)(nil) +) func initTestGroveLcdDriver() (driver *GroveLcdDriver) { driver, _ = initGroveLcdDriverWithStubbedAdaptor() diff --git a/drivers/i2c/grovepi_driver.go b/drivers/i2c/grovepi_driver.go index fea0dcbbd..bc5a799a4 100644 --- a/drivers/i2c/grovepi_driver.go +++ b/drivers/i2c/grovepi_driver.go @@ -29,9 +29,8 @@ const ( // GrovePiDriver is a driver for the GrovePi+ for I²C bus interface. // https://www.dexterindustries.com/grovepi/ // -// To use this driver with the GrovePi, it must be running the firmware >= 1.4.0 and and the system version >=3. +// To use this driver with the GrovePi, it must be running the firmware >= 1.4.0 and the system version >=3. // https://github.com/DexterInd/GrovePi/blob/master/README.md -// type GrovePiDriver struct { *Driver pins map[int]string @@ -39,12 +38,13 @@ type GrovePiDriver struct { // NewGrovePiDriver creates a new driver with specified i2c interface // Params: -// conn Connector - the Adaptor to use with this Driver +// +// conn Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewGrovePiDriver(c Connector, options ...func(Config)) *GrovePiDriver { d := &GrovePiDriver{ Driver: NewDriver(c, "GrovePi", grovePiDefaultAddress), diff --git a/drivers/i2c/grovepi_driver_test.go b/drivers/i2c/grovepi_driver_test.go index 23b16db5f..db6fd83e9 100644 --- a/drivers/i2c/grovepi_driver_test.go +++ b/drivers/i2c/grovepi_driver_test.go @@ -56,7 +56,7 @@ func TestGrovePiOptions(t *testing.T) { func TestGrovePiSomeRead(t *testing.T) { // arrange - var tests = map[string]struct { + tests := map[string]struct { usedPin int wantWritten []uint8 simResponse [][]uint8 @@ -179,7 +179,7 @@ func TestGrovePiSomeRead(t *testing.T) { func TestGrovePiSomeWrite(t *testing.T) { // arrange - var tests = map[string]struct { + tests := map[string]struct { usedPin int usedValue int wantWritten []uint8 diff --git a/drivers/i2c/hmc5883l_driver.go b/drivers/i2c/hmc5883l_driver.go index f2acbd34a..395ab8431 100644 --- a/drivers/i2c/hmc5883l_driver.go +++ b/drivers/i2c/hmc5883l_driver.go @@ -109,16 +109,17 @@ var hmc5883lGainBits = map[float64]int{ // NewHMC5883LDriver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver -// i2c.WithHMC5883LSamplesAveraged(int) -// i2c.WithHMC5883LDataOutputRate(int) -// i2c.WithHMC5883LMeasurementFlow(int) -// i2c.WithHMC5883LGain(int) // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver +// i2c.WithHMC5883LSamplesAveraged(int) +// i2c.WithHMC5883LDataOutputRate(int) +// i2c.WithHMC5883LMeasurementFlow(int) +// i2c.WithHMC5883LGain(int) func NewHMC5883LDriver(c Connector, options ...func(Config)) *HMC5883LDriver { h := &HMC5883LDriver{ Driver: NewDriver(c, "HMC5883L", hmc5883lDefaultAddress), diff --git a/drivers/i2c/hmc5883l_driver_test.go b/drivers/i2c/hmc5883l_driver_test.go index c7b9b2dff..890ccefe1 100644 --- a/drivers/i2c/hmc5883l_driver_test.go +++ b/drivers/i2c/hmc5883l_driver_test.go @@ -61,7 +61,7 @@ func TestHMC5883LWithHMC5883LGain(t *testing.T) { func TestHMC5883LRead(t *testing.T) { // arrange - var tests = map[string]struct { + tests := map[string]struct { inputX []uint8 inputY []uint8 inputZ []uint8 @@ -136,7 +136,7 @@ func TestHMC5883L_readRawData(t *testing.T) { // * apply two's complement converter // // arrange - var tests = map[string]struct { + tests := map[string]struct { inputX []uint8 inputY []uint8 inputZ []uint8 diff --git a/drivers/i2c/hmc6352_driver.go b/drivers/i2c/hmc6352_driver.go index 6c9d8544c..8dd8c43f3 100644 --- a/drivers/i2c/hmc6352_driver.go +++ b/drivers/i2c/hmc6352_driver.go @@ -9,12 +9,13 @@ type HMC6352Driver struct { // NewHMC6352Driver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewHMC6352Driver(c Connector, options ...func(Config)) *HMC6352Driver { h := &HMC6352Driver{ Driver: NewDriver(c, "HMC6352", hmc6352DefaultAddress), diff --git a/drivers/i2c/i2c_config_test.go b/drivers/i2c/i2c_config_test.go index 522e506bb..7c9a2fbb2 100644 --- a/drivers/i2c/i2c_config_test.go +++ b/drivers/i2c/i2c_config_test.go @@ -37,7 +37,7 @@ func TestWithAddress(t *testing.T) { } func TestGetBusOrDefaultWithBusOption(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { init int bus int want int @@ -59,7 +59,7 @@ func TestGetBusOrDefaultWithBusOption(t *testing.T) { } func TestGetAddressOrDefaultWithAddressOption(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { init int address int want int diff --git a/drivers/i2c/i2c_connection_test.go b/drivers/i2c/i2c_connection_test.go index a243dd013..6be0e6237 100644 --- a/drivers/i2c/i2c_connection_test.go +++ b/drivers/i2c/i2c_connection_test.go @@ -5,7 +5,6 @@ package i2c import ( "testing" - "unsafe" "github.com/stretchr/testify/assert" diff --git a/drivers/i2c/i2c_driver.go b/drivers/i2c/i2c_driver.go index 238e7ac45..88c26ab79 100644 --- a/drivers/i2c/i2c_driver.go +++ b/drivers/i2c/i2c_driver.go @@ -91,7 +91,7 @@ func (d *Driver) Start() error { var err error bus := d.GetBusOrDefault(d.connector.DefaultI2cBus()) - address := d.GetAddressOrDefault(int(d.defaultAddress)) + address := d.GetAddressOrDefault(d.defaultAddress) if d.connection, err = d.connector.GetI2cConnection(address, bus); err != nil { return err diff --git a/drivers/i2c/ina3221_driver.go b/drivers/i2c/ina3221_driver.go index 1624325fd..6ff5ab7a2 100644 --- a/drivers/i2c/ina3221_driver.go +++ b/drivers/i2c/ina3221_driver.go @@ -149,7 +149,7 @@ func (i *INA3221Driver) readWordFromRegister(reg uint8) (uint16, error) { return 0, err } - return uint16(((val & 0x00FF) << 8) | ((val & 0xFF00) >> 8)), nil + return ((val & 0x00FF) << 8) | ((val & 0xFF00) >> 8), nil } // initialize initializes the INA3221 device diff --git a/drivers/i2c/ina3221_driver_test.go b/drivers/i2c/ina3221_driver_test.go index 2e490830e..784306c5c 100644 --- a/drivers/i2c/ina3221_driver_test.go +++ b/drivers/i2c/ina3221_driver_test.go @@ -1,11 +1,9 @@ package i2c import ( - "testing" - "errors" - "strings" + "testing" "github.com/stretchr/testify/assert" "gobot.io/x/gobot/v2" diff --git a/drivers/i2c/l3gd20h_driver_test.go b/drivers/i2c/l3gd20h_driver_test.go index 01a3cf728..b59337ed2 100644 --- a/drivers/i2c/l3gd20h_driver_test.go +++ b/drivers/i2c/l3gd20h_driver_test.go @@ -47,7 +47,7 @@ func TestL3GD20HOptions(t *testing.T) { } func TestL3GD20HWithL3GD20HFullScaleRange(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { scale L3GD20HScale want uint8 }{ @@ -81,7 +81,7 @@ func TestL3GD20HWithL3GD20HFullScaleRange(t *testing.T) { } func TestL3GD20HScale(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { scale L3GD20HScale want uint8 }{ @@ -146,7 +146,7 @@ func TestL3GD20HMeasurement(t *testing.T) { // // data table according to data sheet AN4506 example in table 7, supplemented with FS limit values sensitivity := float32(0.00875) // FS=245 dps - var tests = map[string]struct { + tests := map[string]struct { gyroData []byte wantX float32 wantY float32 diff --git a/drivers/i2c/lidarlite_driver.go b/drivers/i2c/lidarlite_driver.go index 698fb9dc6..79f7d7d40 100644 --- a/drivers/i2c/lidarlite_driver.go +++ b/drivers/i2c/lidarlite_driver.go @@ -14,12 +14,13 @@ type LIDARLiteDriver struct { // NewLIDARLiteDriver creates a new driver for the LIDARLite I2C LIDAR device. // // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewLIDARLiteDriver(c Connector, options ...func(Config)) *LIDARLiteDriver { l := &LIDARLiteDriver{ Driver: NewDriver(c, "LIDARLite", lidarliteDefaultAddress), diff --git a/drivers/i2c/mcp23017_driver.go b/drivers/i2c/mcp23017_driver.go index 0746f5766..4b8697859 100644 --- a/drivers/i2c/mcp23017_driver.go +++ b/drivers/i2c/mcp23017_driver.go @@ -192,7 +192,7 @@ func WithMCP23017Intpol(val uint8) func(Config) { } } -// WithMCP23017ForceWrite option modifies the MCP23017Driver forceRefresh option +// WithMCP23017ForceRefresh option modifies the MCP23017Driver forceRefresh option // Setting to true (1) will force refresh operation to register, although there is no change. // Normally this is not needed, so default is off (0). // When there is something flaky, there is a small chance to stabilize by setting this flag to true. @@ -209,7 +209,7 @@ func WithMCP23017ForceRefresh(val uint8) func(Config) { } // WithMCP23017AutoIODirOff option modifies the MCP23017Driver autoIODirOff option -// Set IO direction at each read or write operation ensures the correct direction, which is the the default setting. +// Set IO direction at each read or write operation ensures the correct direction, which is the default setting. // Most hardware is configured statically, so this can avoided by setting the direction using SetPinMode(), // e.g. in the start up sequence. If this way is taken, the automatic set of direction at each call can // be safely deactivated with this flag (set to true, 1). @@ -234,7 +234,7 @@ func (m *MCP23017Driver) SetPinMode(pin uint8, portStr string, val uint8) (err e selectedPort := m.getPort(portStr) // Set IODIR register bit for given pin to an output/input. - if err = m.write(selectedPort.IODIR, uint8(pin), bitState(val)); err != nil { + if err = m.write(selectedPort.IODIR, pin, bitState(val)); err != nil { return } return @@ -271,7 +271,7 @@ func (m *MCP23017Driver) WriteGPIO(pin uint8, portStr string, val uint8) (err er if !m.mcpBehav.autoIODirOff { // Set IODIR register bit for given pin to an output by clearing bit. // can't call SetPinMode() because mutex will cause deadlock - if err = m.write(selectedPort.IODIR, uint8(pin), clear); err != nil { + if err = m.write(selectedPort.IODIR, pin, clear); err != nil { return err } } @@ -292,7 +292,7 @@ func (m *MCP23017Driver) ReadGPIO(pin uint8, portStr string) (val uint8, err err if !m.mcpBehav.autoIODirOff { // Set IODIR register bit for given pin to an input by set bit. // can't call SetPinMode() because mutex will cause deadlock - if err = m.write(selectedPort.IODIR, uint8(pin), set); err != nil { + if err = m.write(selectedPort.IODIR, pin, set); err != nil { return 0, err } } @@ -300,7 +300,7 @@ func (m *MCP23017Driver) ReadGPIO(pin uint8, portStr string) (val uint8, err err if err != nil { return val, err } - val = 1 << uint8(pin) & val + val = 1 << pin & val if val > 1 { val = 1 } diff --git a/drivers/i2c/mcp23017_driver_test.go b/drivers/i2c/mcp23017_driver_test.go index 220df3272..8fff18697 100644 --- a/drivers/i2c/mcp23017_driver_test.go +++ b/drivers/i2c/mcp23017_driver_test.go @@ -31,7 +31,7 @@ func initTestMCP23017(b uint8) (driver *MCP23017Driver) { return d } -func initTestMCP23017WithStubbedAdaptor(b uint8) (*MCP23017Driver, *i2cTestAdaptor) { +func initTestMCP23017WithStubbedAdaptor(b uint8) (*MCP23017Driver, *i2cTestAdaptor) { //nolint:unparam // keep for tests // create the driver, ready to use for tests a := newI2cTestAdaptor() d := NewMCP23017Driver(a, WithMCP23017Bank(b)) diff --git a/drivers/i2c/mma7660_driver.go b/drivers/i2c/mma7660_driver.go index 007cc8b97..8e9f5acd5 100644 --- a/drivers/i2c/mma7660_driver.go +++ b/drivers/i2c/mma7660_driver.go @@ -32,12 +32,13 @@ type MMA7660Driver struct { // NewMMA7660Driver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewMMA7660Driver(c Connector, options ...func(Config)) *MMA7660Driver { d := &MMA7660Driver{ Driver: NewDriver(c, "MMA7660", mma7660DefaultAddress), diff --git a/drivers/i2c/mpl115a2_driver.go b/drivers/i2c/mpl115a2_driver.go index 0791a55ae..cbe32206f 100644 --- a/drivers/i2c/mpl115a2_driver.go +++ b/drivers/i2c/mpl115a2_driver.go @@ -1,11 +1,11 @@ package i2c import ( - "gobot.io/x/gobot/v2" - "bytes" "encoding/binary" "time" + + "gobot.io/x/gobot/v2" ) const mpl115a2DefaultAddress = 0x60 diff --git a/drivers/i2c/mpu6050_driver.go b/drivers/i2c/mpu6050_driver.go index 38b294945..778e9a5c0 100644 --- a/drivers/i2c/mpu6050_driver.go +++ b/drivers/i2c/mpu6050_driver.go @@ -14,11 +14,13 @@ const ( mpu6050EarthStandardGravity = 9.80665 // [m/s²] standard gravity (pole: 9.834, equator: 9.764) ) -type MPU6050DlpfConfig uint8 -type MPU6050FrameSyncConfig uint8 -type MPU6050GyroFsConfig uint8 -type MPU6050AccelFsConfig uint8 -type MPU6050Pwr1ClockConfig uint8 +type ( + MPU6050DlpfConfig uint8 + MPU6050FrameSyncConfig uint8 + MPU6050GyroFsConfig uint8 + MPU6050AccelFsConfig uint8 + MPU6050Pwr1ClockConfig uint8 +) const ( mpu6050Reg_GeneralConfig = 0x1A // external frame synchronization and digital low pass filter diff --git a/drivers/i2c/pca9501_driver.go b/drivers/i2c/pca9501_driver.go index dd38474d4..05677886b 100644 --- a/drivers/i2c/pca9501_driver.go +++ b/drivers/i2c/pca9501_driver.go @@ -16,7 +16,6 @@ const pca9501DefaultAddress = 0x3F // this applies, if all 6 address pins left o // please refer to data sheet: https://www.nxp.com/docs/en/data-sheet/PCA9501.pdf // // PCA9501 is the replacement for PCF8574, so this driver should also work for PCF8574 except EEPROM calls -// type PCA9501Driver struct { connectionMem Connection *Driver @@ -24,12 +23,13 @@ type PCA9501Driver struct { // NewPCA9501Driver creates a new driver with specified i2c interface // Params: -// a Connector - the Adaptor to use with this Driver +// +// a Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver func NewPCA9501Driver(a Connector, options ...func(Config)) *PCA9501Driver { p := &PCA9501Driver{ Driver: NewDriver(a, "PCA9501", pca9501DefaultAddress, options...), @@ -76,9 +76,9 @@ func (p *PCA9501Driver) WriteGPIO(pin uint8, val uint8) error { return err } // set pin as output by clearing bit - iodirVal := clearBit(iodir, uint8(pin)) + iodirVal := clearBit(iodir, pin) // write CTRL register - err = p.connection.WriteByte(uint8(iodirVal)) + err = p.connection.WriteByte(iodirVal) if err != nil { return err } @@ -90,12 +90,12 @@ func (p *PCA9501Driver) WriteGPIO(pin uint8, val uint8) error { // set or reset the bit in value var nVal uint8 if val == 0 { - nVal = clearBit(cVal, uint8(pin)) + nVal = clearBit(cVal, pin) } else { - nVal = setBit(cVal, uint8(pin)) + nVal = setBit(cVal, pin) } // write new value to port - err = p.connection.WriteByte(uint8(nVal)) + err = p.connection.WriteByte(nVal) if err != nil { return err } @@ -113,9 +113,9 @@ func (p *PCA9501Driver) ReadGPIO(pin uint8) (uint8, error) { return 0, err } // set pin as input by setting bit - iodirVal := setBit(iodir, uint8(pin)) + iodirVal := setBit(iodir, pin) // write CTRL register - err = p.connection.WriteByte(uint8(iodirVal)) + err = p.connection.WriteByte(iodirVal) if err != nil { return 0, err } @@ -124,7 +124,7 @@ func (p *PCA9501Driver) ReadGPIO(pin uint8) (uint8, error) { if err != nil { return val, err } - val = 1 << uint8(pin) & val + val = 1 << pin & val if val > 1 { val = 1 } diff --git a/drivers/i2c/pca9501_driver_test.go b/drivers/i2c/pca9501_driver_test.go index 33ecb93d7..30e34315b 100644 --- a/drivers/i2c/pca9501_driver_test.go +++ b/drivers/i2c/pca9501_driver_test.go @@ -114,7 +114,7 @@ func TestPCA9501CommandsReadEEPROM(t *testing.T) { } func TestPCA9501WriteGPIO(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { setVal uint8 ioDirAllInput uint8 ioStateAllInput uint8 @@ -223,7 +223,7 @@ func TestPCA9501WriteGPIOErrorAtWriteValue(t *testing.T) { } func TestPCA9501ReadGPIO(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { ctrlState uint8 want uint8 }{ diff --git a/drivers/i2c/pca953x_driver.go b/drivers/i2c/pca953x_driver.go index 94151fba0..fd193441a 100644 --- a/drivers/i2c/pca953x_driver.go +++ b/drivers/i2c/pca953x_driver.go @@ -36,10 +36,12 @@ const ( PCA953xModePwm1 PCA953xGPIOMode = 0x03 ) -var errToSmallPeriod = fmt.Errorf("Given Period to small, must be at least 1/152s (~6.58ms) or 152Hz") -var errToBigPeriod = fmt.Errorf("Given Period to high, must be max. 256/152s (~1.68s) or 152/256Hz (~0.6Hz)") -var errToSmallDutyCycle = fmt.Errorf("Given Duty Cycle to small, must be at least 0%%") -var errToBigDutyCycle = fmt.Errorf("Given Duty Cycle to high, must be max. 100%%") +var ( + errToSmallPeriod = fmt.Errorf("Given Period to small, must be at least 1/152s (~6.58ms) or 152Hz") + errToBigPeriod = fmt.Errorf("Given Period to high, must be max. 256/152s (~1.68s) or 152/256Hz (~0.6Hz)") + errToSmallDutyCycle = fmt.Errorf("Given Duty Cycle to small, must be at least 0%%") + errToBigDutyCycle = fmt.Errorf("Given Duty Cycle to high, must be max. 100%%") +) // PCA953xDriver is a Gobot Driver for LED Dimmer PCA9530 (2-bit), PCA9533 (4-bit), PCA9531 (8-bit), PCA9532 (16-bit) // Although this is designed for LED's it can be used as a GPIO (read, write, pwm). @@ -118,7 +120,7 @@ func (d *PCA953xDriver) ReadGPIO(idx uint8) (uint8, error) { if err != nil { return val, err } - val = 1 << uint8(idx) & val + val = 1 << idx & val if val > 1 { val = 1 } @@ -133,7 +135,7 @@ func (d *PCA953xDriver) WritePeriod(idx uint8, valSec float32) error { // period is valid in range ~6.58ms..1.68s val, err := pca953xCalcPsc(valSec) if err != nil && pca953xDebug { - fmt.Println(err, "value shrinked!") + fmt.Println(err, "value limited!") } var regPsc pca953xRegister = pca953xRegPsc0 if idx > 0 { @@ -166,7 +168,7 @@ func (d *PCA953xDriver) WriteFrequency(idx uint8, valHz float32) error { // frequency is valid in range ~0.6..152Hz val, err := pca953xCalcPsc(1 / valHz) if err != nil && pca953xDebug { - fmt.Println(err, "value shrinked!") + fmt.Println(err, "value limited!") } regPsc := pca953xRegPsc0 if idx > 0 { @@ -199,7 +201,7 @@ func (d *PCA953xDriver) WriteDutyCyclePercent(idx uint8, valPercent float32) err val, err := pca953xCalcPwm(valPercent) if err != nil && pca953xDebug { - fmt.Println(err, "value shrinked!") + fmt.Println(err, "value limited!") } regPwm := pca953xRegPwm0 if idx > 0 { diff --git a/drivers/i2c/pca953x_driver_test.go b/drivers/i2c/pca953x_driver_test.go index 20e944b78..ab35b8e2f 100644 --- a/drivers/i2c/pca953x_driver_test.go +++ b/drivers/i2c/pca953x_driver_test.go @@ -40,7 +40,7 @@ func TestPCA953xWriteGPIO(t *testing.T) { // * read current state of LED select register (write reg, read val) // * modify 2 bits according to given index of GPIO // * write the new state to the LED select register (write reg, write val) - var tests = map[string]struct { + tests := map[string]struct { idx uint8 ls0State uint8 ls1State uint8 @@ -109,7 +109,7 @@ func TestPCA953xReadGPIO(t *testing.T) { // sequence to read: // * read current state of INPUT register (write reg 0x00, read val) // * convert bit position to output value - var tests = map[string]struct { + tests := map[string]struct { idx uint8 want uint8 wantErr error @@ -171,7 +171,7 @@ func TestPCA953xWritePeriod(t *testing.T) { // * calculate PSC value (0..255) from given value in seconds, valid values are 0.00658 ... 1.68 [s] // * choose PSC0 (0x01) or PSC1 (0x03) frequency prescaler register by the given index // * write the value to the register (write reg, write val) - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val float32 wantWritten []uint8 @@ -186,7 +186,7 @@ func TestPCA953xWritePeriod(t *testing.T) { val: 0.5, wantWritten: []byte{0x03, 75}, }, - "write_shrinked_noerror": { + "write_limited_noerror": { idx: 0, val: 2, wantWritten: []byte{0x01, 255}, @@ -211,7 +211,7 @@ func TestPCA953xReadPeriod(t *testing.T) { // * choose PSC0 (0x01) or PSC1 (0x03) frequency prescaler register by the given index // * read the value from the register (write reg, write val) // * calculate value in seconds from PSC value - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val uint8 want float32 @@ -262,7 +262,7 @@ func TestPCA953xWriteFrequency(t *testing.T) { // * calculate PSC value (0..255) from given value in Hz, valid values are 0.6 ... 152 [Hz] // * choose PSC0 (0x01) or PSC1 (0x03) frequency prescaler register by the given index // * write the value to the register (write reg, write val) - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val float32 wantWritten []uint8 @@ -277,7 +277,7 @@ func TestPCA953xWriteFrequency(t *testing.T) { val: 2, wantWritten: []byte{0x03, 75}, }, - "write_shrinked_noerror": { + "write_limited_noerror": { idx: 0, val: 153, wantWritten: []byte{0x01, 0}, @@ -302,7 +302,7 @@ func TestPCA953xReadFrequency(t *testing.T) { // * choose PSC0 (0x01) or PSC1 (0x03) frequency prescaler register by the given index // * read the value from the register (write reg, write val) // * calculate value in Hz from PSC value - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val uint8 want float32 @@ -353,7 +353,7 @@ func TestPCA953xWriteDutyCyclePercent(t *testing.T) { // * calculate PWM value (0..255) from given value in percent, valid values are 0 ... 100 [%] // * choose PWM0 (0x02) or PWM1 (0x04) pwm register by the given index // * write the value to the register (write reg, write val) - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val float32 wantWritten []uint8 @@ -368,7 +368,7 @@ func TestPCA953xWriteDutyCyclePercent(t *testing.T) { val: 50, wantWritten: []byte{0x04, 128}, }, - "write_shrinked_noerror": { + "write_limited_noerror": { idx: 1, val: 101, wantWritten: []byte{0x04, 255}, @@ -393,7 +393,7 @@ func TestPCA953xReadDutyCyclePercent(t *testing.T) { // * choose PWM0 (0x02) or PWM1 (0x04) pwm register by the given index // * read the value from the register (write reg, write val) // * calculate value percent from PWM value - var tests = map[string]struct { + tests := map[string]struct { idx uint8 val uint8 want float32 @@ -496,7 +496,7 @@ func TestPCA953x_writeRegister(t *testing.T) { assert.Equal(t, 1, numCallsWrite) assert.Equal(t, wantByteCount, len(a.written)) assert.Equal(t, uint8(wantRegAddress), a.written[0]) - assert.Equal(t, uint8(wantRegVal), a.written[1]) + assert.Equal(t, wantRegVal, a.written[1]) } func TestPCA953x_pca953xCalcPsc(t *testing.T) { diff --git a/drivers/i2c/pca9685_driver.go b/drivers/i2c/pca9685_driver.go index 34ea629cf..74df04fed 100644 --- a/drivers/i2c/pca9685_driver.go +++ b/drivers/i2c/pca9685_driver.go @@ -162,7 +162,7 @@ func (p *PCA9685Driver) SetPWMFreq(freq float32) error { // Put oscillator in sleep mode, clear bit 7 here to avoid overwriting // previous setting newmode := (oldmode & 0x7F) | 0x10 - if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), byte(newmode)}); err != nil { + if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), newmode}); err != nil { return err } // Write prescaler value @@ -170,14 +170,14 @@ func (p *PCA9685Driver) SetPWMFreq(freq float32) error { return err } // Put back to old settings - if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), byte(oldmode)}); err != nil { + if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), oldmode}); err != nil { return err } time.Sleep(5 * time.Millisecond) // Enable response to All Call address, enable auto-increment, clear restart - if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), byte(oldmode | 0x80)}); err != nil { + if _, err := p.connection.Write([]byte{byte(PCA9685_MODE1), oldmode | 0x80}); err != nil { return err } diff --git a/drivers/i2c/pca9685_driver_test.go b/drivers/i2c/pca9685_driver_test.go index ca448d447..0c0b97852 100644 --- a/drivers/i2c/pca9685_driver_test.go +++ b/drivers/i2c/pca9685_driver_test.go @@ -15,8 +15,10 @@ import ( var _ gobot.Driver = (*PCA9685Driver)(nil) // and also the PwmWriter and ServoWriter interfaces -var _ gpio.PwmWriter = (*PCA9685Driver)(nil) -var _ gpio.ServoWriter = (*PCA9685Driver)(nil) +var ( + _ gpio.PwmWriter = (*PCA9685Driver)(nil) + _ gpio.ServoWriter = (*PCA9685Driver)(nil) +) func initTestPCA9685DriverWithStubbedAdaptor() (*PCA9685Driver, *i2cTestAdaptor) { a := newI2cTestAdaptor() diff --git a/drivers/i2c/pcf8583_driver.go b/drivers/i2c/pcf8583_driver.go index 89e6be711..2db6821b2 100644 --- a/drivers/i2c/pcf8583_driver.go +++ b/drivers/i2c/pcf8583_driver.go @@ -49,7 +49,7 @@ const ( // 0 1 0 1 0 0 0 A0|rd // Lowest bit (rd) is mapped to switch between write(0)/read(1), it is not part of the "real" address. // -// PCF8583 is mainly compatible to PCF8593, so this driver should also work for PCF8593 except RAM calls +// # PCF8583 is mainly compatible to PCF8593, so this driver should also work for PCF8593 except RAM calls // // This driver was tested with Tinkerboard. type PCF8583Driver struct { @@ -61,13 +61,14 @@ type PCF8583Driver struct { // NewPCF8583Driver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver -// i2c.WithPCF8583Mode(PCF8583Control): mode of this driver // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver +// i2c.WithPCF8583Mode(PCF8583Control): mode of this driver func NewPCF8583Driver(c Connector, options ...func(Config)) *PCF8583Driver { d := &PCF8583Driver{ Driver: NewDriver(c, "PCF8583", pcf8583DefaultAddress), @@ -149,7 +150,8 @@ func (d *PCF8583Driver) WriteTime(val time.Time) error { } year, month, day := val.Date() err = d.connection.WriteBlockData(uint8(pcf8583Reg_CTRL), - []byte{ctrlRegVal | uint8(pcf8583CtrlStopCounting), + []byte{ + ctrlRegVal | uint8(pcf8583CtrlStopCounting), pcf8583encodeBcd(uint8(val.Nanosecond() / 1000000 / 10)), // sub seconds in 1/10th seconds pcf8583encodeBcd(uint8(val.Second())), pcf8583encodeBcd(uint8(val.Minute())), @@ -216,7 +218,8 @@ func (d *PCF8583Driver) WriteCounter(val int32) error { return fmt.Errorf("%s: can't write counter because the device is in wrong mode 0x%02x", d.name, ctrlRegVal) } err = d.connection.WriteBlockData(uint8(pcf8583Reg_CTRL), - []byte{ctrlRegVal | uint8(pcf8583CtrlStopCounting), // stop + []byte{ + ctrlRegVal | uint8(pcf8583CtrlStopCounting), // stop pcf8583encodeBcd(uint8(val % 100)), // 2 lowest digits pcf8583encodeBcd(uint8((val / 100) % 100)), // 2 middle digits pcf8583encodeBcd(uint8((val / 10000) % 100)), // 2 highest digits @@ -329,13 +332,13 @@ func pcf8583encodeBcd(val byte) byte { log.Printf("PCF8583 BCD value (%d) exceeds limit of 99, now limited.", val) } } - hi, lo := byte(val/10), byte(val%10) + hi, lo := val/10, val%10 return hi<<4 | lo } func pcf8583decodeBcd(bcd byte) byte { // 0x12 => decimal 12 - hi, lo := byte(bcd>>4), byte(bcd&0x0f) + hi, lo := bcd>>4, bcd&0x0f if hi > 9 { hi = 9 if pcf8583Debug { diff --git a/drivers/i2c/pcf8583_driver_test.go b/drivers/i2c/pcf8583_driver_test.go index a772b1192..a2a4a93ea 100644 --- a/drivers/i2c/pcf8583_driver_test.go +++ b/drivers/i2c/pcf8583_driver_test.go @@ -68,7 +68,7 @@ func TestPCF8583CommandsReadTime(t *testing.T) { d, a := initTestPCF8583WithStubbedAdaptor() d.yearOffset = 2019 milliSec := 550 * time.Millisecond // 0.55 sec = 550 ms - want := time.Date(2021, time.December, 24, 18, 00, 00, int(milliSec), time.UTC) + want := time.Date(2021, time.December, 24, 18, 0, 0, int(milliSec), time.UTC) reg0Val := uint8(0x00) // clock mode 32.768 kHz reg1Val := uint8(0x55) // BCD: 1/10 and 1/100 sec (55) reg2Val := uint8(0x00) // BCD: 10 and 1 sec (00) @@ -152,7 +152,7 @@ func TestPCF8583CommandsReadCounter(t *testing.T) { func TestPCF8583CommandsWriteRAM(t *testing.T) { // arrange d, _ := initTestPCF8583WithStubbedAdaptor() - var addressValue = map[string]interface{}{ + addressValue := map[string]interface{}{ "address": uint8(0x12), "val": uint8(0x45), } @@ -165,7 +165,7 @@ func TestPCF8583CommandsWriteRAM(t *testing.T) { func TestPCF8583CommandsReadRAM(t *testing.T) { // arrange d, _ := initTestPCF8583WithStubbedAdaptor() - var address = map[string]interface{}{ + address := map[string]interface{}{ "address": uint8(0x34), } // act @@ -609,5 +609,5 @@ func TestPCF8583_initializeWithModeSwitch(t *testing.T) { assert.Equal(t, 3, len(a.written)) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[0]) assert.Equal(t, uint8(pcf8583Reg_CTRL), a.written[1]) - assert.Equal(t, uint8(wantReg0Val), a.written[2]) + assert.Equal(t, wantReg0Val, a.written[2]) } diff --git a/drivers/i2c/pcf8591_driver.go b/drivers/i2c/pcf8591_driver.go index b62942734..e686429ad 100644 --- a/drivers/i2c/pcf8591_driver.go +++ b/drivers/i2c/pcf8591_driver.go @@ -15,8 +15,10 @@ const ( pcf8591Debug = false ) -type pcf8591Mode uint8 -type PCF8591Channel uint8 +type ( + pcf8591Mode uint8 + PCF8591Channel uint8 +) const ( pcf8591_CHAN0 PCF8591Channel = 0x00 @@ -96,7 +98,6 @@ var pcf8591ModeMap = map[string]pcf8591ModeChan{ // https://www.adafruit.com/product/4648 // // This driver was tested with Tinkerboard and the YL-40 driver. -// type PCF8591Driver struct { *Driver lastCtrlByte byte @@ -109,13 +110,14 @@ type PCF8591Driver struct { // NewPCF8591Driver creates a new driver with specified i2c interface // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver -// i2c.WithPCF8591With400kbitStabilization(uint8, uint8): stabilize read in 400 kbit mode // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver +// i2c.WithPCF8591With400kbitStabilization(uint8, uint8): stabilize read in 400 kbit mode func NewPCF8591Driver(c Connector, options ...func(Config)) *PCF8591Driver { p := &PCF8591Driver{ Driver: NewDriver(c, "PCF8591", pcf8591DefaultAddress), @@ -182,11 +184,11 @@ func WithPCF8591ForceRefresh(val uint8) func(Config) { // An i2c bus extender (LTC4311) don't fix it (it seems rather the opposite). // // This leads to following behavior: -// * the control byte is not written correctly -// * the transition process takes an additional cycle, very often -// * some circuits takes one cycle longer transition time in addition -// * reading more than one byte by Read([]byte), e.g. to calculate an average, is not sufficient, -// because some missing integration steps in each conversion (each byte value is a little bit lower than expected) +// - the control byte is not written correctly +// - the transition process takes an additional cycle, very often +// - some circuits takes one cycle longer transition time in addition +// - reading more than one byte by Read([]byte), e.g. to calculate an average, is not sufficient, +// because some missing integration steps in each conversion (each byte value is a little bit lower than expected) // // So, for default, we drop the first three bytes to get the right value. func (p *PCF8591Driver) AnalogRead(description string) (value int, err error) { diff --git a/drivers/i2c/sht2x_driver.go b/drivers/i2c/sht2x_driver.go index 3c1e36e1e..abbf376b6 100644 --- a/drivers/i2c/sht2x_driver.go +++ b/drivers/i2c/sht2x_driver.go @@ -165,10 +165,10 @@ func (d *SHT2xDriver) readSensor(cmd byte) (read uint16, err error) { return } - //Hang out while measurement is taken. 85ms max, page 9 of datasheet. + // Hang out while measurement is taken. 85ms max, page 9 of datasheet. time.Sleep(85 * time.Millisecond) - //Comes back in three bytes, data(MSB) / data(LSB) / Checksum + // Comes back in three bytes, data(MSB) / data(LSB) / Checksum buf := make([]byte, 3) counter := 0 for { @@ -188,7 +188,7 @@ func (d *SHT2xDriver) readSensor(cmd byte) (read uint16, err error) { time.Sleep(1 * time.Millisecond) } - //Store the result + // Store the result crc := crc8.Checksum(buf[0:2], d.crcTable) if buf[2] != crc { err = errors.New("Invalid crc") @@ -221,12 +221,12 @@ func (d *SHT2xDriver) sendAccuracy() error { return err } - userRegister &= 0x7e //Turn off the resolution bits + userRegister &= 0x7e // Turn off the resolution bits acc := d.accuracy - acc &= 0x81 //Turn off all other bits but resolution bits - userRegister |= acc //Mask in the requested resolution bits + acc &= 0x81 // Turn off all other bits but resolution bits + userRegister |= acc // Mask in the requested resolution bits - //Request a write to user register + // Request a write to user register if _, err := d.connection.Write([]byte{SHT2xWriteUserReg, userRegister}); err != nil { return err } diff --git a/drivers/i2c/ssd1306_driver.go b/drivers/i2c/ssd1306_driver.go index 157d21536..9a8e92944 100644 --- a/drivers/i2c/ssd1306_driver.go +++ b/drivers/i2c/ssd1306_driver.go @@ -26,13 +26,13 @@ const ( ssd1306SetComOutput8 = 0xC8 ssd1306SetContrast = 0x81 // scrolling commands - //ssd1306ContinuousHScrollRight = 0x26 - //ssd1306ContinuousHScrollLeft = 0x27 - //ssd1306ContinuousVHScrollRight = 0x29 - //ssd1306ContinuousVHScrollLeft = 0x2A - //ssd1306StopScroll = 0x2E - //ssd1306StartScroll = 0x2F - // adressing settings commands + // ssd1306ContinuousHScrollRight = 0x26 + // ssd1306ContinuousHScrollLeft = 0x27 + // ssd1306ContinuousVHScrollRight = 0x29 + // ssd1306ContinuousVHScrollLeft = 0x2A + // ssd1306StopScroll = 0x2E + // ssd1306StartScroll = 0x2F + // addressing settings commands ssd1306SetMemoryAddressingMode = 0x20 ssd1306ColumnAddr = 0x21 ssd1306PageAddr = 0x22 @@ -235,14 +235,14 @@ func NewSSD1306Driver(c Connector, options ...func(Config)) *SSD1306Driver { return map[string]interface{}{} }) s.AddCommand("SetContrast", func(params map[string]interface{}) interface{} { - contrast := byte(params["contrast"].(byte)) + contrast := params["contrast"].(byte) err := s.SetContrast(contrast) return map[string]interface{}{"err": err} }) s.AddCommand("Set", func(params map[string]interface{}) interface{} { - x := int(params["x"].(int)) - y := int(params["y"].(int)) - c := int(params["c"].(int)) + x := params["x"].(int) + y := params["y"].(int) + c := params["c"].(int) s.Set(x, y, c) return nil }) diff --git a/drivers/i2c/ssd1306_driver_test.go b/drivers/i2c/ssd1306_driver_test.go index b140a9e5a..ef6ae5590 100644 --- a/drivers/i2c/ssd1306_driver_test.go +++ b/drivers/i2c/ssd1306_driver_test.go @@ -15,9 +15,13 @@ import ( // and tests all implementations, so no further tests needed here for gobot.Driver interface var _ gobot.Driver = (*SSD1306Driver)(nil) -func initTestSSD1306DriverWithStubbedAdaptor(width, height int, externalVCC bool) (*SSD1306Driver, *i2cTestAdaptor) { +func initTestSSD1306DriverWithStubbedAdaptor( + width, height int, + externalVCC bool, //nolint:unparam // keep for tests +) (*SSD1306Driver, *i2cTestAdaptor) { a := newI2cTestAdaptor() - d := NewSSD1306Driver(a, WithSSD1306DisplayWidth(width), WithSSD1306DisplayHeight(height), WithSSD1306ExternalVCC(externalVCC)) + d := NewSSD1306Driver(a, WithSSD1306DisplayWidth(width), WithSSD1306DisplayHeight(height), + WithSSD1306ExternalVCC(externalVCC)) if err := d.Start(); err != nil { panic(err) } diff --git a/drivers/i2c/th02_driver.go b/drivers/i2c/th02_driver.go index 4edee7900..bf29309e7 100644 --- a/drivers/i2c/th02_driver.go +++ b/drivers/i2c/th02_driver.go @@ -40,7 +40,7 @@ const ( th02Reg_Config = 0x03 th02Reg_ID = 0x11 - //th02Status_ReadyBit = 0x01 // D0 is /RDY + // th02Status_ReadyBit = 0x01 // D0 is /RDY th02Config_StartBit = 0x01 // D0 is START th02Config_HeatBit = 0x02 // D1 is HEAT @@ -50,8 +50,8 @@ const ( // Accuracy constants for the TH02 devices (deprecated, use WithFastMode() instead) const ( - TH02HighAccuracy = 0 //High Accuracy (T: 14 bit, H: 12 bit), normal (35 ms) - TH02LowAccuracy = 1 //Lower Accuracy (T: 13 bit, H: 11 bit), fast (18 ms) + TH02HighAccuracy = 0 // High Accuracy (T: 14 bit, H: 12 bit), normal (35 ms) + TH02LowAccuracy = 1 // Lower Accuracy (T: 13 bit, H: 11 bit), fast (18 ms) ) // TH02Driver is a Driver for a TH02 humidity and temperature sensor @@ -123,7 +123,7 @@ func (s *TH02Driver) SerialNumber() (uint8, error) { defer s.mutex.Unlock() ret, err := s.connection.ReadByteData(th02Reg_ID) - return uint8(ret) >> 4, err + return ret >> 4, err } // FastMode returns true if the fast mode is enabled in the device @@ -185,7 +185,6 @@ func (s *TH02Driver) Sample() (temperature float32, relhumidity float32, _ error } return temperature, relhumidity, nil - } func (s *TH02Driver) createConfig(measurement bool, readTemp bool) byte { diff --git a/drivers/i2c/th02_driver_test.go b/drivers/i2c/th02_driver_test.go index 51a46c66e..44501e82e 100644 --- a/drivers/i2c/th02_driver_test.go +++ b/drivers/i2c/th02_driver_test.go @@ -59,7 +59,7 @@ func TestTH02SetAccuracy(t *testing.T) { } func TestTH02WithFastMode(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { value int want bool }{ @@ -84,7 +84,7 @@ func TestTH02FastMode(t *testing.T) { // * write config register address (0x03) // * read register content // * if sixth bit (D5) is set, the fast mode is configured on, otherwise off - var tests = map[string]struct { + tests := map[string]struct { read uint8 want bool }{ @@ -116,7 +116,7 @@ func TestTH02SetHeater(t *testing.T) { // * write config register address (0x03) // * prepare config value by set/reset the heater bit (0x02, D1) // * write the config value - var tests = map[string]struct { + tests := map[string]struct { heater bool want uint8 }{ @@ -144,7 +144,7 @@ func TestTH02Heater(t *testing.T) { // * write config register address (0x03) // * read register content // * if second bit (D1) is set, the heater is configured on, otherwise off - var tests = map[string]struct { + tests := map[string]struct { read uint8 want bool }{ @@ -207,7 +207,7 @@ func TestTH02Sample(t *testing.T) { // test table according to data sheet page 15, 17 // operating range of the temperature sensor is -40..85 °C (F-grade 0..70 °C) - var tests = map[string]struct { + tests := map[string]struct { hData uint16 tData uint16 wantRH float32 @@ -298,8 +298,8 @@ func TestTH02Sample(t *testing.T) { temp, rh, err := d.Sample() // assert assert.Nil(t, err) - assert.Equal(t, float32(tc.wantRH), rh) - assert.Equal(t, float32(tc.wantT), temp) + assert.Equal(t, tc.wantRH, rh) + assert.Equal(t, tc.wantT, temp) }) } } @@ -309,7 +309,7 @@ func TestTH02_readData(t *testing.T) { var callCounter int - var tests = map[string]struct { + tests := map[string]struct { rd func([]byte) (int, error) wr func([]byte) (int, error) rtn uint16 @@ -455,7 +455,7 @@ func TestTH02_waitForReadyFailOnReadError(t *testing.T) { func TestTH02_createConfig(t *testing.T) { d := &TH02Driver{} - var tests = map[string]struct { + tests := map[string]struct { meas bool fast bool readTemp bool diff --git a/drivers/i2c/tsl2561_driver.go b/drivers/i2c/tsl2561_driver.go index 7bc4fa8b6..cc3ff7160 100644 --- a/drivers/i2c/tsl2561_driver.go +++ b/drivers/i2c/tsl2561_driver.go @@ -121,18 +121,19 @@ type TSL2561Driver struct { // NewTSL2561Driver creates a new driver for the TSL2561 device. // // Params: -// c Connector - the Adaptor to use with this Driver +// +// c Connector - the Adaptor to use with this Driver // // Optional params: -// i2c.WithBus(int): bus to use with this driver -// i2c.WithAddress(int): address to use with this driver -// i2c.WithTSL2561Gain1X: sets the gain to 1X -// i2c.WithTSL2561Gain16X: sets the gain to 16X -// i2c.WithTSL2561AutoGain: turns on auto gain -// i2c.WithTSL2561IntegrationTime13MS: sets integration time to 13ms -// i2c.WithTSL2561IntegrationTime101MS: sets integration time to 101ms -// i2c.WithTSL2561IntegrationTime402MS: sets integration time to 402ms // +// i2c.WithBus(int): bus to use with this driver +// i2c.WithAddress(int): address to use with this driver +// i2c.WithTSL2561Gain1X: sets the gain to 1X +// i2c.WithTSL2561Gain16X: sets the gain to 16X +// i2c.WithTSL2561AutoGain: turns on auto gain +// i2c.WithTSL2561IntegrationTime13MS: sets integration time to 13ms +// i2c.WithTSL2561IntegrationTime101MS: sets integration time to 101ms +// i2c.WithTSL2561IntegrationTime402MS: sets integration time to 402ms func NewTSL2561Driver(c Connector, options ...func(Config)) *TSL2561Driver { d := &TSL2561Driver{ Driver: NewDriver(c, "TSL2561", TSL2561AddressFloat), @@ -282,7 +283,7 @@ func (d *TSL2561Driver) GetLuminocity() (broadband uint16, ir uint16, err error) } else { // If we've already adjusted the gain once, just return the new results. // This avoids endless loops where a value is at one extreme pre-gain, - // and the the other extreme post-gain + // and the other extreme post-gain valid = true } diff --git a/drivers/i2c/tsl2561_driver_test.go b/drivers/i2c/tsl2561_driver_test.go index 2c363b997..7b60391a7 100644 --- a/drivers/i2c/tsl2561_driver_test.go +++ b/drivers/i2c/tsl2561_driver_test.go @@ -133,7 +133,7 @@ func TestTSL2561DriverEvenMoreOptions(t *testing.T) { assert.NotNil(t, d) assert.False(t, d.autoGain) - assert.Equal(t, TSL2561Gain(TSL2561Gain1X), d.gain) + assert.Equal(t, TSL2561Gain1X, d.gain) assert.Equal(t, TSL2561IntegrationTime13MS, d.integrationTime) } diff --git a/drivers/i2c/wiichuck_driver.go b/drivers/i2c/wiichuck_driver.go index 45b6c7eda..fc2d305bd 100644 --- a/drivers/i2c/wiichuck_driver.go +++ b/drivers/i2c/wiichuck_driver.go @@ -108,7 +108,7 @@ func (w *WiichuckDriver) setJoystickDefaultValue(joystickAxis string, defaultVal // calculateJoystickValue returns distance between axis and origin func (w *WiichuckDriver) calculateJoystickValue(axis float64, origin float64) float64 { - return float64(axis - origin) + return axis - origin } // isEncrypted returns true if value is encrypted diff --git a/drivers/i2c/wiichuck_driver_test.go b/drivers/i2c/wiichuck_driver_test.go index f6da53d98..161dcd9d9 100644 --- a/drivers/i2c/wiichuck_driver_test.go +++ b/drivers/i2c/wiichuck_driver_test.go @@ -63,7 +63,6 @@ func TestWiichuckDriverStart(t *testing.T) { case <-time.After(100 * time.Millisecond): t.Errorf("origin not read correctly") } - } func TestWiichuckDriverHalt(t *testing.T) { diff --git a/drivers/i2c/yl40_driver.go b/drivers/i2c/yl40_driver.go index bc3d2a8b2..4509ddfeb 100644 --- a/drivers/i2c/yl40_driver.go +++ b/drivers/i2c/yl40_driver.go @@ -90,7 +90,7 @@ func NewYL40Driver(a Connector, options ...func(Config)) *YL40Driver { options = append(options, WithAddress(yl40DefaultAddress)) pcf := NewPCF8591Driver(a, options...) - ntc := aio.TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3950} //Ohm, R25=10k, B=3950 + ntc := aio.TemperatureSensorNtcConf{TC0: 25, R0: 10000.0, B: 3950} // Ohm, R25=10k, B=3950 defTempScaler := aio.TemperatureSensorNtcScaler(255, 1000, true, ntc) defConf := yl40Config{ diff --git a/drivers/i2c/yl40_driver_test.go b/drivers/i2c/yl40_driver_test.go index 0ad398a0f..a3e604403 100644 --- a/drivers/i2c/yl40_driver_test.go +++ b/drivers/i2c/yl40_driver_test.go @@ -19,7 +19,7 @@ func initTestYL40DriverWithStubbedAdaptor() (*YL40Driver, *i2cTestAdaptor) { func TestYL40Driver(t *testing.T) { // arrange, act yl := NewYL40Driver(newI2cTestAdaptor()) - //assert + // assert assert.NotNil(t, yl.PCF8591Driver) assert.Equal(t, time.Duration(0), yl.conf.sensors[YL40Bri].interval) assert.NotNil(t, yl.conf.sensors[YL40Bri].scaler) @@ -59,7 +59,7 @@ func TestYL40DriverWithYL40InputScaler(t *testing.T) { f2 := func(input int) (value float64) { return 0.2 } f3 := func(input int) (value float64) { return 0.3 } f4 := func(input int) (value float64) { return 0.4 } - //act + // act WithYL40InputScaler(YL40Bri, f1)(yl) WithYL40InputScaler(YL40Temp, f2)(yl) WithYL40InputScaler(YL40AIN2, f3)(yl) @@ -75,7 +75,7 @@ func TestYL40DriverWithYL40WithYL40OutputScaler(t *testing.T) { // arrange yl := NewYL40Driver(newI2cTestAdaptor()) fo := func(input float64) (value int) { return 123 } - //act + // act WithYL40OutputScaler(fo)(yl) // assert assert.True(t, fEqual(yl.conf.aOutScaler, fo)) diff --git a/drivers/spi/apa102.go b/drivers/spi/apa102.go index a56baf48d..5e12ddfb1 100644 --- a/drivers/spi/apa102.go +++ b/drivers/spi/apa102.go @@ -15,17 +15,18 @@ type APA102Driver struct { // NewAPA102Driver creates a new Gobot Driver for APA102 RGB LEDs. // // Params: -// a *Adaptor - the Adaptor to use with this Driver. -// count int - how many LEDs are in the array controlled by this driver. -// bright - the default brightness to apply for all LEDs (must be between 0 and 31). +// +// a *Adaptor - the Adaptor to use with this Driver. +// count int - how many LEDs are in the array controlled by this driver. +// bright - the default brightness to apply for all LEDs (must be between 0 and 31). // // Optional params: -// spi.WithBusNumber(int): bus to use with this driver. -// spi.WithChipNumber(int): chip to use with this driver. -// spi.WithMode(int): mode to use with this driver. -// spi.WithBitCount(int): number of bits to use with this driver. -// spi.WithSpeed(int64): speed in Hz to use with this driver. // +// spi.WithBusNumber(int): bus to use with this driver. +// spi.WithChipNumber(int): chip to use with this driver. +// spi.WithMode(int): mode to use with this driver. +// spi.WithBitCount(int): number of bits to use with this driver. +// spi.WithSpeed(int64): speed in Hz to use with this driver. func NewAPA102Driver(a Connector, count int, bright uint8, options ...func(Config)) *APA102Driver { d := &APA102Driver{ Driver: NewDriver(a, "APA102"), @@ -72,7 +73,7 @@ func (d *APA102Driver) Draw() error { if c.A != 0 { tx[j] = 0xe0 + byte(math.Min(float64(c.A), 31)) } else { - tx[j] = 0xe0 + byte(d.brightness) + tx[j] = 0xe0 + d.brightness } tx[j+1] = c.B tx[j+2] = c.G diff --git a/drivers/spi/helpers_test.go b/drivers/spi/helpers_test.go index c66c310c0..66d1d2301 100644 --- a/drivers/spi/helpers_test.go +++ b/drivers/spi/helpers_test.go @@ -8,12 +8,14 @@ import ( ) // make sure that this SpiBusAdaptor fulfills all the required interfaces -var _ Connector = (*spiTestAdaptor)(nil) -var _ gobot.Connection = (*spiTestAdaptor)(nil) +var ( + _ Connector = (*spiTestAdaptor)(nil) + _ gobot.Connection = (*spiTestAdaptor)(nil) +) type spiTestAdaptor struct { sys *system.Accesser - //busNum int + // busNum int spiConnectErr bool spi *system.MockSpiAccess connection Connection @@ -34,7 +36,7 @@ func (a *spiTestAdaptor) GetSpiConnection(busNum, chipNum, mode, bits int, maxSp if a.spiConnectErr { return nil, fmt.Errorf("Invalid SPI connection in helper") } - //a.busNum = busNum + // a.busNum = busNum sysdev, err := a.sys.NewSpiDevice(busNum, chipNum, mode, bits, maxSpeed) a.connection = NewConnection(sysdev) return a.connection, err diff --git a/drivers/spi/mcp3002.go b/drivers/spi/mcp3002.go index 4d1d2a9f9..5358f67e6 100644 --- a/drivers/spi/mcp3002.go +++ b/drivers/spi/mcp3002.go @@ -16,15 +16,16 @@ type MCP3002Driver struct { // NewMCP3002Driver creates a new Gobot Driver for MCP3002 A/D converter // // Params: -// a *Adaptor - the Adaptor to use with this Driver +// +// a *Adaptor - the Adaptor to use with this Driver // // Optional params: -// spi.WithBusNumber(int): bus to use with this driver -// spi.WithChipNumber(int): chip to use with this driver -// spi.WithMode(int): mode to use with this driver -// spi.WithBitCount(int): number of bits to use with this driver -// spi.WithSpeed(int64): speed in Hz to use with this driver // +// spi.WithBusNumber(int): bus to use with this driver +// spi.WithChipNumber(int): chip to use with this driver +// spi.WithMode(int): mode to use with this driver +// spi.WithBitCount(int): number of bits to use with this driver +// spi.WithSpeed(int64): speed in Hz to use with this driver func NewMCP3002Driver(a Connector, options ...func(Config)) *MCP3002Driver { d := &MCP3002Driver{ Driver: NewDriver(a, "MCP3002"), diff --git a/drivers/spi/mcp3002_test.go b/drivers/spi/mcp3002_test.go index c1a53a751..abbe0129f 100644 --- a/drivers/spi/mcp3002_test.go +++ b/drivers/spi/mcp3002_test.go @@ -37,7 +37,7 @@ func TestNewMCP3002Driver(t *testing.T) { } func TestMCP3002Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3004.go b/drivers/spi/mcp3004.go index 8c262b12f..eb5d77ee8 100644 --- a/drivers/spi/mcp3004.go +++ b/drivers/spi/mcp3004.go @@ -16,15 +16,16 @@ type MCP3004Driver struct { // NewMCP3004Driver creates a new Gobot Driver for MCP3004 A/D converter // // Params: -// a *Adaptor - the Adaptor to use with this Driver +// +// a *Adaptor - the Adaptor to use with this Driver // // Optional params: -// spi.WithBusNumber(int): bus to use with this driver -// spi.WithChipNumber(int): chip to use with this driver -// spi.WithMode(int): mode to use with this driver -// spi.WithBitCount(int): number of bits to use with this driver -// spi.WithSpeed(int64): speed in Hz to use with this driver // +// spi.WithBusNumber(int): bus to use with this driver +// spi.WithChipNumber(int): chip to use with this driver +// spi.WithMode(int): mode to use with this driver +// spi.WithBitCount(int): number of bits to use with this driver +// spi.WithSpeed(int64): speed in Hz to use with this driver func NewMCP3004Driver(a Connector, options ...func(Config)) *MCP3004Driver { d := &MCP3004Driver{ Driver: NewDriver(a, "MCP3004"), diff --git a/drivers/spi/mcp3004_test.go b/drivers/spi/mcp3004_test.go index 49f0f797b..6cc1e82f6 100644 --- a/drivers/spi/mcp3004_test.go +++ b/drivers/spi/mcp3004_test.go @@ -37,7 +37,7 @@ func TestNewMCP3004Driver(t *testing.T) { } func TestMCP3004Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3008.go b/drivers/spi/mcp3008.go index c5e037662..15a1f1622 100644 --- a/drivers/spi/mcp3008.go +++ b/drivers/spi/mcp3008.go @@ -16,15 +16,16 @@ type MCP3008Driver struct { // NewMCP3008Driver creates a new Gobot Driver for MCP3008Driver A/D converter // // Params: -// a *Adaptor - the Adaptor to use with this Driver +// +// a *Adaptor - the Adaptor to use with this Driver // // Optional params: -// spi.WithBusNumber(int): bus to use with this driver -// spi.WithChipNumber(int): chip to use with this driver -// spi.WithMode(int): mode to use with this driver -// spi.WithBitCount(int): number of bits to use with this driver -// spi.WithSpeed(int64): speed in Hz to use with this driver // +// spi.WithBusNumber(int): bus to use with this driver +// spi.WithChipNumber(int): chip to use with this driver +// spi.WithMode(int): mode to use with this driver +// spi.WithBitCount(int): number of bits to use with this driver +// spi.WithSpeed(int64): speed in Hz to use with this driver func NewMCP3008Driver(a Connector, options ...func(Config)) *MCP3008Driver { d := &MCP3008Driver{ Driver: NewDriver(a, "MCP3008"), diff --git a/drivers/spi/mcp3008_test.go b/drivers/spi/mcp3008_test.go index 1e7ad1958..e16230adc 100644 --- a/drivers/spi/mcp3008_test.go +++ b/drivers/spi/mcp3008_test.go @@ -37,7 +37,7 @@ func TestNewMCP3008Driver(t *testing.T) { } func TestMCP3008Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3202_test.go b/drivers/spi/mcp3202_test.go index 787e496fb..c5fa0ba92 100644 --- a/drivers/spi/mcp3202_test.go +++ b/drivers/spi/mcp3202_test.go @@ -37,7 +37,7 @@ func TestNewMCP3202Driver(t *testing.T) { } func TestMCP3202Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3204_test.go b/drivers/spi/mcp3204_test.go index 6f37dbbed..e2bcc2e92 100644 --- a/drivers/spi/mcp3204_test.go +++ b/drivers/spi/mcp3204_test.go @@ -37,7 +37,7 @@ func TestNewMCP3204Driver(t *testing.T) { } func TestMCP3204Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3208_test.go b/drivers/spi/mcp3208_test.go index 62c49ccb4..64d3a6395 100644 --- a/drivers/spi/mcp3208_test.go +++ b/drivers/spi/mcp3208_test.go @@ -37,7 +37,7 @@ func TestNewMCP3208Driver(t *testing.T) { } func TestMCP3208Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/mcp3304_test.go b/drivers/spi/mcp3304_test.go index 71dce0381..0740ddd45 100644 --- a/drivers/spi/mcp3304_test.go +++ b/drivers/spi/mcp3304_test.go @@ -37,7 +37,7 @@ func TestNewMCP3304Driver(t *testing.T) { } func TestMCP3304Read(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { chanNum int simRead []byte want int diff --git a/drivers/spi/spi_config.go b/drivers/spi/spi_config.go index 1e5f344d7..25142145b 100644 --- a/drivers/spi/spi_config.go +++ b/drivers/spi/spi_config.go @@ -15,7 +15,8 @@ func NewConfig() Config { chip: NotInitialized, mode: NotInitialized, bits: NotInitialized, - speed: NotInitialized} + speed: NotInitialized, + } } // WithBusNumber sets which bus to use as a optional param. diff --git a/drivers/spi/spi_driver_test.go b/drivers/spi/spi_driver_test.go index 7f96e487e..a91fefcf5 100644 --- a/drivers/spi/spi_driver_test.go +++ b/drivers/spi/spi_driver_test.go @@ -10,7 +10,7 @@ import ( var _ gobot.Driver = (*Driver)(nil) -func initTestDriverWithStubbedAdaptor() (*Driver, *spiTestAdaptor) { +func initTestDriverWithStubbedAdaptor() (*Driver, *spiTestAdaptor) { //nolint:unparam // keep for further tests a := newSpiTestAdaptor() d := NewDriver(a, "SPI_BASIC") if err := d.Start(); err != nil { diff --git a/drivers/spi/ssd1306_driver.go b/drivers/spi/ssd1306_driver.go index 377a0a5be..e57ac28a5 100644 --- a/drivers/spi/ssd1306_driver.go +++ b/drivers/spi/ssd1306_driver.go @@ -170,14 +170,14 @@ func NewSSD1306Driver(a gobot.Adaptor, options ...func(Config)) *SSD1306Driver { return map[string]interface{}{"err": err} }) s.AddCommand("SetContrast", func(params map[string]interface{}) interface{} { - contrast := byte(params["contrast"].(byte)) + contrast := params["contrast"].(byte) err := s.SetContrast(contrast) return map[string]interface{}{"err": err} }) s.AddCommand("Set", func(params map[string]interface{}) interface{} { - x := int(params["x"].(int)) - y := int(params["y"].(int)) - c := int(params["c"].(int)) + x := params["x"].(int) + y := params["y"].(int) + c := params["c"].(int) s.Set(x, y, c) return nil }) diff --git a/drivers/spi/ssd1306_driver_test.go b/drivers/spi/ssd1306_driver_test.go index a8b2caf87..7f01b1502 100644 --- a/drivers/spi/ssd1306_driver_test.go +++ b/drivers/spi/ssd1306_driver_test.go @@ -61,21 +61,25 @@ func (t *gpioTestAdaptor) ServoWrite(string, byte) (err error) { defer t.mtx.Unlock() return t.testAdaptorServoWrite() } + func (t *gpioTestAdaptor) PwmWrite(string, byte) (err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorPwmWrite() } + func (t *gpioTestAdaptor) AnalogRead(string) (val int, err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorAnalogRead() } + func (t *gpioTestAdaptor) DigitalRead(string) (val int, err error) { t.mtx.Lock() defer t.mtx.Unlock() return t.testAdaptorDigitalRead() } + func (t *gpioTestAdaptor) DigitalWrite(string, byte) (err error) { t.mtx.Lock() defer t.mtx.Unlock() diff --git a/examples/bb8-collision.go b/examples/bb8-collision.go index 63eb6b865..0b4df325d 100644 --- a/examples/bb8-collision.go +++ b/examples/bb8-collision.go @@ -29,7 +29,6 @@ func main() { bb := bb8.NewDriver(bleAdaptor) work := func() { - bb.On("collision", func(data interface{}) { fmt.Printf("collision detected = %+v \n", data) bb.SetRGB(255, 0, 0) @@ -46,5 +45,4 @@ func main() { ) robot.Start() - } diff --git a/examples/edison_grove_button.go b/examples/edison_grove_button.go index a58270460..cd47cc570 100644 --- a/examples/edison_grove_button.go +++ b/examples/edison_grove_button.go @@ -26,7 +26,6 @@ func main() { button.On(gpio.ButtonRelease, func(data interface{}) { fmt.Println("Off!") }) - } robot := gobot.NewRobot("bot", diff --git a/examples/edison_grove_touch.go b/examples/edison_grove_touch.go index 96d63d30a..c44281fe2 100644 --- a/examples/edison_grove_touch.go +++ b/examples/edison_grove_touch.go @@ -26,7 +26,6 @@ func main() { touch.On(gpio.ButtonRelease, func(data interface{}) { fmt.Println("Off!") }) - } robot := gobot.NewRobot("blinkBot", diff --git a/examples/firmata_aip1640.go b/examples/firmata_aip1640.go index 2faad221a..a2e4527f6 100644 --- a/examples/firmata_aip1640.go +++ b/examples/firmata_aip1640.go @@ -23,7 +23,6 @@ import ( ) func main() { - firmataAdaptor := firmata.NewAdaptor(os.Args[1]) // In the WEMOS D1 Mini LED Matrix Shield clockPin = 14, dataPin = 13 aip1640 := gpio.NewAIP1640Driver(firmataAdaptor, "14", "13") diff --git a/examples/firmata_ssd1306.go b/examples/firmata_ssd1306.go index a65dcf233..14ad349db 100644 --- a/examples/firmata_ssd1306.go +++ b/examples/firmata_ssd1306.go @@ -26,7 +26,6 @@ func main() { stage := false work := func() { - gobot.Every(1*time.Second, func() { fmt.Println("displaying") oled.Clear() diff --git a/examples/firmata_temp36.go b/examples/firmata_temp36.go index abc95fa14..94fca35a4 100644 --- a/examples/firmata_temp36.go +++ b/examples/firmata_temp36.go @@ -14,11 +14,10 @@ package main import ( + "fmt" "os" "time" - "fmt" - "gobot.io/x/gobot/v2" "gobot.io/x/gobot/v2/platforms/firmata" ) diff --git a/examples/firmata_travis.go b/examples/firmata_travis.go index 970f9c8aa..f1e863b27 100644 --- a/examples/firmata_travis.go +++ b/examples/firmata_travis.go @@ -55,7 +55,7 @@ func checkTravis(robot *gobot.Robot) { resetLeds(robot) user := "hybridgroup" name := "gobot" - //name := "broken-arrow" + // name := "broken-arrow" fmt.Printf("Checking repo %s/%s\n", user, name) turnOn(robot, "blue") resp, err := http.Get(fmt.Sprintf("https://api.travis-ci.org/repos/%s/%s.json", user, name)) diff --git a/examples/gopigo3_servo.go b/examples/gopigo3_servo.go index 0cd08e18b..dbb943cb8 100644 --- a/examples/gopigo3_servo.go +++ b/examples/gopigo3_servo.go @@ -27,7 +27,6 @@ func main() { fmt.Println("Turning", i) servo.Move(i) }) - } robot := gobot.NewRobot("gopigo3servo", diff --git a/examples/jetson-nano_blink.go b/examples/jetson-nano_blink.go index 9174565e0..cd5632e49 100644 --- a/examples/jetson-nano_blink.go +++ b/examples/jetson-nano_blink.go @@ -31,5 +31,4 @@ func main() { ) robot.Start() - } diff --git a/examples/jetson-nano_servo.go b/examples/jetson-nano_servo.go index 9a2278c0c..064589ffc 100644 --- a/examples/jetson-nano_servo.go +++ b/examples/jetson-nano_servo.go @@ -21,7 +21,6 @@ import ( ) func main() { - jetsonAdaptor := jetson.NewAdaptor() servo := gpio.NewServoDriver(jetsonAdaptor, "32") @@ -29,7 +28,6 @@ func main() { flg := true work := func() { gobot.Every(100*time.Millisecond, func() { - log.Println("Turning", counter) servo.Move(uint8(counter)) if counter == 140 { @@ -42,10 +40,8 @@ func main() { counter = counter + 1 } else { counter = counter - 1 - } }) - } robot := gobot.NewRobot("Jetsonservo", diff --git a/examples/joystick_xboxone.go b/examples/joystick_xboxone.go index a680529e6..883a4d5f9 100644 --- a/examples/joystick_xboxone.go +++ b/examples/joystick_xboxone.go @@ -18,7 +18,6 @@ func main() { joystick := joystick.NewDriver(joystickAdaptor, joystick.XboxOne) work := func() { - // start button joystick.On(joystick.Event("start_press"), func(data interface{}) { fmt.Println("start_press") @@ -117,7 +116,7 @@ func main() { fmt.Println("lb_release") }) - //rb button + // rb button joystick.On(joystick.Event("rb_press"), func(data interface{}) { fmt.Println("rb_press") }) @@ -130,7 +129,7 @@ func main() { fmt.Println("right_x", data) }) - //ry stick + // ry stick joystick.On(joystick.Event("right_y"), func(data interface{}) { fmt.Println("right_y", data) }) @@ -143,12 +142,12 @@ func main() { fmt.Println("right_stick_release") }) - //lx stick + // lx stick joystick.On(joystick.Event("left_x"), func(data interface{}) { fmt.Println("left_x", data) }) - //ly stick + // ly stick joystick.On(joystick.Event("left_y"), func(data interface{}) { fmt.Println("left_y", data) }) @@ -160,7 +159,6 @@ func main() { joystick.On(joystick.Event("left_stick_release"), func(data interface{}) { fmt.Println("left_stick_release") }) - } robot := gobot.NewRobot("joystickBot", diff --git a/examples/nanopi_direct_pin_event.go b/examples/nanopi_direct_pin_event.go index 39c2a2c81..f29f4dd8d 100644 --- a/examples/nanopi_direct_pin_event.go +++ b/examples/nanopi_direct_pin_event.go @@ -34,7 +34,6 @@ var ( // LED's: the output pins are wired to the cathode of a LED, the anode is wired with a resistor (70-130Ohm for 20mA) to VCC // Expected behavior: always one LED is on, the other in opposite state, if button is pressed for >2 seconds the state changes func main() { - board := nanopi.NewNeoAdaptor() work := func() { diff --git a/examples/nanopi_pca9533.go b/examples/nanopi_pca9533.go index 9c5f64bb1..73a5d614a 100644 --- a/examples/nanopi_pca9533.go +++ b/examples/nanopi_pca9533.go @@ -129,5 +129,4 @@ func initialize(pca *i2c.PCA953xDriver, led2FrequHz float32, led3FrequHz float32 if err != nil { fmt.Println("errW:", err) } - } diff --git a/examples/raspi_adafruit_dcmotor.go b/examples/raspi_adafruit_dcmotor.go index 8850a0bbc..9c3b668cc 100644 --- a/examples/raspi_adafruit_dcmotor.go +++ b/examples/raspi_adafruit_dcmotor.go @@ -49,7 +49,6 @@ func main() { work := func() { gobot.Every(5*time.Second, func() { - dcMotor := 2 // 0-based adafruitDCMotorRunner(adaFruit, dcMotor) }) diff --git a/examples/raspi_direct_pin_event.go b/examples/raspi_direct_pin_event.go index ccb44c0a9..0f50f3122 100644 --- a/examples/raspi_direct_pin_event.go +++ b/examples/raspi_direct_pin_event.go @@ -34,7 +34,6 @@ var ( // LED's: the output pins are wired to the cathode of a LED, the anode is wired with a resistor (70-130Ohm for 20mA) to VCC // Expected behavior: always one LED is on, the other in opposite state, if button is pressed for >2 seconds the state changes func main() { - board := raspi.NewAdaptor() work := func() { diff --git a/examples/raspi_generic.go b/examples/raspi_generic.go index 45ea5cbe3..319986cdc 100644 --- a/examples/raspi_generic.go +++ b/examples/raspi_generic.go @@ -74,7 +74,6 @@ func main() { if read && write { if reflect.DeepEqual(wData, rData) { fmt.Printf("EEPROM addr: %d equal: %v\n", eepromAddr, rData) - } else { fmt.Printf("EEPROM addr: %d wr: %v differ rd: %v\n", eepromAddr, wData, rData) } diff --git a/examples/raspi_hmc5883l.go b/examples/raspi_hmc5883l.go index 57c55b430..1a6e46dc1 100644 --- a/examples/raspi_hmc5883l.go +++ b/examples/raspi_hmc5883l.go @@ -27,7 +27,6 @@ func main() { work := func() { gobot.Every(200*time.Millisecond, func() { - // get heading in radians, to convert to degrees multiply by 180/math.Pi heading, _ := hmc5883l.Heading() fmt.Println("Heading", heading) diff --git a/examples/raspi_ina3221.go b/examples/raspi_ina3221.go index 001f41532..13f4786bd 100644 --- a/examples/raspi_ina3221.go +++ b/examples/raspi_ina3221.go @@ -16,12 +16,10 @@ import ( ) func main() { - r := raspi.NewAdaptor() ina := i2c.NewINA3221Driver(r) work := func() { - gobot.Every(5*time.Second, func() { for _, ch := range []i2c.INA3221Channel{i2c.INA3221Channel1, i2c.INA3221Channel2, i2c.INA3221Channel3} { val, err := ina.GetBusVoltage(ch) diff --git a/examples/raspi_pca9533.go b/examples/raspi_pca9533.go index a48ec1f4d..f71959f2f 100644 --- a/examples/raspi_pca9533.go +++ b/examples/raspi_pca9533.go @@ -129,5 +129,4 @@ func initialize(pca *i2c.PCA953xDriver, led2FrequHz float32, led3FrequHz float32 if err != nil { fmt.Println("errW:", err) } - } diff --git a/examples/raspi_ssd1306.go b/examples/raspi_ssd1306.go index fc08aa938..c43f58175 100644 --- a/examples/raspi_ssd1306.go +++ b/examples/raspi_ssd1306.go @@ -23,7 +23,6 @@ func main() { stage := false work := func() { - gobot.Every(1*time.Second, func() { oled.Clear() if stage { diff --git a/examples/raspi_stepper_move.go b/examples/raspi_stepper_move.go index 5c22b9b2a..61784039c 100644 --- a/examples/raspi_stepper_move.go +++ b/examples/raspi_stepper_move.go @@ -19,15 +19,15 @@ func main() { stepper := gpio.NewStepperDriver(r, [4]string{"7", "11", "13", "15"}, gpio.StepperModes.DualPhaseStepping, 2048) work := func() { - //set spped + // set spped stepper.SetSpeed(15) - //Move forward one revolution + // Move forward one revolution if err := stepper.Move(2048); err != nil { fmt.Println(err) } - //Move backward one revolution + // Move backward one revolution if err := stepper.Move(-2048); err != nil { fmt.Println(err) } diff --git a/examples/tinkerboard_adafruit1109_lcd_keys.go b/examples/tinkerboard_adafruit1109_lcd_keys.go index ae3f93fe9..305c09484 100644 --- a/examples/tinkerboard_adafruit1109_lcd_keys.go +++ b/examples/tinkerboard_adafruit1109_lcd_keys.go @@ -110,9 +110,7 @@ func main() { } } }) - }) - } robot := gobot.NewRobot("adaBot", diff --git a/examples/tinkerboard_direct_pin.go b/examples/tinkerboard_direct_pin.go index 4a3b43522..222425f60 100644 --- a/examples/tinkerboard_direct_pin.go +++ b/examples/tinkerboard_direct_pin.go @@ -62,7 +62,6 @@ func main() { } else { level = 1 } - }) } diff --git a/examples/tinkerboard_generic.go b/examples/tinkerboard_generic.go index e54948b4d..c76e9e16e 100644 --- a/examples/tinkerboard_generic.go +++ b/examples/tinkerboard_generic.go @@ -84,7 +84,6 @@ func main() { if read && write { if reflect.DeepEqual(wData, rData) { fmt.Printf("EEPROM addr: %d equal: %v\n", eepromAddr, rData) - } else { fmt.Printf("EEPROM addr: %d wr: %v differ rd: %v\n", eepromAddr, wData, rData) } diff --git a/examples/tinkerboard_mfcrc522gpio.go b/examples/tinkerboard_mfcrc522gpio.go index b630b2efe..fa126e2df 100644 --- a/examples/tinkerboard_mfcrc522gpio.go +++ b/examples/tinkerboard_mfcrc522gpio.go @@ -41,7 +41,6 @@ func main() { } gobot.Every(2*time.Second, func() { - if !wasCardDetected { fmt.Println("\n+++ poll for card +++") if err := d.IsCardPresent(); err != nil { @@ -64,7 +63,6 @@ func main() { fmt.Printf("-- start text --\n%s\n-- end text --\n", text) } } - }) } diff --git a/examples/tinkerboard_pca9533.go b/examples/tinkerboard_pca9533.go index 2b1360969..cf9b03085 100644 --- a/examples/tinkerboard_pca9533.go +++ b/examples/tinkerboard_pca9533.go @@ -129,5 +129,4 @@ func initialize(pca *i2c.PCA953xDriver, led2FrequHz float32, led3FrequHz float32 if err != nil { fmt.Println("errW:", err) } - } diff --git a/examples/tinkerboard_pcf8583_clock.go b/examples/tinkerboard_pcf8583_clock.go index da2e93dca..ddd3209be 100644 --- a/examples/tinkerboard_pcf8583_clock.go +++ b/examples/tinkerboard_pcf8583_clock.go @@ -25,7 +25,6 @@ func main() { pcf := i2c.NewPCF8583Driver(board, i2c.WithBus(1), i2c.WithPCF8583Mode(i2c.PCF8583CtrlModeClock50)) work := func() { - currentTime := time.Now() log.Println(currentTime) diff --git a/helpers_test.go b/helpers_test.go index b97cf7c03..dee5d39a1 100644 --- a/helpers_test.go +++ b/helpers_test.go @@ -23,8 +23,10 @@ type testDriver struct { Commander } -var testDriverStart = func() (err error) { return } -var testDriverHalt = func() (err error) { return } +var ( + testDriverStart = func() (err error) { return } + testDriverHalt = func() (err error) { return } +) func (t *testDriver) Start() (err error) { return testDriverStart() } func (t *testDriver) Halt() (err error) { return testDriverHalt() } @@ -51,8 +53,10 @@ type testAdaptor struct { port string } -var testAdaptorConnect = func() (err error) { return } -var testAdaptorFinalize = func() (err error) { return } +var ( + testAdaptorConnect = func() (err error) { return } + testAdaptorFinalize = func() (err error) { return } +) func (t *testAdaptor) Finalize() (err error) { return testAdaptorFinalize() } func (t *testAdaptor) Connect() (err error) { return testAdaptorConnect() } @@ -60,7 +64,7 @@ func (t *testAdaptor) Name() string { return t.name } func (t *testAdaptor) SetName(n string) { t.name = n } func (t *testAdaptor) Port() string { return t.port } -func newTestAdaptor(name string, port string) *testAdaptor { +func newTestAdaptor(name string, port string) *testAdaptor { //nolint:unparam // keep for tests return &testAdaptor{ name: name, port: port, diff --git a/platforms/adaptors/digitalpinsadaptor.go b/platforms/adaptors/digitalpinsadaptor.go index a171134e4..5321bb2e5 100644 --- a/platforms/adaptors/digitalpinsadaptor.go +++ b/platforms/adaptors/digitalpinsadaptor.go @@ -10,8 +10,10 @@ import ( "gobot.io/x/gobot/v2/system" ) -type digitalPinTranslator func(pin string) (chip string, line int, err error) -type digitalPinInitializer func(gobot.DigitalPinner) error +type ( + digitalPinTranslator func(pin string) (chip string, line int, err error) + digitalPinInitializer func(gobot.DigitalPinner) error +) type digitalPinsOptioner interface { setDigitalPinInitializer(digitalPinInitializer) @@ -158,7 +160,8 @@ func WithGpioDebounce(pin string, period time.Duration) func(Optioner) { // WithGpioEventOnFallingEdge prepares the given input pin to be generate an event on falling edge. // This is working for inputs since Kernel 5.10, but will be ignored for outputs or with sysfs ABI. func WithGpioEventOnFallingEdge(pin string, handler func(lineOffset int, timestamp time.Duration, detectedEdge string, - seqno uint32, lseqno uint32)) func(Optioner) { + seqno uint32, lseqno uint32), +) func(Optioner) { return func(o Optioner) { a, ok := o.(digitalPinsOptioner) if ok { @@ -170,7 +173,8 @@ func WithGpioEventOnFallingEdge(pin string, handler func(lineOffset int, timesta // WithGpioEventOnRisingEdge prepares the given input pin to be generate an event on rising edge. // This is working for inputs since Kernel 5.10, but will be ignored for outputs or with sysfs ABI. func WithGpioEventOnRisingEdge(pin string, handler func(lineOffset int, timestamp time.Duration, detectedEdge string, - seqno uint32, lseqno uint32)) func(Optioner) { + seqno uint32, lseqno uint32), +) func(Optioner) { return func(o Optioner) { a, ok := o.(digitalPinsOptioner) if ok { @@ -182,7 +186,8 @@ func WithGpioEventOnRisingEdge(pin string, handler func(lineOffset int, timestam // WithGpioEventOnBothEdges prepares the given input pin to be generate an event on rising and falling edges. // This is working for inputs since Kernel 5.10, but will be ignored for outputs or with sysfs ABI. func WithGpioEventOnBothEdges(pin string, handler func(lineOffset int, timestamp time.Duration, detectedEdge string, - seqno uint32, lseqno uint32)) func(Optioner) { + seqno uint32, lseqno uint32), +) func(Optioner) { return func(o Optioner) { a, ok := o.(digitalPinsOptioner) if ok { @@ -336,7 +341,8 @@ func (a *DigitalPinsAdaptor) prepareDigitalPinDebounce(id string, period time.Du } func (a *DigitalPinsAdaptor) prepareDigitalPinEventOnFallingEdge(id string, handler func(int, time.Duration, string, - uint32, uint32)) { + uint32, uint32), +) { if a.pinOptions == nil { a.pinOptions = make(map[string][]func(gobot.DigitalPinOptioner) bool) } @@ -345,7 +351,8 @@ func (a *DigitalPinsAdaptor) prepareDigitalPinEventOnFallingEdge(id string, hand } func (a *DigitalPinsAdaptor) prepareDigitalPinEventOnRisingEdge(id string, handler func(int, time.Duration, string, - uint32, uint32)) { + uint32, uint32), +) { if a.pinOptions == nil { a.pinOptions = make(map[string][]func(gobot.DigitalPinOptioner) bool) } @@ -354,7 +361,8 @@ func (a *DigitalPinsAdaptor) prepareDigitalPinEventOnRisingEdge(id string, handl } func (a *DigitalPinsAdaptor) prepareDigitalPinEventOnBothEdges(id string, handler func(int, time.Duration, string, - uint32, uint32)) { + uint32, uint32), +) { if a.pinOptions == nil { a.pinOptions = make(map[string][]func(gobot.DigitalPinOptioner) bool) } diff --git a/platforms/adaptors/digitalpinsadaptor_test.go b/platforms/adaptors/digitalpinsadaptor_test.go index 59a4f74d5..fce9649a7 100644 --- a/platforms/adaptors/digitalpinsadaptor_test.go +++ b/platforms/adaptors/digitalpinsadaptor_test.go @@ -2,12 +2,11 @@ package adaptors import ( "fmt" - "testing" - "time" - "runtime" "strconv" "sync" + "testing" + "time" "github.com/stretchr/testify/assert" "gobot.io/x/gobot/v2" @@ -16,9 +15,11 @@ import ( ) // make sure that this adaptor fulfills all the required interfaces -var _ gobot.DigitalPinnerProvider = (*DigitalPinsAdaptor)(nil) -var _ gpio.DigitalReader = (*DigitalPinsAdaptor)(nil) -var _ gpio.DigitalWriter = (*DigitalPinsAdaptor)(nil) +var ( + _ gobot.DigitalPinnerProvider = (*DigitalPinsAdaptor)(nil) + _ gpio.DigitalReader = (*DigitalPinsAdaptor)(nil) + _ gpio.DigitalWriter = (*DigitalPinsAdaptor)(nil) +) func initTestDigitalPinsAdaptorWithMockedFilesystem(mockPaths []string) (*DigitalPinsAdaptor, *system.MockFilesystem) { sys := system.NewAccesser() diff --git a/platforms/adaptors/pwmpinsadaptor.go b/platforms/adaptors/pwmpinsadaptor.go index 914771940..f1b88de91 100644 --- a/platforms/adaptors/pwmpinsadaptor.go +++ b/platforms/adaptors/pwmpinsadaptor.go @@ -15,8 +15,10 @@ import ( // 100ns = 10MHz, 10ns = 100MHz, 1ns = 1GHz const pwmPeriodDefault = 10000000 // 10 ms = 100 Hz -type pwmPinTranslator func(pin string) (path string, channel int, err error) -type pwmPinInitializer func(gobot.PWMPinner) error +type ( + pwmPinTranslator func(pin string) (path string, channel int, err error) + pwmPinInitializer func(gobot.PWMPinner) error +) type pwmPinsOption interface { setInitializer(pwmPinInitializer) @@ -228,7 +230,7 @@ func (a *PWMPinsAdaptor) pwmPin(id string) (gobot.PWMPinner, error) { // also this value will be adjusted in the same ratio. The order of writing the values must be observed, otherwise an // error occur "write error: Invalid argument". func setPeriod(pin gobot.PWMPinner, period uint32, adjustDuty bool) error { - var errorBase = fmt.Sprintf("setPeriod(%v, %d) failed", pin, period) + errorBase := fmt.Sprintf("setPeriod(%v, %d) failed", pin, period) var oldDuty uint32 var err error @@ -255,11 +257,11 @@ func setPeriod(pin gobot.PWMPinner, period uint32, adjustDuty bool) error { if err := pin.SetPeriod(period); err != nil { return fmt.Errorf("%s with '%v'", errorBase, err) } - if err := pin.SetDutyCycle(uint32(duty)); err != nil { + if err := pin.SetDutyCycle(duty); err != nil { return fmt.Errorf("%s with '%v'", errorBase, err) } } else { - if err := pin.SetDutyCycle(uint32(duty)); err != nil { + if err := pin.SetDutyCycle(duty); err != nil { return fmt.Errorf("%s with '%v'", errorBase, err) } if err := pin.SetPeriod(period); err != nil { diff --git a/platforms/adaptors/pwmpinsadaptor_test.go b/platforms/adaptors/pwmpinsadaptor_test.go index fad38191f..322533c7a 100644 --- a/platforms/adaptors/pwmpinsadaptor_test.go +++ b/platforms/adaptors/pwmpinsadaptor_test.go @@ -16,7 +16,7 @@ import ( ) const ( - pwmDir = "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/" + pwmDir = "/sys/devices/platform/ff680020.pwm/pwm/pwmchip3/" //nolint:gosec // false positive pwmPwm0Dir = pwmDir + "pwm44/" pwmExportPath = pwmDir + "export" pwmUnexportPath = pwmDir + "unexport" @@ -36,9 +36,11 @@ var pwmMockPaths = []string{ } // make sure that this PWMPinsAdaptor fulfills all the required interfaces -var _ gobot.PWMPinnerProvider = (*PWMPinsAdaptor)(nil) -var _ gpio.PwmWriter = (*PWMPinsAdaptor)(nil) -var _ gpio.ServoWriter = (*PWMPinsAdaptor)(nil) +var ( + _ gobot.PWMPinnerProvider = (*PWMPinsAdaptor)(nil) + _ gpio.PwmWriter = (*PWMPinsAdaptor)(nil) + _ gpio.ServoWriter = (*PWMPinsAdaptor)(nil) +) func initTestPWMPinsAdaptorWithMockedFilesystem(mockPaths []string) (*PWMPinsAdaptor, *system.MockFilesystem) { sys := system.NewAccesser() @@ -270,7 +272,7 @@ func TestSetPeriod(t *testing.T) { func Test_PWMPin(t *testing.T) { translateErr := "translator_error" translator := func(string) (string, int, error) { return pwmDir, 44, nil } - var tests = map[string]struct { + tests := map[string]struct { mockPaths []string period string dutyCycle string @@ -353,7 +355,6 @@ func Test_PWMPin(t *testing.T) { assert.Contains(t, err.Error(), tc.wantErr) assert.Nil(t, got) } - }) } } diff --git a/platforms/adaptors/spibusadaptor.go b/platforms/adaptors/spibusadaptor.go index 12e6acf00..55608300a 100644 --- a/platforms/adaptors/spibusadaptor.go +++ b/platforms/adaptors/spibusadaptor.go @@ -27,7 +27,8 @@ type SpiBusAdaptor struct { // NewSpiBusAdaptor provides the access to SPI buses of the board. The validator is used to check the // bus number (given by user) to the abilities of the board. func NewSpiBusAdaptor(sys *system.Accesser, v spiBusNumberValidator, busNum, chipNum, mode, bits int, - maxSpeed int64) *SpiBusAdaptor { + maxSpeed int64, +) *SpiBusAdaptor { a := &SpiBusAdaptor{ sys: sys, validateBusNumber: v, diff --git a/platforms/audio/audio_adaptor_test.go b/platforms/audio/audio_adaptor_test.go index b11e9741e..42f69549e 100644 --- a/platforms/audio/audio_adaptor_test.go +++ b/platforms/audio/audio_adaptor_test.go @@ -71,7 +71,7 @@ func TestAudioAdaptorSoundWithValidMP3Filename(t *testing.T) { func myExecCommand(command string, args ...string) *exec.Cmd { cs := []string{"-test.run=TestHelperProcess", "--", command} cs = append(cs, args...) - cmd := exec.Command(os.Args[0], cs...) + cmd := exec.Command(os.Args[0], cs...) //nolint:gosec // ok for test cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"} return cmd } diff --git a/platforms/beaglebone/beaglebone_adaptor.go b/platforms/beaglebone/beaglebone_adaptor.go index c208f9fa6..2486b9cf2 100644 --- a/platforms/beaglebone/beaglebone_adaptor.go +++ b/platforms/beaglebone/beaglebone_adaptor.go @@ -127,7 +127,7 @@ func (c *Adaptor) DigitalWrite(id string, val byte) error { defer c.mutex.Unlock() if strings.Contains(id, "usr") { - fi, e := c.sys.OpenFile(c.usrLed+id+"/brightness", os.O_WRONLY|os.O_APPEND, 0666) + fi, e := c.sys.OpenFile(c.usrLed+id+"/brightness", os.O_WRONLY|os.O_APPEND, 0o666) defer fi.Close() //nolint:staticcheck // for historical reasons if e != nil { return e @@ -145,14 +145,14 @@ func (c *Adaptor) AnalogRead(pin string) (val int, err error) { if err != nil { return } - fi, err := c.sys.OpenFile(fmt.Sprintf("%v/%v", c.analogPath, analogPin), os.O_RDONLY, 0644) + fi, err := c.sys.OpenFile(fmt.Sprintf("%v/%v", c.analogPath, analogPin), os.O_RDONLY, 0o644) defer fi.Close() //nolint:staticcheck // for historical reasons if err != nil { return } - var buf = make([]byte, 1024) + buf := make([]byte, 1024) _, err = fi.Read(buf) if err != nil { return @@ -238,7 +238,7 @@ func (p pwmPinData) findPWMDir(sys *system.Accesser) (dir string, err error) { func (c *Adaptor) muxPin(pin, cmd string) error { path := fmt.Sprintf("/sys/devices/platform/ocp/ocp:%s_pinmux/state", pin) - fi, e := c.sys.OpenFile(path, os.O_WRONLY, 0666) + fi, e := c.sys.OpenFile(path, os.O_WRONLY, 0o666) defer fi.Close() //nolint:staticcheck // for historical reasons if e != nil { return e diff --git a/platforms/beaglebone/beaglebone_adaptor_test.go b/platforms/beaglebone/beaglebone_adaptor_test.go index 987d08e9a..55a927a6b 100644 --- a/platforms/beaglebone/beaglebone_adaptor_test.go +++ b/platforms/beaglebone/beaglebone_adaptor_test.go @@ -15,16 +15,18 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ aio.AnalogReader = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) -var _ spi.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ aio.AnalogReader = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) + _ spi.Connector = (*Adaptor)(nil) +) func initTestAdaptorWithMockedFilesystem(mockPaths []string) (*Adaptor, *system.MockFilesystem) { a := NewAdaptor() @@ -244,7 +246,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -276,7 +278,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -321,7 +323,7 @@ func Test_translateAndMuxPWMPin(t *testing.T) { } a, fs := initTestAdaptorWithMockedFilesystem(mockPaths) - var tests = map[string]struct { + tests := map[string]struct { wantDir string wantChannel int wantErr error diff --git a/platforms/ble/battery_driver.go b/platforms/ble/battery_driver.go index 0366a63d6..fc38e7262 100644 --- a/platforms/ble/battery_driver.go +++ b/platforms/ble/battery_driver.go @@ -57,6 +57,6 @@ func (b *BatteryDriver) GetBatteryLevel() (level uint8) { } buf := bytes.NewBuffer(c) val, _ := buf.ReadByte() - l = uint8(val) + l = val return l } diff --git a/platforms/ble/ble_client_adaptor.go b/platforms/ble/ble_client_adaptor.go index ce65c3807..8af9419dc 100644 --- a/platforms/ble/ble_client_adaptor.go +++ b/platforms/ble/ble_client_adaptor.go @@ -11,8 +11,10 @@ import ( "tinygo.org/x/bluetooth" ) -var currentAdapter *bluetooth.Adapter -var bleMutex sync.Mutex +var ( + currentAdapter *bluetooth.Adapter + bleMutex sync.Mutex +) // BLEConnector is the interface that a BLE ClientAdaptor must implement type BLEConnector interface { @@ -212,7 +214,7 @@ func (b *ClientAdaptor) Subscribe(cUUID string, f func([]byte, error)) error { } // getBLEAdapter is singleton for bluetooth adapter connection -func getBLEAdapter(impl string) (*bluetooth.Adapter, error) { +func getBLEAdapter(impl string) (*bluetooth.Adapter, error) { //nolint:unparam // TODO: impl is unused, maybe an error if currentAdapter != nil { return currentAdapter, nil } diff --git a/platforms/chip/chip_adaptor_test.go b/platforms/chip/chip_adaptor_test.go index 69113b4ad..f235930a6 100644 --- a/platforms/chip/chip_adaptor_test.go +++ b/platforms/chip/chip_adaptor_test.go @@ -13,14 +13,16 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) var mockPaths = []string{ "/sys/class/gpio/export", @@ -176,7 +178,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -211,7 +213,7 @@ func Test_validateI2cBusNumber(t *testing.T) { } func Test_translatePWMPin(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { usePro bool wantDir string wantChannel int diff --git a/platforms/dexter/gopigo3/driver.go b/platforms/dexter/gopigo3/driver.go index bbed8c56a..f4c3f12ad 100644 --- a/platforms/dexter/gopigo3/driver.go +++ b/platforms/dexter/gopigo3/driver.go @@ -307,9 +307,9 @@ func (g *Driver) SetLED(led Led, red, green, blue uint8) error { goPiGo3Address, SET_LED, byte(led), - byte(red), - byte(green), - byte(blue), + red, + green, + blue, }) } @@ -403,7 +403,7 @@ func (g *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder return flags, power, encoder, dps, err } // get flags - flags = uint8(response[4]) + flags = response[4] // get power power = uint16(response[5]) if power&0x80 == 0x80 { @@ -420,7 +420,7 @@ func (g *Driver) GetMotorStatus(motor Motor) (flags uint8, power uint16, encoder if e&0x80000000 == 0x80000000 { encoder = int(uint64(e) - 0x100000000) } - //get dps + // get dps d := make([]byte, 4) d[1] = response[10] d[0] = response[11] @@ -596,7 +596,7 @@ func (g *Driver) DigitalWrite(pin string, val byte) error { goPiGo3Address, SET_GROVE_STATE, byte(grovePin), - byte(val), + val, }) } diff --git a/platforms/dexter/gopigo3/driver_test.go b/platforms/dexter/gopigo3/driver_test.go index 4b1c5846d..c133742d4 100644 --- a/platforms/dexter/gopigo3/driver_test.go +++ b/platforms/dexter/gopigo3/driver_test.go @@ -9,8 +9,10 @@ import ( "gobot.io/x/gobot/v2/drivers/spi" ) -var _ gobot.Driver = (*Driver)(nil) -var negativeEncoder = false +var ( + _ gobot.Driver = (*Driver)(nil) + negativeEncoder = false +) func initTestDriver() *Driver { d := NewDriver(&TestConnector{}) @@ -272,8 +274,7 @@ func (ctr *TestConnector) SpiDefaultMaxSpeed() int64 { return 0 } -type TestSpiDevice struct { -} +type TestSpiDevice struct{} func (c TestSpiDevice) Close() error { return nil diff --git a/platforms/digispark/digispark_adaptor.go b/platforms/digispark/digispark_adaptor.go index d72e88173..29c0815b0 100644 --- a/platforms/digispark/digispark_adaptor.go +++ b/platforms/digispark/digispark_adaptor.go @@ -54,7 +54,6 @@ func (d *Adaptor) Finalize() (err error) { return } // DigitalWrite writes a value to the pin. Acceptable values are 1 or 0. func (d *Adaptor) DigitalWrite(pin string, level byte) (err error) { p, err := strconv.Atoi(pin) - if err != nil { return } diff --git a/platforms/digispark/digispark_adaptor_test.go b/platforms/digispark/digispark_adaptor_test.go index f144f0a05..7f5fc36d3 100644 --- a/platforms/digispark/digispark_adaptor_test.go +++ b/platforms/digispark/digispark_adaptor_test.go @@ -12,9 +12,11 @@ import ( var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) +var ( + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) +) type mock struct { locationA uint8 @@ -33,6 +35,7 @@ func (l *mock) digitalWrite(pin uint8, state uint8) error { l.state = state return l.error() } + func (l *mock) pinMode(pin uint8, mode uint8) error { l.pin = pin l.mode = mode @@ -48,6 +51,7 @@ func (l *mock) pwmUpdateCompare(channelA uint8, channelB uint8) error { l.pwmChannelB = channelB return l.error() } + func (l *mock) pwmUpdatePrescaler(value uint) error { l.pwmPrescalerValue = value return l.error() diff --git a/platforms/digispark/digispark_i2c.go b/platforms/digispark/digispark_i2c.go index 07a8a9547..6249c2a20 100644 --- a/platforms/digispark/digispark_i2c.go +++ b/platforms/digispark/digispark_i2c.go @@ -38,7 +38,7 @@ func (c *digisparkI2cConnection) Test(address uint8) error { return c.adaptor.littleWire.i2cStart(address, 0) } -// UpdateDelay updates i2c signal delay amount; tune if neccessary to fit your requirements +// UpdateDelay updates i2c signal delay amount; tune if necessary to fit your requirements func (c *digisparkI2cConnection) UpdateDelay(duration uint) error { if !c.adaptor.i2c { return errors.New("Digispark i2c not initialized") diff --git a/platforms/digispark/digispark_i2c_test.go b/platforms/digispark/digispark_i2c_test.go index dfc0dd463..9b5ccbeec 100644 --- a/platforms/digispark/digispark_i2c_test.go +++ b/platforms/digispark/digispark_i2c_test.go @@ -8,11 +8,15 @@ import ( "gobot.io/x/gobot/v2/drivers/i2c" ) -const availableI2cAddress = 0x40 -const maxUint8 = ^uint8(0) +const ( + availableI2cAddress = 0x40 + maxUint8 = ^uint8(0) +) -var _ i2c.Connector = (*Adaptor)(nil) -var i2cData = []byte{5, 4, 3, 2, 1, 0} +var ( + _ i2c.Connector = (*Adaptor)(nil) + i2cData = []byte{5, 4, 3, 2, 1, 0} +) type i2cMock struct { duration uint diff --git a/platforms/digispark/littleWire.go b/platforms/digispark/littleWire.go index d3e3c3c83..0f2236835 100644 --- a/platforms/digispark/littleWire.go +++ b/platforms/digispark/littleWire.go @@ -106,7 +106,7 @@ func (l *littleWire) i2cRead(readBuffer []byte, length int, endWithStop uint8) e return l.error() } -// i2cUpdateDelay updates i2c signal delay amount. Tune if neccessary to fit your requirements +// i2cUpdateDelay updates i2c signal delay amount. Tune if necessary to fit your requirements func (l *littleWire) i2cUpdateDelay(duration uint) error { C.i2c_updateDelay(l.lwHandle, C.uint(duration)) return l.error() diff --git a/platforms/digispark/littleWire.h b/platforms/digispark/littleWire.h index a46a353b2..ada3f0dbc 100644 --- a/platforms/digispark/littleWire.h +++ b/platforms/digispark/littleWire.h @@ -405,7 +405,7 @@ void i2c_write(littleWire* lwHandle, unsigned char* sendBuffer, unsigned char le void i2c_read(littleWire* lwHandle, unsigned char* readBuffer, unsigned char length, unsigned char endWithStop); /** - * Update i2c signal delay amount. Tune if neccessary to fit your requirements. + * Update i2c signal delay amount. Tune if necessary to fit your requirements. * * @param lwHandle littleWire device pointer * @param duration Delay amount diff --git a/platforms/dji/tello/crc.go b/platforms/dji/tello/crc.go index 834a74d4a..3aa031b0d 100644 --- a/platforms/dji/tello/crc.go +++ b/platforms/dji/tello/crc.go @@ -23,7 +23,7 @@ var crc8table = []byte{ func CalculateCRC8(pkt []byte) byte { crc := byte(0x77) for _, val := range pkt { - crc = crc8table[(crc^byte(val))&0xff] + crc = crc8table[(crc^val)&0xff] } return crc diff --git a/platforms/dji/tello/driver.go b/platforms/dji/tello/driver.go index f48d28e99..808993c05 100644 --- a/platforms/dji/tello/driver.go +++ b/platforms/dji/tello/driver.go @@ -208,7 +208,8 @@ func NewDriver(port string) *Driver { // NewDriverWithIP creates a driver for the Tello EDU drone. Pass in the ip address and UDP port to use for the responses // from the drone. func NewDriverWithIP(ip string, port string) *Driver { - d := &Driver{name: gobot.DefaultName("Tello"), + d := &Driver{ + name: gobot.DefaultName("Tello"), reqAddr: ip + ":8889", respPort: port, videoPort: "11111", @@ -275,7 +276,6 @@ func (d *Driver) Start() error { panic(err) } }) - if err != nil { panic(err) } @@ -519,7 +519,7 @@ func (d *Driver) Rate() error { } // bound is a naive implementation that returns the smaller of x or y. -func bound(x, y float32) float32 { +func bound(x, y float32) float32 { //nolint:unparam // keep y as parameter if x < -y { return -y } diff --git a/platforms/dji/tello/driver_test.go b/platforms/dji/tello/driver_test.go index 793015bbd..3571c0160 100644 --- a/platforms/dji/tello/driver_test.go +++ b/platforms/dji/tello/driver_test.go @@ -20,6 +20,7 @@ type WriteCloserDoNothing struct{} func (w *WriteCloserDoNothing) Write(p []byte) (n int, err error) { return 0, nil } + func (w *WriteCloserDoNothing) Close() error { return nil } diff --git a/platforms/dragonboard/dragonboard_adaptor_test.go b/platforms/dragonboard/dragonboard_adaptor_test.go index e54a4d5c3..acf7117f4 100644 --- a/platforms/dragonboard/dragonboard_adaptor_test.go +++ b/platforms/dragonboard/dragonboard_adaptor_test.go @@ -12,13 +12,15 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) -func initTestAdaptor(t *testing.T) *Adaptor { +func initTestAdaptor() *Adaptor { a := NewAdaptor() if err := a.Connect(); err != nil { panic(err) @@ -27,14 +29,14 @@ func initTestAdaptor(t *testing.T) *Adaptor { } func TestName(t *testing.T) { - a := initTestAdaptor(t) + a := initTestAdaptor() assert.True(t, strings.HasPrefix(a.Name(), "DragonBoard")) a.SetName("NewName") assert.Equal(t, "NewName", a.Name()) } func TestDigitalIO(t *testing.T) { - a := initTestAdaptor(t) + a := initTestAdaptor() mockPaths := []string{ "/sys/class/gpio/export", "/sys/class/gpio/unexport", @@ -57,7 +59,7 @@ func TestDigitalIO(t *testing.T) { } func TestFinalizeErrorAfterGPIO(t *testing.T) { - a := initTestAdaptor(t) + a := initTestAdaptor() mockPaths := []string{ "/sys/class/gpio/export", "/sys/class/gpio/unexport", @@ -78,7 +80,7 @@ func TestFinalizeErrorAfterGPIO(t *testing.T) { } func TestI2cDefaultBus(t *testing.T) { - a := initTestAdaptor(t) + a := initTestAdaptor() assert.Equal(t, 0, a.DefaultI2cBus()) } @@ -100,7 +102,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ diff --git a/platforms/firmata/client/client.go b/platforms/firmata/client/client.go index 5b770265d..d445ed2a2 100644 --- a/platforms/firmata/client/client.go +++ b/platforms/firmata/client/client.go @@ -333,16 +333,18 @@ func (b *Client) ReportAnalog(pin int, state int) error { // I2cRead reads numBytes from address once. func (b *Client) I2cRead(address int, numBytes int) error { - return b.WriteSysex([]byte{I2CRequest, byte(address), (I2CModeRead << 3), - byte(numBytes) & 0x7F, (byte(numBytes) >> 7) & 0x7F}) + return b.WriteSysex([]byte{ + I2CRequest, byte(address), (I2CModeRead << 3), + byte(numBytes) & 0x7F, (byte(numBytes) >> 7) & 0x7F, + }) } // I2cWrite writes data to address. func (b *Client) I2cWrite(address int, data []byte) error { ret := []byte{I2CRequest, byte(address), (I2CModeWrite << 3)} for _, val := range data { - ret = append(ret, byte(val&0x7F)) - ret = append(ret, byte((val>>7)&0x7F)) + ret = append(ret, val&0x7F) + ret = append(ret, (val>>7)&0x7F) } return b.WriteSysex(ret) } @@ -360,7 +362,7 @@ func (b *Client) togglePinReporting(pin int, state int, mode byte) error { state = 0 } - return b.write([]byte{byte(mode) | byte(pin), byte(state)}) + return b.write([]byte{mode | byte(pin), byte(state)}) } // WriteSysex writes an arbitrary Sysex command to the microcontroller. @@ -421,7 +423,7 @@ func (b *Client) process() error { portValue := buf[0] | (buf[1] << 7) for i := 0; i < 8; i++ { - pinNumber := int((8*byte(port) + byte(i))) + pinNumber := int((8*port + byte(i))) if len(b.pins) > pinNumber { if b.pins[pinNumber].Mode == Input { b.pins[pinNumber].Value = int((portValue >> (byte(i) & 0x07)) & 0x01) @@ -505,9 +507,9 @@ func (b *Client) process() error { b.Publish(b.Event(fmt.Sprintf("PinState%v", pin)), b.pins[pin]) case I2CReply: reply := I2cReply{ - Address: int(byte(currentBuffer[2]) | byte(currentBuffer[3])<<7), - Register: int(byte(currentBuffer[4]) | byte(currentBuffer[5])<<7), - Data: []byte{byte(currentBuffer[6]) | byte(currentBuffer[7])<<7}, + Address: int(currentBuffer[2] | currentBuffer[3]<<7), + Register: int(currentBuffer[4] | currentBuffer[5]<<7), + Data: []byte{currentBuffer[6] | currentBuffer[7]<<7}, } for i := 8; i < len(currentBuffer); i = i + 2 { if currentBuffer[i] == byte(0xF7) { @@ -517,7 +519,7 @@ func (b *Client) process() error { break } reply.Data = append(reply.Data, - byte(currentBuffer[i])|byte(currentBuffer[i+1])<<7, + currentBuffer[i]|currentBuffer[i+1]<<7, ) } b.Publish(b.Event("I2cReply"), reply) diff --git a/platforms/firmata/client/client_test.go b/platforms/firmata/client/client_test.go index 968e04adc..5d979fead 100644 --- a/platforms/firmata/client/client_test.go +++ b/platforms/firmata/client/client_test.go @@ -16,33 +16,43 @@ type readWriteCloser struct { id string } -var testWriteData = bytes.Buffer{} -var writeDataMutex sync.Mutex +var ( + testWriteData = bytes.Buffer{} + writeDataMutex sync.Mutex +) // do not set this data directly, use always addTestReadData() -var testReadDataMap = make(map[string][]byte) -var rwDataMapMutex sync.Mutex +var ( + testReadDataMap = make(map[string][]byte) + rwDataMapMutex sync.Mutex +) // arduino uno r3 protocol response "2.3" var testDataProtocolResponse = []byte{249, 2, 3} // arduino uno r3 firmware response "StandardFirmata.ino" -var testDataFirmwareResponse = []byte{240, 121, 2, 3, 83, 0, 116, 0, 97, 0, 110, 0, 100, 0, 97, +var testDataFirmwareResponse = []byte{ + 240, 121, 2, 3, 83, 0, 116, 0, 97, 0, 110, 0, 100, 0, 97, 0, 114, 0, 100, 0, 70, 0, 105, 0, 114, 0, 109, 0, 97, 0, 116, 0, 97, 0, 46, - 0, 105, 0, 110, 0, 111, 0, 247} + 0, 105, 0, 110, 0, 111, 0, 247, +} // arduino uno r3 capabilities response -var testDataCapabilitiesResponse = []byte{240, 108, 127, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, +var testDataCapabilitiesResponse = []byte{ + 240, 108, 127, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 3, 8, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 4, 14, 127, 0, 1, 1, 1, 2, 10, 127, 0, 1, 1, 1, 2, 10, 127, 0, 1, 1, 1, 2, 10, 127, 0, 1, 1, 1, 2, 10, - 127, 0, 1, 1, 1, 2, 10, 6, 1, 127, 0, 1, 1, 1, 2, 10, 6, 1, 127, 247} + 127, 0, 1, 1, 1, 2, 10, 6, 1, 127, 0, 1, 1, 1, 2, 10, 6, 1, 127, 247, +} // arduino uno r3 analog mapping response -var testDataAnalogMappingResponse = []byte{240, 106, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, - 127, 127, 127, 127, 0, 1, 2, 3, 4, 5, 247} +var testDataAnalogMappingResponse = []byte{ + 240, 106, 127, 127, 127, 127, 127, 127, 127, 127, 127, 127, + 127, 127, 127, 127, 0, 1, 2, 3, 4, 5, 247, +} func (readWriteCloser) Write(p []byte) (int, error) { writeDataMutex.Lock() @@ -79,7 +89,7 @@ func (rwc readWriteCloser) Read(b []byte) (int, error) { if len(data) < size { size = len(data) } - copy(b, []byte(data)[:size]) + copy(b, data[:size]) testReadDataMap[rwc.id] = data[size:] return size, nil } diff --git a/platforms/firmata/firmata_adaptor_test.go b/platforms/firmata/firmata_adaptor_test.go index 9f31cbb93..f943e57af 100644 --- a/platforms/firmata/firmata_adaptor_test.go +++ b/platforms/firmata/firmata_adaptor_test.go @@ -16,13 +16,15 @@ import ( ) // make sure that this Adaptor fulfills all required analog and digital interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ aio.AnalogReader = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ FirmataAdaptor = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ aio.AnalogReader = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ FirmataAdaptor = (*Adaptor)(nil) +) type readWriteCloser struct{} @@ -30,15 +32,17 @@ func (readWriteCloser) Write(p []byte) (int, error) { return testWriteData.Write(p) } -var testReadData = []byte{} -var testWriteData = bytes.Buffer{} +var ( + testReadData = []byte{} + testWriteData = bytes.Buffer{} +) func (readWriteCloser) Read(b []byte) (int, error) { size := len(b) if len(testReadData) < size { size = len(testReadData) } - copy(b, []byte(testReadData)[:size]) + copy(b, testReadData[:size]) testReadData = testReadData[size:] return size, nil @@ -69,9 +73,11 @@ func newMockFirmataBoard() *mockFirmataBoard { // setup mock for GPIO, PWM and servo tests func (mockFirmataBoard) Connect(io.ReadWriteCloser) error { return nil } + func (m mockFirmataBoard) Disconnect() error { return m.disconnectError } + func (m mockFirmataBoard) Pins() []client.Pin { return m.pins } @@ -113,7 +119,7 @@ func TestAdaptorFinalize(t *testing.T) { } func TestAdaptorConnect(t *testing.T) { - var openSP = func(port string) (io.ReadWriteCloser, error) { + openSP := func(port string) (io.ReadWriteCloser, error) { return &readWriteCloser{}, nil } a := NewAdaptor("/dev/null") diff --git a/platforms/firmata/firmata_i2c_test.go b/platforms/firmata/firmata_i2c_test.go index 9afb94445..4bc3c55fd 100644 --- a/platforms/firmata/firmata_i2c_test.go +++ b/platforms/firmata/firmata_i2c_test.go @@ -31,6 +31,7 @@ func (t *i2cMockFirmataBoard) I2cRead(address int, numBytes int) error { }() return nil } + func (t *i2cMockFirmataBoard) I2cWrite(address int, data []byte) error { t.i2cWritten = append(t.i2cWritten, data...) return nil diff --git a/platforms/holystone/hs200/hs200_driver.go b/platforms/holystone/hs200/hs200_driver.go index c9f2808ef..e11f4114d 100644 --- a/platforms/holystone/hs200/hs200_driver.go +++ b/platforms/holystone/hs200/hs200_driver.go @@ -45,8 +45,10 @@ func NewDriver(tcpaddress string, udpaddress string) *Driver { } command[10] = checksum(command) - return &Driver{name: gobot.DefaultName("HS200"), stopc: make(chan struct{}), - tcpaddress: tcpaddress, udpaddress: udpaddress, cmd: command, mutex: &sync.RWMutex{}} + return &Driver{ + name: gobot.DefaultName("HS200"), stopc: make(chan struct{}), + tcpaddress: tcpaddress, udpaddress: udpaddress, cmd: command, mutex: &sync.RWMutex{}, + } } // Name returns the name of the device. diff --git a/platforms/intel-iot/curie/imu_driver_test.go b/platforms/intel-iot/curie/imu_driver_test.go index 48723d230..30eb76413 100644 --- a/platforms/intel-iot/curie/imu_driver_test.go +++ b/platforms/intel-iot/curie/imu_driver_test.go @@ -21,15 +21,17 @@ func (readWriteCloser) Write(p []byte) (int, error) { return testWriteData.Write(p) } -var testReadData = []byte{} -var testWriteData = bytes.Buffer{} +var ( + testReadData = []byte{} + testWriteData = bytes.Buffer{} +) func (readWriteCloser) Read(b []byte) (int, error) { size := len(b) if len(testReadData) < size { size = len(testReadData) } - copy(b, []byte(testReadData)[:size]) + copy(b, testReadData[:size]) testReadData = testReadData[size:] return size, nil @@ -63,6 +65,7 @@ func (mockFirmataBoard) Connect(io.ReadWriteCloser) error { return nil } func (m mockFirmataBoard) Disconnect() error { return m.disconnectError } + func (m mockFirmataBoard) Pins() []client.Pin { return m.pins } diff --git a/platforms/intel-iot/edison/edison_adaptor.go b/platforms/intel-iot/edison/edison_adaptor.go index 0dbd92bca..bcd754126 100644 --- a/platforms/intel-iot/edison/edison_adaptor.go +++ b/platforms/intel-iot/edison/edison_adaptor.go @@ -262,7 +262,7 @@ func (c *Adaptor) arduinoI2CSetup() error { } func (c *Adaptor) readFile(path string) ([]byte, error) { - file, err := c.sys.OpenFile(path, os.O_RDONLY, 0644) + file, err := c.sys.OpenFile(path, os.O_RDONLY, 0o644) defer file.Close() //nolint:staticcheck // for historical reasons if err != nil { return make([]byte, 0), err @@ -356,7 +356,7 @@ func (c *Adaptor) translateAndMuxPWMPin(id string) (string, int, error) { if err := c.digitalWrite(id, 1); err != nil { return "", -1, err } - if err := c.changePinMode(strconv.Itoa(int(sysPin.pin)), "1"); err != nil { + if err := c.changePinMode(strconv.Itoa(sysPin.pin), "1"); err != nil { return "", -1, err } return "/sys/class/pwm/pwmchip0", sysPin.pwmPin, nil @@ -378,7 +378,7 @@ func (c *Adaptor) newExportedDigitalPin(pin int, o ...func(gobot.DigitalPinOptio // changePinMode writes pin mode to current_pinmux file func (c *Adaptor) changePinMode(pin, mode string) error { - file, err := c.sys.OpenFile("/sys/kernel/debug/gpio_debug/gpio"+pin+"/current_pinmux", os.O_WRONLY, 0644) + file, err := c.sys.OpenFile("/sys/kernel/debug/gpio_debug/gpio"+pin+"/current_pinmux", os.O_WRONLY, 0o644) defer file.Close() //nolint:staticcheck // for historical reasons if err != nil { return err diff --git a/platforms/intel-iot/edison/edison_adaptor_test.go b/platforms/intel-iot/edison/edison_adaptor_test.go index 79e557e7a..d27024a4d 100644 --- a/platforms/intel-iot/edison/edison_adaptor_test.go +++ b/platforms/intel-iot/edison/edison_adaptor_test.go @@ -14,14 +14,16 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ aio.AnalogReader = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ aio.AnalogReader = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) var testPinFiles = []string{ "/sys/bus/iio/devices/iio:device1/in_voltage0_raw", @@ -411,7 +413,6 @@ func TestDigitalPinInFileError(t *testing.T) { _, err := a.DigitalPin("13") assert.Contains(t, err.Error(), "no such file") - } func TestDigitalPinInResistorFileError(t *testing.T) { @@ -569,11 +570,10 @@ func TestI2cFinalizeWithErrors(t *testing.T) { // assert assert.NotNil(t, err) assert.Contains(t, err.Error(), "close error") - } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { board string busNr int wantErr error diff --git a/platforms/intel-iot/joule/joule_adaptor_test.go b/platforms/intel-iot/joule/joule_adaptor_test.go index 316a1da0d..3ef493fb1 100644 --- a/platforms/intel-iot/joule/joule_adaptor_test.go +++ b/platforms/intel-iot/joule/joule_adaptor_test.go @@ -13,13 +13,15 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) func initTestAdaptorWithMockedFilesystem() (*Adaptor, *system.MockFilesystem) { a := NewAdaptor() @@ -187,7 +189,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ diff --git a/platforms/jetson/jetson_adaptor_test.go b/platforms/jetson/jetson_adaptor_test.go index a7529f16f..6ba241227 100644 --- a/platforms/jetson/jetson_adaptor_test.go +++ b/platforms/jetson/jetson_adaptor_test.go @@ -2,12 +2,11 @@ package jetson import ( "fmt" - "strings" - "testing" - "runtime" "strconv" + "strings" "sync" + "testing" "github.com/stretchr/testify/assert" "gobot.io/x/gobot/v2" @@ -18,13 +17,15 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) -var _ spi.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) + _ spi.Connector = (*Adaptor)(nil) +) func initTestAdaptorWithMockedFilesystem(mockPaths []string) (*Adaptor, *system.MockFilesystem) { a := NewAdaptor() @@ -175,7 +176,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -207,7 +208,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ diff --git a/platforms/jetson/pwm_pin.go b/platforms/jetson/pwm_pin.go index 9a9fcf313..18b432e0c 100644 --- a/platforms/jetson/pwm_pin.go +++ b/platforms/jetson/pwm_pin.go @@ -126,7 +126,7 @@ func (p *PWMPin) SetDutyCycle(duty uint32) error { func (p *PWMPin) writeFile(subpath string, value string) error { sysfspath := path.Join(p.path, subpath) - fi, err := p.sys.OpenFile(sysfspath, os.O_WRONLY|os.O_APPEND, 0644) + fi, err := p.sys.OpenFile(sysfspath, os.O_WRONLY|os.O_APPEND, 0o644) defer fi.Close() //nolint:staticcheck // for historical reasons if err != nil { diff --git a/platforms/joystick/bin/scanner.go b/platforms/joystick/bin/scanner.go index ec74112c9..fb4816fcf 100644 --- a/platforms/joystick/bin/scanner.go +++ b/platforms/joystick/bin/scanner.go @@ -1,7 +1,6 @@ //go:build utils // +build utils -// // Do not build by default. // // Joystick scanner @@ -9,17 +8,19 @@ // https://github.com/0xcafed00d/joystick/blob/master/joysticktest/joysticktest.go // Simple program that displays the state of the specified joystick // -// go run joysticktest.go 2 +// go run joysticktest.go 2 +// // displays state of joystick id 2 package main import ( "fmt" - "github.com/nsf/termbox-go" - "github.com/0xcafed00d/joystick" "os" "strconv" "time" + + "github.com/0xcafed00d/joystick" + "github.com/nsf/termbox-go" ) func printAt(x, y int, s string) { @@ -31,7 +32,6 @@ func printAt(x, y int, s string) { func readJoystick(js joystick.Joystick) { jinfo, err := js.Read() - if err != nil { printAt(1, 5, "Error: "+err.Error()) return @@ -55,7 +55,6 @@ func readJoystick(js joystick.Joystick) { } func main() { - jsid := 0 if len(os.Args) > 1 { i, err := strconv.Atoi(os.Args[1]) diff --git a/platforms/keyboard/keyboard.go b/platforms/keyboard/keyboard.go index 78ddc4f96..8ad037d90 100644 --- a/platforms/keyboard/keyboard.go +++ b/platforms/keyboard/keyboard.go @@ -78,7 +78,7 @@ const ( var originalState string func Parse(input bytes) KeyEvent { - var event = KeyEvent{Bytes: input, Char: string(input[:])} + event := KeyEvent{Bytes: input, Char: string(input[:])} var code byte diff --git a/platforms/leap/leap_motion_driver_test.go b/platforms/leap/leap_motion_driver_test.go index 735ad8e4a..34490e40c 100644 --- a/platforms/leap/leap_motion_driver_test.go +++ b/platforms/leap/leap_motion_driver_test.go @@ -30,9 +30,11 @@ func (n *NullReadWriteCloser) Write(p []byte) (int, error) { defer n.mtx.Unlock() return len(p), n.writeError } + func (n *NullReadWriteCloser) Read(b []byte) (int, error) { return len(b), nil } + func (n *NullReadWriteCloser) Close() error { return nil } diff --git a/platforms/mavlink/common/common.go b/platforms/mavlink/common/common.go index 1b26feee0..4f8133186 100644 --- a/platforms/mavlink/common/common.go +++ b/platforms/mavlink/common/common.go @@ -486,7 +486,7 @@ const ( // // MAV_ROI /* The ROI (region of interest) for the vehicle. This can be - be used by the vehicle for camera/vehicle attitude alignment (see + used by the vehicle for camera/vehicle attitude alignment (see MAV_CMD_NAV_ROI).*/ // const ( diff --git a/platforms/mavlink/common/mavlink.go b/platforms/mavlink/common/mavlink.go index 8051e5538..895a84531 100644 --- a/platforms/mavlink/common/mavlink.go +++ b/platforms/mavlink/common/mavlink.go @@ -188,7 +188,7 @@ func crcAccumulate(data uint8, crcAccum uint16) uint16 { tmp = data ^ (uint8)(crcAccum&0xff) tmp ^= (tmp << 4) - crcAccum = (uint16(crcAccum) >> 8) ^ (uint16(tmp) << 8) ^ (uint16(tmp) << 3) ^ (uint16(tmp) >> 4) + crcAccum = (crcAccum >> 8) ^ (uint16(tmp) << 8) ^ (uint16(tmp) << 3) ^ (uint16(tmp) >> 4) return crcAccum } diff --git a/platforms/mavlink/mavlink_driver.go b/platforms/mavlink/mavlink_driver.go index 97c12cdd5..d4330633d 100644 --- a/platforms/mavlink/mavlink_driver.go +++ b/platforms/mavlink/mavlink_driver.go @@ -25,8 +25,7 @@ type Driver struct { gobot.Eventer } -type MavlinkInterface interface { -} +type MavlinkInterface interface{} // NewDriver creates a new mavlink driver. // diff --git a/platforms/microbit/accelerometer_driver.go b/platforms/microbit/accelerometer_driver.go index b1cc4e3a9..97b26ad89 100644 --- a/platforms/microbit/accelerometer_driver.go +++ b/platforms/microbit/accelerometer_driver.go @@ -29,7 +29,7 @@ type AccelerometerData struct { const ( // BLE services - //accelerometerService = "e95d0753251d470aa062fa1922dfa9a8" + // accelerometerService = "e95d0753251d470aa062fa1922dfa9a8" // BLE characteristics accelerometerCharacteristic = "e95dca4b251d470aa062fa1922dfa9a8" @@ -85,7 +85,8 @@ func (b *AccelerometerDriver) Start() error { result := &AccelerometerData{ X: float32(a.X) / 1000.0, Y: float32(a.Y) / 1000.0, - Z: float32(a.Z) / 1000.0} + Z: float32(a.Z) / 1000.0, + } b.Publish(b.Event(Accelerometer), result) }) diff --git a/platforms/microbit/button_driver.go b/platforms/microbit/button_driver.go index 09b17107a..3fc779329 100644 --- a/platforms/microbit/button_driver.go +++ b/platforms/microbit/button_driver.go @@ -14,7 +14,7 @@ type ButtonDriver struct { const ( // BLE services - //buttonService = "e95d9882251d470aa062fa1922dfa9a8" + // buttonService = "e95d9882251d470aa062fa1922dfa9a8" // BLE characteristics buttonACharacteristic = "e95dda90251d470aa062fa1922dfa9a8" diff --git a/platforms/microbit/io_pin_driver.go b/platforms/microbit/io_pin_driver.go index b855c16bc..e9e4e51d6 100644 --- a/platforms/microbit/io_pin_driver.go +++ b/platforms/microbit/io_pin_driver.go @@ -22,7 +22,7 @@ type IOPinDriver struct { const ( // BLE services - //ioPinService = "e95d127b251d470aa062fa1922dfa9a8" + // ioPinService = "e95d127b251d470aa062fa1922dfa9a8" // BLE characteristics pinDataCharacteristic = "e95d8d00251d470aa062fa1922dfa9a8" diff --git a/platforms/microbit/io_pin_driver_test.go b/platforms/microbit/io_pin_driver_test.go index ace606c7d..e04eb1faa 100644 --- a/platforms/microbit/io_pin_driver_test.go +++ b/platforms/microbit/io_pin_driver_test.go @@ -15,9 +15,11 @@ import ( var _ gobot.Driver = (*IOPinDriver)(nil) // that supports the DigitalReader, DigitalWriter, & AnalogReader interfaces -var _ gpio.DigitalReader = (*IOPinDriver)(nil) -var _ gpio.DigitalWriter = (*IOPinDriver)(nil) -var _ aio.AnalogReader = (*IOPinDriver)(nil) +var ( + _ gpio.DigitalReader = (*IOPinDriver)(nil) + _ gpio.DigitalWriter = (*IOPinDriver)(nil) + _ aio.AnalogReader = (*IOPinDriver)(nil) +) func initTestIOPinDriver() *IOPinDriver { d := NewIOPinDriver(NewBleTestAdaptor()) diff --git a/platforms/microbit/led_driver.go b/platforms/microbit/led_driver.go index 3c9af03de..80aca8cd8 100644 --- a/platforms/microbit/led_driver.go +++ b/platforms/microbit/led_driver.go @@ -14,7 +14,7 @@ type LEDDriver struct { const ( // BLE services - //ledService = "e95dd91d251d470aa062fa1922dfa9a8" + // ledService = "e95dd91d251d470aa062fa1922dfa9a8" // BLE characteristics ledMatrixStateCharacteristic = "e95d7b77251d470aa062fa1922dfa9a8" diff --git a/platforms/microbit/magnetometer_driver.go b/platforms/microbit/magnetometer_driver.go index c899be683..c398eddc8 100644 --- a/platforms/microbit/magnetometer_driver.go +++ b/platforms/microbit/magnetometer_driver.go @@ -29,7 +29,7 @@ type MagnetometerData struct { const ( // BLE services - //magnetometerService = "e95df2d8251d470aa062fa1922dfa9a8" + // magnetometerService = "e95df2d8251d470aa062fa1922dfa9a8" // BLE characteristics magnetometerCharacteristic = "e95dfb11251d470aa062fa1922dfa9a8" @@ -85,7 +85,8 @@ func (b *MagnetometerDriver) Start() error { result := &MagnetometerData{ X: float32(a.X) / 1000.0, Y: float32(a.Y) / 1000.0, - Z: float32(a.Z) / 1000.0} + Z: float32(a.Z) / 1000.0, + } b.Publish(b.Event(Magnetometer), result) }) diff --git a/platforms/microbit/temperature_driver.go b/platforms/microbit/temperature_driver.go index 0e7ca7ea1..7daf96077 100644 --- a/platforms/microbit/temperature_driver.go +++ b/platforms/microbit/temperature_driver.go @@ -16,7 +16,7 @@ type TemperatureDriver struct { const ( // BLE services - //temperatureService = "e95d6100251d470aa062fa1922dfa9a8" + // temperatureService = "e95d6100251d470aa062fa1922dfa9a8" // BLE characteristics temperatureCharacteristic = "e95d9250251d470aa062fa1922dfa9a8" diff --git a/platforms/mqtt/doc.go b/platforms/mqtt/doc.go index 5665a7c3f..06f3e194e 100644 --- a/platforms/mqtt/doc.go +++ b/platforms/mqtt/doc.go @@ -3,7 +3,7 @@ Package mqtt provides Gobot adaptor for the mqtt message service. Installing: - Please refer to the main [README.md](https://github.com/hybridgroup/gobot/blob/release/README.md) + Please refer to the main [README.md](https://github.com/hybridgroup/gobot/blob/release/README.md) For further information refer to mqtt README: https://github.com/hybridgroup/gobot/blob/master/platforms/mqtt/README.md diff --git a/platforms/mqtt/mqtt_adaptor.go b/platforms/mqtt/mqtt_adaptor.go index d0889e6c2..24b412445 100644 --- a/platforms/mqtt/mqtt_adaptor.go +++ b/platforms/mqtt/mqtt_adaptor.go @@ -11,10 +11,8 @@ import ( paho "github.com/eclipse/paho.mqtt.golang" ) -var ( - // ErrNilClient is returned when a client action can't be taken because the struct has no client - ErrNilClient = fmt.Errorf("no MQTT client available") -) +// ErrNilClient is returned when a client action can't be taken because the struct has no client +var ErrNilClient = fmt.Errorf("no MQTT client available") // Message is a message received from the broker. type Message paho.Message @@ -234,5 +232,8 @@ func (a *Adaptor) newTLSConfig() *tls.Config { InsecureSkipVerify: false, // Certificates = list of certs client sends to server. Certificates: certs, + // MinVersion contains the minimum TLS version that is acceptable. + // TLS 1.2 is currently used as the minimum when acting as a client. + MinVersion: tls.VersionTLS12, } } diff --git a/platforms/nanopi/nanopi_adaptor_test.go b/platforms/nanopi/nanopi_adaptor_test.go index e75bc6397..3953b6189 100644 --- a/platforms/nanopi/nanopi_adaptor_test.go +++ b/platforms/nanopi/nanopi_adaptor_test.go @@ -18,7 +18,7 @@ const ( ) const ( - pwmDir = "/sys/devices/platform/soc/1c21400.pwm/pwm/pwmchip0/" + pwmDir = "/sys/devices/platform/soc/1c21400.pwm/pwm/pwmchip0/" //nolint:gosec // false positive pwmPwmDir = pwmDir + "pwm0/" pwmExportPath = pwmDir + "export" pwmUnexportPath = pwmDir + "unexport" @@ -47,14 +47,16 @@ var gpioMockPaths = []string{ } // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) func preparePwmFs(fs *system.MockFilesystem) { fs.Files[pwmEnablePath].Contents = "0" @@ -232,7 +234,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -261,7 +263,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -296,7 +298,7 @@ func Test_validateI2cBusNumber(t *testing.T) { } func Test_translateDigitalPin(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { access string pin string wantChip string @@ -339,7 +341,7 @@ func Test_translateDigitalPin(t *testing.T) { func Test_translatePWMPin(t *testing.T) { basePaths := []string{"/sys/devices/platform/soc/1c21400.pwm/pwm/"} - var tests = map[string]struct { + tests := map[string]struct { pin string chip string wantDir string diff --git a/platforms/nats/doc.go b/platforms/nats/doc.go index 3d3bcabd4..5628b9695 100644 --- a/platforms/nats/doc.go +++ b/platforms/nats/doc.go @@ -2,7 +2,7 @@ Package nats provides Gobot adaptor for the nats message service. Installing: - Please refer to the main [README.md](https://github.com/hybridgroup/gobot/blob/release/README.md) + Please refer to the main [README.md](https://github.com/hybridgroup/gobot/blob/release/README.md) For further information refer to nats README: https://github.com/hybridgroup/gobot/blob/master/platforms/nats/README.md diff --git a/platforms/neurosky/neurosky_driver.go b/platforms/neurosky/neurosky_driver.go index a09328ea5..1ebe5198f 100644 --- a/platforms/neurosky/neurosky_driver.go +++ b/platforms/neurosky/neurosky_driver.go @@ -151,7 +151,7 @@ func (n *Driver) parse(buf *bytes.Buffer) error { if _, err := buf.Read(payload); err != nil { return err } - //checksum, _ := buf.ReadByte() + // checksum, _ := buf.ReadByte() buf.Next(1) if err := n.parsePacket(bytes.NewBuffer(payload)); err != nil { panic(err) @@ -183,7 +183,7 @@ func (n *Driver) parsePacket(buf *bytes.Buffer) error { n.Publish(n.Event("blink"), ret) case CodeWave: buf.Next(1) - var ret = make([]byte, 2) + ret := make([]byte, 2) if _, err := buf.Read(ret); err != nil { return err } diff --git a/platforms/neurosky/neurosky_driver_test.go b/platforms/neurosky/neurosky_driver_test.go index 6a85a44a4..d35cd819a 100644 --- a/platforms/neurosky/neurosky_driver_test.go +++ b/platforms/neurosky/neurosky_driver_test.go @@ -160,9 +160,11 @@ func TestNeuroskyDriverParse(t *testing.T) { // CodeAsicEEG go func() { time.Sleep(5 * time.Millisecond) - _ = d.parse(bytes.NewBuffer([]byte{0xAA, 0xAA, 30, 0x83, 24, 1, 121, 89, 0, + _ = d.parse(bytes.NewBuffer([]byte{ + 0xAA, 0xAA, 30, 0x83, 24, 1, 121, 89, 0, 97, 26, 0, 30, 189, 0, 57, 1, 0, 62, 160, 0, 31, 127, 0, 18, 207, 0, 13, - 108, 0x00})) + 108, 0x00, + })) }() _ = d.On(d.Event(EEG), func(data interface{}) { diff --git a/platforms/parrot/ardrone/ardrone_driver_test.go b/platforms/parrot/ardrone/ardrone_driver_test.go index 3f37b1d2d..bec2ff8e2 100644 --- a/platforms/parrot/ardrone/ardrone_driver_test.go +++ b/platforms/parrot/ardrone/ardrone_driver_test.go @@ -41,6 +41,7 @@ func TestArdroneDriverHalt(t *testing.T) { d := initTestArdroneDriver() assert.Nil(t, d.Halt()) } + func TestArdroneDriverTakeOff(t *testing.T) { d := initTestArdroneDriver() d.TakeOff() diff --git a/platforms/parrot/bebop/client/client.go b/platforms/parrot/bebop/client/client.go index 50c76bcbf..9d54c183b 100644 --- a/platforms/parrot/bebop/client/client.go +++ b/platforms/parrot/bebop/client/client.go @@ -202,9 +202,9 @@ func New() *Bebop { } } -func (b *Bebop) write(buf []byte) (int, error) { +func (b *Bebop) write(buf []byte) error { b.writeChan <- buf - return 0, nil + return nil } func (b *Bebop) Discover() error { @@ -248,13 +248,11 @@ func (b *Bebop) Discover() error { func (b *Bebop) Connect() error { err := b.Discover() - if err != nil { return err } c2daddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf("%s:%d", b.IP, b.C2dPort)) - if err != nil { return err } @@ -266,7 +264,6 @@ func (b *Bebop) Connect() error { } d2caddr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", b.D2cPort)) - if err != nil { return err } @@ -278,7 +275,6 @@ func (b *Bebop) Connect() error { go func() { for { _, err := b.c2dClient.Write(<-b.writeChan) - if err != nil { fmt.Println(err) } @@ -302,8 +298,7 @@ func (b *Bebop) Connect() error { // wait a little bit so that there is enough time to get some ACKs time.Sleep(500 * time.Millisecond) for { - _, err := b.write(b.generatePcmd().Bytes()) - if err != nil { + if err := b.write(b.generatePcmd().Bytes()); err != nil { fmt.Println("pcmd c2dClient.Write", err) } time.Sleep(25 * time.Millisecond) @@ -337,8 +332,7 @@ func (b *Bebop) FlatTrim() error { cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) GenerateAllStates() error { @@ -358,8 +352,7 @@ func (b *Bebop) GenerateAllStates() error { cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) TakeOff() error { @@ -379,8 +372,7 @@ func (b *Bebop) TakeOff() error { cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) Land() error { @@ -400,8 +392,7 @@ func (b *Bebop) Land() error { cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) Up(val int) error { @@ -558,9 +549,7 @@ func (b *Bebop) packetReceiver(buf []byte) { // if frame.Type == int(ARNETWORKAL_FRAME_TYPE_DATA_WITH_ACK) { ack := b.createAck(frame).Bytes() - _, err := b.write(ack) - - if err != nil { + if err := b.write(ack); err != nil { fmt.Println("ARNETWORKAL_FRAME_TYPE_DATA_WITH_ACK", err) } } @@ -571,8 +560,7 @@ func (b *Bebop) packetReceiver(buf []byte) { arstreamFrame := NewARStreamFrame(frame.Data) ack := b.createARStreamACK(arstreamFrame).Bytes() - _, err := b.write(ack) - if err != nil { + if err := b.write(ack); err != nil { fmt.Println("ARNETWORKAL_FRAME_TYPE_DATA_LOW_LATENCY", err) } } @@ -582,8 +570,7 @@ func (b *Bebop) packetReceiver(buf []byte) { // if frame.Id == int(ARNETWORK_MANAGER_INTERNAL_BUFFER_ID_PING) { pong := b.createPong(frame).Bytes() - _, err := b.write(pong) - if err != nil { + if err := b.write(pong); err != nil { fmt.Println("ARNETWORK_MANAGER_INTERNAL_BUFFER_ID_PING", err) } } @@ -592,15 +579,13 @@ func (b *Bebop) packetReceiver(buf []byte) { func (b *Bebop) StartRecording() error { buf := b.videoRecord(ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEO_RECORD_START) - _, err := b.write(b.networkFrameGenerator(buf, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(buf, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) StopRecording() error { buf := b.videoRecord(ARCOMMANDS_ARDRONE3_MEDIARECORD_VIDEO_RECORD_STOP) - _, err := b.write(b.networkFrameGenerator(buf, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(buf, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) videoRecord(state byte) *bytes.Buffer { @@ -665,8 +650,7 @@ func (b *Bebop) HullProtection(protect bool) error { } cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) Outdoor(outdoor bool) error { @@ -695,8 +679,7 @@ func (b *Bebop) Outdoor(outdoor bool) error { } cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) VideoEnable(enable bool) error { @@ -721,8 +704,7 @@ func (b *Bebop) VideoEnable(enable bool) error { } cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func (b *Bebop) VideoStreamMode(mode int8) error { @@ -747,8 +729,7 @@ func (b *Bebop) VideoStreamMode(mode int8) error { } cmd.Write(tmp.Bytes()) - _, err := b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) - return err + return b.write(b.networkFrameGenerator(cmd, ARNETWORKAL_FRAME_TYPE_DATA, BD_NET_CD_NONACK_ID).Bytes()) } func bool2int8(b bool) int8 { @@ -834,13 +815,13 @@ func (b *Bebop) createARStreamACK(frame ARStreamFrame) *bytes.Buffer { ackPacket.Write(tmp.Bytes()) tmp = &bytes.Buffer{} - if err := binary.Write(tmp, binary.LittleEndian, uint64(b.tmpFrame.arstreamACK.HighPacketsAck)); err != nil { + if err := binary.Write(tmp, binary.LittleEndian, b.tmpFrame.arstreamACK.HighPacketsAck); err != nil { panic(err) } ackPacket.Write(tmp.Bytes()) tmp = &bytes.Buffer{} - if err := binary.Write(tmp, binary.LittleEndian, uint64(b.tmpFrame.arstreamACK.LowPacketsAck)); err != nil { + if err := binary.Write(tmp, binary.LittleEndian, b.tmpFrame.arstreamACK.LowPacketsAck); err != nil { panic(err) } ackPacket.Write(tmp.Bytes()) diff --git a/platforms/parrot/bebop/client/examples/video.go b/platforms/parrot/bebop/client/examples/video.go index 3946c42c2..0e3731f7d 100644 --- a/platforms/parrot/bebop/client/examples/video.go +++ b/platforms/parrot/bebop/client/examples/video.go @@ -53,14 +53,12 @@ func main() { ffmpeg := exec.Command("ffmpeg", "-i", "pipe:0", "http://localhost:8090/bebop.ffm") ffmpegErr, err := ffmpeg.StderrPipe() - if err != nil { fmt.Println(err) return } ffmpegIn, err := ffmpeg.StdinPipe() - if err != nil { fmt.Println(err) return diff --git a/platforms/parrot/minidrone/minidrone_driver.go b/platforms/parrot/minidrone/minidrone_driver.go index e1d3a1183..926ea0bdb 100644 --- a/platforms/parrot/minidrone/minidrone_driver.go +++ b/platforms/parrot/minidrone/minidrone_driver.go @@ -25,8 +25,8 @@ type Driver struct { const ( // BLE services - //droneCommandService = "9a66fa000800919111e4012d1540cb8e" - //droneNotificationService = "9a66fb000800919111e4012d1540cb8e" + // droneCommandService = "9a66fa000800919111e4012d1540cb8e" + // droneNotificationService = "9a66fb000800919111e4012d1540cb8e" // send characteristics pcmdCharacteristic = "9a66fa0a0800919111e4012d1540cb8e" @@ -419,7 +419,6 @@ func (b *Driver) GunControl(id uint8) error { b.stepsfa0b++ buf := []byte{0x02, byte(b.stepsfa0b) & 0xff, 0x02, 0x10, 0x02, id, 0x00} return b.adaptor().WriteCharacteristic(commandCharacteristic, buf) - } func (b *Driver) generateAnimation(direction int8) *bytes.Buffer { @@ -468,7 +467,7 @@ func (b *Driver) generatePcmd() *bytes.Buffer { if err := binary.Write(cmd, binary.LittleEndian, int8(pcmd.Gaz)); err != nil { panic(err) } - if err := binary.Write(cmd, binary.LittleEndian, float32(pcmd.Psi)); err != nil { + if err := binary.Write(cmd, binary.LittleEndian, pcmd.Psi); err != nil { panic(err) } if err := binary.Write(cmd, binary.LittleEndian, int16(0)); err != nil { diff --git a/platforms/particle/adaptor.go b/platforms/particle/adaptor.go index dbaaf0ca9..2d6b3262f 100644 --- a/platforms/particle/adaptor.go +++ b/platforms/particle/adaptor.go @@ -182,7 +182,6 @@ func (s *Adaptor) EventStream(source string, name string) (event *gobot.Event, e func (s *Adaptor) Variable(name string) (result string, err error) { url := fmt.Sprintf("%v/%s?access_token=%s", s.deviceURL(), name, s.AccessToken) resp, err := s.request("GET", url, nil) - if err != nil { return } @@ -245,9 +244,9 @@ func (s *Adaptor) request(method string, url string, params url.Values) (m map[s var resp *http.Response if method == "POST" { - resp, err = http.PostForm(url, params) + resp, err = http.PostForm(url, params) //nolint:gosec // accepted, because local function and no exposed routing } else if method == "GET" { - resp, err = http.Get(url) + resp, err = http.Get(url) //nolint:gosec // accepted, because local function and no exposed routing } if err != nil { @@ -255,7 +254,6 @@ func (s *Adaptor) request(method string, url string, params url.Values) (m map[s } buf, err := io.ReadAll(resp.Body) - if err != nil { return } diff --git a/platforms/pebble/pebble_adaptor_test.go b/platforms/pebble/pebble_adaptor_test.go index e15597863..23e2488a5 100644 --- a/platforms/pebble/pebble_adaptor_test.go +++ b/platforms/pebble/pebble_adaptor_test.go @@ -17,6 +17,7 @@ func TestAdaptor(t *testing.T) { a := initTestAdaptor() assert.Equal(t, "Pebble", a.Name()) } + func TestAdaptorConnect(t *testing.T) { a := initTestAdaptor() assert.Nil(t, a.Connect()) diff --git a/platforms/raspi/pwm_pin.go b/platforms/raspi/pwm_pin.go index 366ca698d..05f49a952 100644 --- a/platforms/raspi/pwm_pin.go +++ b/platforms/raspi/pwm_pin.go @@ -107,7 +107,7 @@ func (p *PWMPin) SetDutyCycle(duty uint32) error { } func (p *PWMPin) writeValue(data string) (err error) { - fi, err := p.sys.OpenFile(p.path, os.O_WRONLY|os.O_APPEND, 0644) + fi, err := p.sys.OpenFile(p.path, os.O_WRONLY|os.O_APPEND, 0o644) defer fi.Close() //nolint:staticcheck // for historical reasons if err != nil { diff --git a/platforms/raspi/raspi_adaptor.go b/platforms/raspi/raspi_adaptor.go index 19414926a..2d915d550 100644 --- a/platforms/raspi/raspi_adaptor.go +++ b/platforms/raspi/raspi_adaptor.go @@ -5,7 +5,6 @@ import ( "fmt" "strconv" "strings" - "sync" multierror "github.com/hashicorp/go-multierror" @@ -209,7 +208,7 @@ func (c *Adaptor) readRevision() string { } for _, v := range strings.Split(string(content), "\n") { if strings.Contains(v, "Revision") { - s := strings.Split(string(v), " ") + s := strings.Split(v, " ") version, _ := strconv.ParseInt("0x"+s[len(s)-1], 0, 64) if version <= 3 { c.revision = "1" diff --git a/platforms/raspi/raspi_adaptor_test.go b/platforms/raspi/raspi_adaptor_test.go index f73e3f2df..17cbb5b03 100644 --- a/platforms/raspi/raspi_adaptor_test.go +++ b/platforms/raspi/raspi_adaptor_test.go @@ -2,12 +2,11 @@ package raspi import ( "fmt" - "strings" - "testing" - "runtime" "strconv" + "strings" "sync" + "testing" "github.com/stretchr/testify/assert" "gobot.io/x/gobot/v2" @@ -18,15 +17,17 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) -var _ spi.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) + _ spi.Connector = (*Adaptor)(nil) +) func initTestAdaptorWithMockedFilesystem(mockPaths []string) (*Adaptor, *system.MockFilesystem) { a := NewAdaptor() @@ -45,7 +46,7 @@ func TestName(t *testing.T) { func TestGetDefaultBus(t *testing.T) { const contentPattern = "Hardware : BCM2708\n%sSerial : 000000003bc748ea\n" - var tests = map[string]struct { + tests := map[string]struct { revisionPart string wantRev string wantBus int @@ -77,9 +78,9 @@ func TestGetDefaultBus(t *testing.T) { fs := a.sys.UseMockFilesystem([]string{infoFile}) fs.Files[infoFile].Contents = fmt.Sprintf(contentPattern, tc.revisionPart) assert.Equal(t, "", a.revision) - //act, will read and refresh the revision + // act, will read and refresh the revision gotBus := a.DefaultI2cBus() - //assert + // assert assert.Equal(t, tc.wantRev, a.revision) assert.Equal(t, tc.wantBus, gotBus) }) @@ -274,7 +275,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -306,7 +307,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ diff --git a/platforms/rockpi/rockpi_adaptor_test.go b/platforms/rockpi/rockpi_adaptor_test.go index 121777a13..9d1d590e8 100644 --- a/platforms/rockpi/rockpi_adaptor_test.go +++ b/platforms/rockpi/rockpi_adaptor_test.go @@ -21,7 +21,7 @@ func TestDefaultI2cBus(t *testing.T) { } func Test_getPinTranslatorFunction(t *testing.T) { - var cases = map[string]struct { + cases := map[string]struct { pin string model string expectedLine int @@ -71,7 +71,7 @@ func Test_getPinTranslatorFunction(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var cases = map[string]struct { + cases := map[string]struct { busNr int expectedErr error }{ @@ -103,7 +103,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var cases = map[string]struct { + cases := map[string]struct { busNr int wantErr error }{ diff --git a/platforms/sphero/ollie/ollie_driver.go b/platforms/sphero/ollie/ollie_driver.go index eb4f29a18..4ef37d836 100644 --- a/platforms/sphero/ollie/ollie_driver.go +++ b/platforms/sphero/ollie/ollie_driver.go @@ -29,8 +29,8 @@ type Driver struct { const ( // bluetooth service IDs - //spheroBLEService = "22bb746f2bb075542d6f726568705327" - //robotControlService = "22bb746f2ba075542d6f726568705327" + // spheroBLEService = "22bb746f2bb075542d6f726568705327" + // robotControlService = "22bb746f2ba075542d6f726568705327" // BLE characteristic IDs wakeCharacteristic = "22bb746f2bbf75542d6f726568705327" @@ -214,16 +214,15 @@ func (b *Driver) SetTXPower(level int) error { // HandleResponses handles responses returned from Ollie func (b *Driver) HandleResponses(data []byte, e error) { - - //since packets can only be 20 bytes long, we have to puzzle them together + // since packets can only be 20 bytes long, we have to puzzle them together newMessage := false - //append message parts to existing + // append message parts to existing if len(data) > 0 && data[0] != 0xFF { b.asyncBuffer = append(b.asyncBuffer, data...) } - //clear message when new one begins (first byte is always 0xFF) + // clear message when new one begins (first byte is always 0xFF) if len(data) > 0 && data[0] == 0xFF { b.asyncMessage = b.asyncBuffer b.asyncBuffer = data @@ -231,14 +230,14 @@ func (b *Driver) HandleResponses(data []byte, e error) { } parts := b.asyncMessage - //3 is the id of data streaming, located at index 2 byte + // 3 is the id of data streaming, located at index 2 byte if newMessage && len(parts) > 2 && parts[2] == 3 { b.handleDataStreaming(parts) } - //index 1 is the type of the message, 0xFF being a direct response, 0xFE an asynchronous message + // index 1 is the type of the message, 0xFF being a direct response, 0xFE an asynchronous message if len(data) > 4 && data[1] == 0xFF && data[0] == 0xFF { - //locator request + // locator request if data[4] == 0x0B && len(data) == 16 { b.handleLocatorDetected(data) } @@ -253,14 +252,14 @@ func (b *Driver) HandleResponses(data []byte, e error) { // GetLocatorData calls the passed function with the data from the locator func (b *Driver) GetLocatorData(f func(p Point2D)) { - //CID 0x15 is the code for the locator request + // CID 0x15 is the code for the locator request b.PacketChannel() <- b.craftPacket([]uint8{}, 0x02, 0x15) b.locatorCallback = f } // GetPowerState calls the passed function with the Power State information from the sphero func (b *Driver) GetPowerState(f func(p PowerStatePacket)) { - //CID 0x20 is the code for the power state + // CID 0x20 is the code for the power state b.PacketChannel() <- b.craftPacket([]uint8{}, 0x00, 0x20) b.powerstateCallback = f } @@ -271,8 +270,8 @@ func (b *Driver) handleDataStreaming(data []byte) { return } - //data packet is the same as for the normal sphero, since the same communication api is used - //only difference in communication is that the "newer" spheros use BLE for communinations + // data packet is the same as for the normal sphero, since the same communication api is used + // only difference in communication is that the "newer" spheros use BLE for communinations var dataPacket DataStreamingPacket buffer := bytes.NewBuffer(data[5:]) // skip header if err := binary.Read(buffer, binary.BigEndian, &dataPacket); err != nil { @@ -387,7 +386,6 @@ func (b *Driver) craftPacket(body []uint8, did byte, cid byte) *Packet { } func (b *Driver) handlePowerStateDetected(data []uint8) { - var dataPacket PowerStatePacket buffer := bytes.NewBuffer(data[5:]) // skip header if err := binary.Read(buffer, binary.BigEndian, &dataPacket); err != nil { @@ -398,11 +396,11 @@ func (b *Driver) handlePowerStateDetected(data []uint8) { } func (b *Driver) handleLocatorDetected(data []uint8) { - //read the unsigned raw values + // read the unsigned raw values ux := binary.BigEndian.Uint16(data[5:7]) uy := binary.BigEndian.Uint16(data[7:9]) - //convert to signed values + // convert to signed values var x, y int16 if ux > 32255 { @@ -417,7 +415,7 @@ func (b *Driver) handleLocatorDetected(data []uint8) { y = int16(uy) } - //create point obj + // create point obj p := new(Point2D) p.X = x p.Y = y @@ -428,7 +426,6 @@ func (b *Driver) handleLocatorDetected(data []uint8) { } func (b *Driver) handleCollisionDetected(data []uint8) { - if len(data) == ResponsePacketMaxSize { // Check if this is the header of collision response. (i.e. first part of data) // Collision response is 22 bytes long. (individual packet size is maxed at 20) diff --git a/platforms/sphero/ollie/ollie_driver_test.go b/platforms/sphero/ollie/ollie_driver_test.go index 472cc55bf..4eecfee7a 100644 --- a/platforms/sphero/ollie/ollie_driver_test.go +++ b/platforms/sphero/ollie/ollie_driver_test.go @@ -49,7 +49,7 @@ func TestLocatorData(t *testing.T) { } for _, point := range tables { - //0x0B is the locator ID + // 0x0B is the locator ID packet := []byte{0xFF, 0xFF, 0x00, 0x00, 0x0B, point.x1, point.x2, point.y1, point.y2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} d.GetLocatorData(func(p Point2D) { @@ -72,8 +72,9 @@ func TestDataStreaming(t *testing.T) { response = true }) - //example data packet - p1 := []string{"FFFE030053000A003900FAFFFE0007FFFF000000", + // example data packet + p1 := []string{ + "FFFE030053000A003900FAFFFE0007FFFF000000", "000000000000000000FFECFFFB00010000004B01", "BD1034FFFF000300000000000000000000000000", "0000002701FDE500560000000000000065000000", @@ -92,10 +93,10 @@ func TestDataStreaming(t *testing.T) { } - //send empty packet to indicate start of next message + // send empty packet to indicate start of next message d.HandleResponses([]byte{0xFF}, nil) time.Sleep(10 * time.Millisecond) if response == false { - t.Error("no response recieved") + t.Error("no response received") } } diff --git a/platforms/sphero/ollie/ollie_packets.go b/platforms/sphero/ollie/ollie_packets.go index 06c43e34f..673c18954 100644 --- a/platforms/sphero/ollie/ollie_packets.go +++ b/platforms/sphero/ollie/ollie_packets.go @@ -24,7 +24,7 @@ type PowerStatePacket struct { BattVoltage uint16 // Number of charges in the total lifetime of the sphero NumCharges uint16 - //Seconds awake since last charge + // Seconds awake since last charge TimeSinceChg uint16 } diff --git a/platforms/sphero/sphero_driver.go b/platforms/sphero/sphero_driver.go index e1f568a98..b2e9d48ae 100644 --- a/platforms/sphero/sphero_driver.go +++ b/platforms/sphero/sphero_driver.go @@ -403,7 +403,7 @@ func (s *SpheroDriver) getSyncResponse(packet *packet) []byte { return []byte{} } -func (s *SpheroDriver) craftPacket(body []uint8, did byte, cid byte) *packet { +func (s *SpheroDriver) craftPacket(body []uint8, did byte, cid byte) *packet { //nolint:unparam // keep did as parameter s.mtx.Lock() defer s.mtx.Unlock() packet := new(packet) diff --git a/platforms/tinkerboard/adaptor_test.go b/platforms/tinkerboard/adaptor_test.go index 9509388e7..02ce04c1d 100644 --- a/platforms/tinkerboard/adaptor_test.go +++ b/platforms/tinkerboard/adaptor_test.go @@ -18,7 +18,7 @@ const ( ) const ( - pwmDir = "/sys/devices/platform/ff680020.pwm/pwm/pwmchip2/" + pwmDir = "/sys/devices/platform/ff680020.pwm/pwm/pwmchip2/" //nolint:gosec // false positive pwmPwmDir = pwmDir + "pwm0/" pwmExportPath = pwmDir + "export" pwmUnexportPath = pwmDir + "unexport" @@ -47,14 +47,16 @@ var gpioMockPaths = []string{ } // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) +) func preparePwmFs(fs *system.MockFilesystem) { fs.Files[pwmEnablePath].Contents = "0" @@ -232,7 +234,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -268,7 +270,7 @@ func Test_validateSpiBusNumber(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -309,7 +311,7 @@ func Test_validateI2cBusNumber(t *testing.T) { } func Test_translateDigitalPin(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { access string pin string wantChip string @@ -355,7 +357,7 @@ func Test_translatePWMPin(t *testing.T) { "/sys/devices/platform/ff680020.pwm/pwm/", "/sys/devices/platform/ff680030.pwm/pwm/", } - var tests = map[string]struct { + tests := map[string]struct { pin string chip string wantDir string diff --git a/platforms/upboard/up2/adaptor.go b/platforms/upboard/up2/adaptor.go index 19478ab27..5f0360b00 100644 --- a/platforms/upboard/up2/adaptor.go +++ b/platforms/upboard/up2/adaptor.go @@ -125,7 +125,7 @@ func (c *Adaptor) DigitalWrite(id string, val byte) error { // is it one of the built-in LEDs? if id == LEDRed || id == LEDBlue || id == LEDGreen || id == LEDYellow { pinPath := fmt.Sprintf(c.ledPath, id) - fi, err := c.sys.OpenFile(pinPath, os.O_WRONLY|os.O_APPEND, 0666) + fi, err := c.sys.OpenFile(pinPath, os.O_WRONLY|os.O_APPEND, 0o666) defer fi.Close() //nolint:staticcheck // for historical reasons if err != nil { return err @@ -170,5 +170,4 @@ func (c *Adaptor) translatePWMPin(id string) (string, int, error) { return "", -1, fmt.Errorf("'%s' is not a valid id for a PWM pin", id) } return "/sys/class/pwm/pwmchip0", sysPin.pwmPin, nil - } diff --git a/platforms/upboard/up2/adaptor_test.go b/platforms/upboard/up2/adaptor_test.go index 998df6882..d81836dcc 100644 --- a/platforms/upboard/up2/adaptor_test.go +++ b/platforms/upboard/up2/adaptor_test.go @@ -14,15 +14,17 @@ import ( ) // make sure that this Adaptor fulfills all the required interfaces -var _ gobot.Adaptor = (*Adaptor)(nil) -var _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) -var _ gobot.PWMPinnerProvider = (*Adaptor)(nil) -var _ gpio.DigitalReader = (*Adaptor)(nil) -var _ gpio.DigitalWriter = (*Adaptor)(nil) -var _ gpio.PwmWriter = (*Adaptor)(nil) -var _ gpio.ServoWriter = (*Adaptor)(nil) -var _ i2c.Connector = (*Adaptor)(nil) -var _ spi.Connector = (*Adaptor)(nil) +var ( + _ gobot.Adaptor = (*Adaptor)(nil) + _ gobot.DigitalPinnerProvider = (*Adaptor)(nil) + _ gobot.PWMPinnerProvider = (*Adaptor)(nil) + _ gpio.DigitalReader = (*Adaptor)(nil) + _ gpio.DigitalWriter = (*Adaptor)(nil) + _ gpio.PwmWriter = (*Adaptor)(nil) + _ gpio.ServoWriter = (*Adaptor)(nil) + _ i2c.Connector = (*Adaptor)(nil) + _ spi.Connector = (*Adaptor)(nil) +) var pwmMockPaths = []string{ "/sys/class/pwm/pwmchip0/export", @@ -141,7 +143,7 @@ func TestSpiDefaultValues(t *testing.T) { } func Test_validateSpiBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -195,7 +197,7 @@ func TestI2cFinalizeWithErrors(t *testing.T) { } func Test_validateI2cBusNumber(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { busNr int wantErr error }{ @@ -231,7 +233,7 @@ func Test_validateI2cBusNumber(t *testing.T) { } func Test_translatePWMPin(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { wantDir string wantChannel int wantErr error diff --git a/robot.go b/robot.go index 6aa1283bf..647cd8b77 100644 --- a/robot.go +++ b/robot.go @@ -5,9 +5,8 @@ import ( "log" "os" "os/signal" - "sync/atomic" - "sync" + "sync/atomic" multierror "github.com/hashicorp/go-multierror" ) @@ -103,10 +102,10 @@ func (r *Robots) Each(f func(*Robot)) { // NewRobot returns a new Robot. It supports the following optional params: // -// name: string with the name of the Robot. A name will be automatically generated if no name is supplied. -// []Connection: Connections which are automatically started and stopped with the robot -// []Device: Devices which are automatically started and stopped with the robot -// func(): The work routine the robot will execute once all devices and connections have been initialized and started +// name: string with the name of the Robot. A name will be automatically generated if no name is supplied. +// []Connection: Connections which are automatically started and stopped with the robot +// []Device: Devices which are automatically started and stopped with the robot +// func(): The work routine the robot will execute once all devices and connections have been initialized and started func NewRobot(v ...interface{}) *Robot { r := &Robot{ Name: fmt.Sprintf("%X", Rand(int(^uint(0)>>1))), diff --git a/robot_test.go b/robot_test.go index 4d34634f6..5f7e69ced 100644 --- a/robot_test.go +++ b/robot_test.go @@ -47,11 +47,11 @@ func TestRobotStart(t *testing.T) { func TestRobotStartAutoRun(t *testing.T) { adaptor1 := newTestAdaptor("Connection1", "/dev/null") driver1 := newTestDriver(adaptor1, "Device1", "0") - //work := func() {} + // work := func() {} r := NewRobot("autorun", []Connection{adaptor1}, []Device{driver1}, - //work, + // work, ) go func() { diff --git a/robot_work.go b/robot_work.go index 516b3a59d..b3a4e4ac7 100644 --- a/robot_work.go +++ b/robot_work.go @@ -3,9 +3,8 @@ package gobot import ( "context" "fmt" - "time" - "sync" + "time" "github.com/gofrs/uuid" ) @@ -30,7 +29,7 @@ const ( // // someWork := myRobot.Every(context.Background(), time.Second * 2, func(){ // fmt.Println("Here I am doing work") -// }) +// }) // // someWork.CallCancelFunc() // Cancel next tick and remove from work registry // @@ -38,7 +37,7 @@ const ( // // someWork2 := myRobot.Every(context.Background(), time.Second * 2, func(){ // fmt.Println("Here I am doing more work") -// }) +// }) // // somework2.CallCancelFunc() // diff --git a/robot_work_test.go b/robot_work_test.go index 36ed3b4bd..53f401033 100644 --- a/robot_work_test.go +++ b/robot_work_test.go @@ -3,7 +3,6 @@ package gobot import ( "context" "testing" - "time" "github.com/gofrs/uuid" diff --git a/system/digitalpin_access.go b/system/digitalpin_access.go index f5d29befb..9ba351338 100644 --- a/system/digitalpin_access.go +++ b/system/digitalpin_access.go @@ -23,7 +23,8 @@ func (h *sysfsDigitalPinAccess) isSupported() bool { } func (h *sysfsDigitalPinAccess) createPin(chip string, pin int, - o ...func(gobot.DigitalPinOptioner) bool) gobot.DigitalPinner { + o ...func(gobot.DigitalPinOptioner) bool, +) gobot.DigitalPinner { return newDigitalPinSysfs(h.fs, strconv.Itoa(pin), o...) } @@ -41,7 +42,8 @@ func (h *gpiodDigitalPinAccess) isSupported() bool { } func (h *gpiodDigitalPinAccess) createPin(chip string, pin int, - o ...func(gobot.DigitalPinOptioner) bool) gobot.DigitalPinner { + o ...func(gobot.DigitalPinOptioner) bool, +) gobot.DigitalPinner { return newDigitalPinGpiod(chip, pin, o...) } diff --git a/system/digitalpin_access_test.go b/system/digitalpin_access_test.go index 58e5f4292..beda36d0c 100644 --- a/system/digitalpin_access_test.go +++ b/system/digitalpin_access_test.go @@ -16,7 +16,7 @@ func Test_isSupportedSysfs(t *testing.T) { } func Test_isSupportedGpiod(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { mockPaths []string want bool }{ diff --git a/system/digitalpin_bench_test.go b/system/digitalpin_bench_test.go index eb60722c6..c89a65c71 100644 --- a/system/digitalpin_bench_test.go +++ b/system/digitalpin_bench_test.go @@ -20,5 +20,4 @@ func BenchmarkDigitalRead(b *testing.B) { for i := 0; i < b.N; i++ { _, _ = pin.Read() } - } diff --git a/system/digitalpin_config.go b/system/digitalpin_config.go index c576eabd2..26d8bafaf 100644 --- a/system/digitalpin_config.go +++ b/system/digitalpin_config.go @@ -115,7 +115,8 @@ func WithPinDebounce(period time.Duration) func(gobot.DigitalPinOptioner) bool { // WithPinEventOnFallingEdge initializes the input pin for edge detection and call the event handler on falling edges. func WithPinEventOnFallingEdge(handler func(lineOffset int, timestamp time.Duration, detectedEdge string, seqno uint32, - lseqno uint32)) func(gobot.DigitalPinOptioner) bool { + lseqno uint32), +) func(gobot.DigitalPinOptioner) bool { return func(d gobot.DigitalPinOptioner) bool { return d.SetEventHandlerForEdge(handler, digitalPinEventOnFallingEdge) } @@ -123,7 +124,8 @@ func WithPinEventOnFallingEdge(handler func(lineOffset int, timestamp time.Durat // WithPinEventOnRisingEdge initializes the input pin for edge detection and call the event handler on rising edges. func WithPinEventOnRisingEdge(handler func(lineOffset int, timestamp time.Duration, detectedEdge string, seqno uint32, - lseqno uint32)) func(gobot.DigitalPinOptioner) bool { + lseqno uint32), +) func(gobot.DigitalPinOptioner) bool { return func(d gobot.DigitalPinOptioner) bool { return d.SetEventHandlerForEdge(handler, digitalPinEventOnRisingEdge) } @@ -131,7 +133,8 @@ func WithPinEventOnRisingEdge(handler func(lineOffset int, timestamp time.Durati // WithPinEventOnBothEdges initializes the input pin for edge detection and call the event handler on all edges. func WithPinEventOnBothEdges(handler func(lineOffset int, timestamp time.Duration, detectedEdge string, seqno uint32, - lseqno uint32)) func(gobot.DigitalPinOptioner) bool { + lseqno uint32), +) func(gobot.DigitalPinOptioner) bool { return func(d gobot.DigitalPinOptioner) bool { return d.SetEventHandlerForEdge(handler, digitalPinEventOnBothEdges) } diff --git a/system/digitalpin_config_test.go b/system/digitalpin_config_test.go index 808286333..be73c5190 100644 --- a/system/digitalpin_config_test.go +++ b/system/digitalpin_config_test.go @@ -39,7 +39,7 @@ func TestWithPinLabel(t *testing.T) { oldLabel = "old label" newLabel = "my optional label" ) - var tests = map[string]struct { + tests := map[string]struct { setLabel string want bool }{ @@ -70,7 +70,7 @@ func TestWithPinDirectionOutput(t *testing.T) { oldVal = 3 newVal = 5 ) - var tests = map[string]struct { + tests := map[string]struct { oldDir string want bool wantVal int @@ -100,7 +100,7 @@ func TestWithPinDirectionOutput(t *testing.T) { } func TestWithPinDirectionInput(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldDir string want bool }{ @@ -128,7 +128,7 @@ func TestWithPinDirectionInput(t *testing.T) { } func TestWithPinActiveLow(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldActiveLow bool want bool }{ @@ -154,7 +154,7 @@ func TestWithPinActiveLow(t *testing.T) { } func TestWithPinPullDown(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldBias int want bool wantVal int @@ -181,7 +181,7 @@ func TestWithPinPullDown(t *testing.T) { } func TestWithPinPullUp(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldBias int want bool wantVal int @@ -208,7 +208,7 @@ func TestWithPinPullUp(t *testing.T) { } func TestWithPinOpenDrain(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldDrive int want bool wantVal int @@ -239,7 +239,7 @@ func TestWithPinOpenDrain(t *testing.T) { } func TestWithPinOpenSource(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { oldDrive int want bool wantVal int @@ -274,7 +274,7 @@ func TestWithPinDebounce(t *testing.T) { oldVal = time.Duration(10) newVal = time.Duration(14) ) - var tests = map[string]struct { + tests := map[string]struct { oldDebouncePeriod time.Duration want bool wantVal time.Duration @@ -305,7 +305,7 @@ func TestWithPinEventOnFallingEdge(t *testing.T) { oldVal = digitalPinEventNone newVal = digitalPinEventOnFallingEdge ) - var tests = map[string]struct { + tests := map[string]struct { oldEdge int want bool wantVal int @@ -343,7 +343,7 @@ func TestWithPinEventOnRisingEdge(t *testing.T) { oldVal = digitalPinEventNone newVal = digitalPinEventOnRisingEdge ) - var tests = map[string]struct { + tests := map[string]struct { oldEdge int want bool wantVal int @@ -381,7 +381,7 @@ func TestWithPinEventOnBothEdges(t *testing.T) { oldVal = digitalPinEventNone newVal = digitalPinEventOnBothEdges ) - var tests = map[string]struct { + tests := map[string]struct { oldEdge int want bool wantVal int diff --git a/system/digitalpin_gpiod.go b/system/digitalpin_gpiod.go index 1c5497b5e..df913cad1 100644 --- a/system/digitalpin_gpiod.go +++ b/system/digitalpin_gpiod.go @@ -28,24 +28,36 @@ type digitalPinGpiod struct { var digitalPinGpiodReconfigure = digitalPinGpiodReconfigureLine // to allow unit testing -var digitalPinGpiodUsed = map[bool]string{true: "used", false: "unused"} -var digitalPinGpiodActiveLow = map[bool]string{true: "low", false: "high"} -var digitalPinGpiodDebounced = map[bool]string{true: "debounced", false: "not debounced"} +var ( + digitalPinGpiodUsed = map[bool]string{true: "used", false: "unused"} + digitalPinGpiodActiveLow = map[bool]string{true: "low", false: "high"} + digitalPinGpiodDebounced = map[bool]string{true: "debounced", false: "not debounced"} +) -var digitalPinGpiodDirection = map[gpiod.LineDirection]string{gpiod.LineDirectionUnknown: "unknown direction", - gpiod.LineDirectionInput: "input", gpiod.LineDirectionOutput: "output"} +var digitalPinGpiodDirection = map[gpiod.LineDirection]string{ + gpiod.LineDirectionUnknown: "unknown direction", + gpiod.LineDirectionInput: "input", gpiod.LineDirectionOutput: "output", +} -var digitalPinGpiodDrive = map[gpiod.LineDrive]string{gpiod.LineDrivePushPull: "push-pull", gpiod.LineDriveOpenDrain: "open-drain", - gpiod.LineDriveOpenSource: "open-source"} +var digitalPinGpiodDrive = map[gpiod.LineDrive]string{ + gpiod.LineDrivePushPull: "push-pull", gpiod.LineDriveOpenDrain: "open-drain", + gpiod.LineDriveOpenSource: "open-source", +} -var digitalPinGpiodBias = map[gpiod.LineBias]string{gpiod.LineBiasUnknown: "unknown", gpiod.LineBiasDisabled: "disabled", - gpiod.LineBiasPullUp: "pull-up", gpiod.LineBiasPullDown: "pull-down"} +var digitalPinGpiodBias = map[gpiod.LineBias]string{ + gpiod.LineBiasUnknown: "unknown", gpiod.LineBiasDisabled: "disabled", + gpiod.LineBiasPullUp: "pull-up", gpiod.LineBiasPullDown: "pull-down", +} -var digitalPinGpiodEdgeDetect = map[gpiod.LineEdge]string{gpiod.LineEdgeNone: "no", gpiod.LineEdgeRising: "rising", - gpiod.LineEdgeFalling: "falling", gpiod.LineEdgeBoth: "both"} +var digitalPinGpiodEdgeDetect = map[gpiod.LineEdge]string{ + gpiod.LineEdgeNone: "no", gpiod.LineEdgeRising: "rising", + gpiod.LineEdgeFalling: "falling", gpiod.LineEdgeBoth: "both", +} -var digitalPinGpiodEventClock = map[gpiod.LineEventClock]string{gpiod.LineEventClockMonotonic: "monotonic", - gpiod.LineEventClockRealtime: "realtime"} +var digitalPinGpiodEventClock = map[gpiod.LineEventClock]string{ + gpiod.LineEventClockMonotonic: "monotonic", + gpiod.LineEventClockRealtime: "realtime", +} // newDigitalPinGpiod returns a digital pin given the pin number, with the label "gobotio" followed by the pin number. // The pin label can be modified optionally. The pin is handled by the character device Kernel ABI. @@ -53,7 +65,7 @@ func newDigitalPinGpiod(chipName string, pin int, options ...func(gobot.DigitalP if chipName == "" { chipName = "gpiochip0" } - cfg := newDigitalPinConfig("gobotio"+strconv.Itoa(int(pin)), options...) + cfg := newDigitalPinConfig("gobotio"+strconv.Itoa(pin), options...) d := &digitalPinGpiod{ chipName: chipName, pin: pin, @@ -218,7 +230,7 @@ func digitalPinGpiodReconfigureLine(d *digitalPinGpiod, forceInput bool) error { } } else { if systemGpiodDebug { - log.Printf("ouput (%s): ini-state %d, drive %d, inverse %t, bias %d", + log.Printf("output (%s): ini-state %d, drive %d, inverse %t, bias %d", id, d.outInitialState, d.drive, d.activeLow, d.bias) } opts = append(opts, gpiod.AsOutput(d.outInitialState)) diff --git a/system/digitalpin_gpiod_test.go b/system/digitalpin_gpiod_test.go index 78e69f78a..04f8bdd61 100644 --- a/system/digitalpin_gpiod_test.go +++ b/system/digitalpin_gpiod_test.go @@ -8,10 +8,12 @@ import ( "gobot.io/x/gobot/v2" ) -var _ gobot.DigitalPinner = (*digitalPinGpiod)(nil) -var _ gobot.DigitalPinValuer = (*digitalPinGpiod)(nil) -var _ gobot.DigitalPinOptioner = (*digitalPinGpiod)(nil) -var _ gobot.DigitalPinOptionApplier = (*digitalPinGpiod)(nil) +var ( + _ gobot.DigitalPinner = (*digitalPinGpiod)(nil) + _ gobot.DigitalPinValuer = (*digitalPinGpiod)(nil) + _ gobot.DigitalPinOptioner = (*digitalPinGpiod)(nil) + _ gobot.DigitalPinOptionApplier = (*digitalPinGpiod)(nil) +) func Test_newDigitalPinGpiod(t *testing.T) { // arrange @@ -44,7 +46,7 @@ func Test_newDigitalPinGpiodWithOptions(t *testing.T) { } func TestApplyOptions(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { changed []bool simErr error wantReconfigured int @@ -113,7 +115,7 @@ func TestApplyOptions(t *testing.T) { } func TestExport(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { simErr error wantReconfigured int wantErr error @@ -154,7 +156,7 @@ func TestExport(t *testing.T) { } func TestUnexport(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { simNoLine bool simReconfErr error simCloseErr error @@ -216,7 +218,7 @@ func TestUnexport(t *testing.T) { } func TestWrite(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { val int simErr error want int @@ -265,7 +267,7 @@ func TestWrite(t *testing.T) { } func TestRead(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { simVal int simErr error wantErr []string diff --git a/system/digitalpin_mock.go b/system/digitalpin_mock.go index c2e8d2fd2..440df69ea 100644 --- a/system/digitalpin_mock.go +++ b/system/digitalpin_mock.go @@ -13,7 +13,8 @@ type digitalPinMock struct{} func (h *mockDigitalPinAccess) isSupported() bool { return true } func (h *mockDigitalPinAccess) createPin(chip string, pin int, - o ...func(gobot.DigitalPinOptioner) bool) gobot.DigitalPinner { + o ...func(gobot.DigitalPinOptioner) bool, +) gobot.DigitalPinner { dpm := &digitalPinMock{} return dpm } diff --git a/system/digitalpin_sysfs.go b/system/digitalpin_sysfs.go index b716ff639..f29a4157e 100644 --- a/system/digitalpin_sysfs.go +++ b/system/digitalpin_sysfs.go @@ -68,7 +68,7 @@ func (d *digitalPinSysfs) Export() error { // Unexport release the pin func (d *digitalPinSysfs) Unexport() error { - unexport, err := d.fs.openFile(gpioPath+"/unexport", os.O_WRONLY, 0644) + unexport, err := d.fs.openFile(gpioPath+"/unexport", os.O_WRONLY, 0o644) if err != nil { return err } @@ -115,7 +115,7 @@ func (d *digitalPinSysfs) Read() (int, error) { } func (d *digitalPinSysfs) reconfigure() error { - exportFile, err := d.fs.openFile(gpioPath+"/export", os.O_WRONLY, 0644) + exportFile, err := d.fs.openFile(gpioPath+"/export", os.O_WRONLY, 0o644) if err != nil { return err } @@ -137,7 +137,7 @@ func (d *digitalPinSysfs) reconfigure() error { attempt := 0 for { attempt++ - d.dirFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/direction", gpioPath, d.label), os.O_RDWR, 0644) + d.dirFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/direction", gpioPath, d.label), os.O_RDWR, 0o644) if err == nil { break } @@ -151,7 +151,7 @@ func (d *digitalPinSysfs) reconfigure() error { d.valFile.Close() } if err == nil { - d.valFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/value", gpioPath, d.label), os.O_RDWR, 0644) + d.valFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/value", gpioPath, d.label), os.O_RDWR, 0o644) } // configure direction @@ -162,7 +162,7 @@ func (d *digitalPinSysfs) reconfigure() error { // configure inverse logic if err == nil { if d.activeLow { - d.activeLowFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/active_low", gpioPath, d.label), os.O_RDWR, 0644) + d.activeLowFile, err = d.fs.openFile(fmt.Sprintf("%s/%s/active_low", gpioPath, d.label), os.O_RDWR, 0o644) if err == nil { _, err = writeFile(d.activeLowFile, []byte("1")) } diff --git a/system/digitalpin_sysfs_test.go b/system/digitalpin_sysfs_test.go index 5c2fe57b0..4079a45da 100644 --- a/system/digitalpin_sysfs_test.go +++ b/system/digitalpin_sysfs_test.go @@ -9,10 +9,12 @@ import ( "gobot.io/x/gobot/v2" ) -var _ gobot.DigitalPinner = (*digitalPinSysfs)(nil) -var _ gobot.DigitalPinValuer = (*digitalPinSysfs)(nil) -var _ gobot.DigitalPinOptioner = (*digitalPinSysfs)(nil) -var _ gobot.DigitalPinOptionApplier = (*digitalPinSysfs)(nil) +var ( + _ gobot.DigitalPinner = (*digitalPinSysfs)(nil) + _ gobot.DigitalPinValuer = (*digitalPinSysfs)(nil) + _ gobot.DigitalPinOptioner = (*digitalPinSysfs)(nil) + _ gobot.DigitalPinOptionApplier = (*digitalPinSysfs)(nil) +) func initTestDigitalPinSysFsWithMockedFilesystem(mockPaths []string) (*digitalPinSysfs, *MockFilesystem) { fs := newMockFilesystem(mockPaths) diff --git a/system/fs.go b/system/fs.go index ad7edccf3..2bdfd365d 100644 --- a/system/fs.go +++ b/system/fs.go @@ -35,7 +35,6 @@ func (fs *nativeFilesystem) find(baseDir string, pattern string) ([]string, erro for _, item := range items { if reg.MatchString(item.Name()) { found = append(found, path.Join(baseDir, item.Name())) - } } return found, nil diff --git a/system/fs_mock.go b/system/fs_mock.go index 197bad026..f7f1a5f1f 100644 --- a/system/fs_mock.go +++ b/system/fs_mock.go @@ -9,8 +9,10 @@ import ( "time" ) -var _ File = (*MockFile)(nil) -var _ filesystem = (*MockFilesystem)(nil) +var ( + _ File = (*MockFile)(nil) + _ filesystem = (*MockFilesystem)(nil) +) // MockFilesystem represents a filesystem of mock files. type MockFilesystem struct { diff --git a/system/fs_mock_test.go b/system/fs_mock_test.go index 40202c980..dca212b19 100644 --- a/system/fs_mock_test.go +++ b/system/fs_mock_test.go @@ -12,18 +12,18 @@ func TestMockFilesystemOpen(t *testing.T) { f1 := fs.Files["foo"] assert.False(t, f1.Opened) - f2, err := fs.openFile("foo", 0, 0666) + f2, err := fs.openFile("foo", 0, 0o666) assert.Equal(t, f2, f1) assert.Nil(t, err) err = f2.Sync() assert.Nil(t, err) - _, err = fs.openFile("bar", 0, 0666) + _, err = fs.openFile("bar", 0, 0o666) assert.Errorf(t, err, " : bar: no such file") fs.Add("bar") - f4, _ := fs.openFile("bar", 0, 0666) + f4, _ := fs.openFile("bar", 0, 0o666) assert.NotEqual(t, f1.Fd(), f4.Fd()) } @@ -45,7 +45,7 @@ func TestMockFilesystemStat(t *testing.T) { func TestMockFilesystemFind(t *testing.T) { // arrange fs := newMockFilesystem([]string{"/foo", "/bar/foo", "/bar/foo/baz", "/bar/baz/foo", "/bar/foo/bak"}) - var tests = map[string]struct { + tests := map[string]struct { baseDir string pattern string want []string @@ -72,7 +72,7 @@ func TestMockFilesystemWrite(t *testing.T) { fs := newMockFilesystem([]string{"bar"}) f1 := fs.Files["bar"] - f2, err := fs.openFile("bar", 0, 0666) + f2, err := fs.openFile("bar", 0, 0o666) assert.Nil(t, err) // Never been read or written. assert.True(t, f1.Seq <= 0) @@ -88,7 +88,7 @@ func TestMockFilesystemRead(t *testing.T) { f1 := fs.Files["bar"] f1.Contents = "Yip" - f2, err := fs.openFile("bar", 0, 0666) + f2, err := fs.openFile("bar", 0, 0o666) assert.Nil(t, err) // Never been read or written. assert.True(t, f1.Seq <= 0) diff --git a/system/fs_test.go b/system/fs_test.go index 0f5e4e8ad..b4e3a3152 100644 --- a/system/fs_test.go +++ b/system/fs_test.go @@ -9,7 +9,7 @@ import ( func TestFilesystemOpen(t *testing.T) { fs := &nativeFilesystem{} - file, err := fs.openFile(os.DevNull, os.O_RDONLY, 0666) + file, err := fs.openFile(os.DevNull, os.O_RDONLY, 0o666) assert.Nil(t, err) var _ File = file } diff --git a/system/i2c_device.go b/system/i2c_device.go index 9b7717527..2c2e4cba1 100644 --- a/system/i2c_device.go +++ b/system/i2c_device.go @@ -189,7 +189,7 @@ func (d *i2cDevice) WriteByteData(address int, reg uint8, val uint8) error { return err } - var data = val + data := val return d.smbusAccess(address, I2C_SMBUS_WRITE, reg, I2C_SMBUS_BYTE_DATA, unsafe.Pointer(&data)) } @@ -202,7 +202,7 @@ func (d *i2cDevice) WriteWordData(address int, reg uint8, val uint16) error { return err } - var data = val + data := val return d.smbusAccess(address, I2C_SMBUS_WRITE, reg, I2C_SMBUS_WORD_DATA, unsafe.Pointer(&data)) } @@ -381,7 +381,7 @@ func (d *i2cDevice) syscallIoctl(signal uintptr, payload unsafe.Pointer, sender return nil } -func (d *i2cDevice) openFileLazy(sender string) (err error) { +func (d *i2cDevice) openFileLazy(sender string) (err error) { //nolint:unparam // useful for debugging // lazy initialization // note: "os.ModeExclusive" is undefined without create the file. This means for the existing character device, // a second open will not return an error e.g. due to a busy resource, so most likely "os.ModeExclusive" is not really diff --git a/system/i2c_device_test.go b/system/i2c_device_test.go index 1e5e666a1..78682ec40 100644 --- a/system/i2c_device_test.go +++ b/system/i2c_device_test.go @@ -59,7 +59,7 @@ func initTestI2cDeviceWithMockedSys() (*i2cDevice, *mockSyscall) { } func TestNewI2cDevice(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { dev string wantErr string }{ @@ -113,7 +113,7 @@ func TestWriteRead(t *testing.T) { } func TestReadByte(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -157,7 +157,7 @@ func TestReadByte(t *testing.T) { } func TestReadByteData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -204,7 +204,7 @@ func TestReadByteData(t *testing.T) { } func TestReadWordData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -268,7 +268,7 @@ func TestReadBlockData(t *testing.T) { wantB8 = byte(99) wantB9 = byte(111) ) - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -313,7 +313,7 @@ func TestReadBlockData(t *testing.T) { } func TestWriteByte(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -355,7 +355,7 @@ func TestWriteByte(t *testing.T) { } func TestWriteByteData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -402,7 +402,7 @@ func TestWriteByteData(t *testing.T) { } func TestWriteWordData(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -467,7 +467,7 @@ func TestWriteBlockData(t *testing.T) { b8 = byte(0x88) b9 = byte(0x99) ) - var tests = map[string]struct { + tests := map[string]struct { funcs uint64 syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) wantErr string @@ -528,7 +528,7 @@ func Test_setAddress(t *testing.T) { } func Test_queryFunctionality(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { requested uint64 dev string syscallImpl func(trap, a1, a2, a3 uintptr) (r1, r2 uintptr, err SyscallErrno) diff --git a/system/pwmpin_sysfs.go b/system/pwmpin_sysfs.go index d695c6761..5950b7674 100644 --- a/system/pwmpin_sysfs.go +++ b/system/pwmpin_sysfs.go @@ -12,8 +12,8 @@ import ( const pwmDebug = false const ( - pwmPinErrorPattern = "%s() failed for id %s with %v" - pwmPinSetErrorPattern = "%s(%v) failed for id %s with %v" + pwmPinErrorPattern = "%s() failed for id %s with %v" //nolint:gosec // false positive + pwmPinSetErrorPattern = "%s(%v) failed for id %s with %v" //nolint:gosec // false positive ) // pwmPinSysFs represents a PWM pin @@ -221,7 +221,7 @@ func (p *pwmPinSysFs) pwmPolarityPath() string { } func writePwmFile(fs filesystem, path string, data []byte) (int, error) { - file, err := fs.openFile(path, os.O_WRONLY, 0644) + file, err := fs.openFile(path, os.O_WRONLY, 0o644) defer file.Close() //nolint:staticcheck // for historical reasons if err != nil { return 0, err @@ -231,7 +231,7 @@ func writePwmFile(fs filesystem, path string, data []byte) (int, error) { } func readPwmFile(fs filesystem, path string) ([]byte, error) { - file, err := fs.openFile(path, os.O_RDONLY, 0644) + file, err := fs.openFile(path, os.O_RDONLY, 0o644) defer file.Close() //nolint:staticcheck // for historical reasons if err != nil { return make([]byte, 0), err diff --git a/system/spi_access_test.go b/system/spi_access_test.go index d70be2656..e6f0266fc 100644 --- a/system/spi_access_test.go +++ b/system/spi_access_test.go @@ -16,7 +16,7 @@ func TestGpioSpi_isSupported(t *testing.T) { } func TestPeriphioSpi_isSupported(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { mockPaths []string want bool }{ diff --git a/system/syscall_mock.go b/system/syscall_mock.go index 8f00d0198..45317c97d 100644 --- a/system/syscall_mock.go +++ b/system/syscall_mock.go @@ -35,13 +35,13 @@ func (sys *mockSyscall) syscall(trap uintptr, f File, signal uintptr, payload un if sys.smbus.readWrite == I2C_SMBUS_WRITE { // get the data object payload as byte slice - sys.dataSlice = unsafe.Slice((*byte)(unsafe.Pointer(sys.smbus.data)), sys.sliceSize) + sys.dataSlice = unsafe.Slice((*byte)(sys.smbus.data), sys.sliceSize) } if sys.smbus.readWrite == I2C_SMBUS_READ { // fill data object with data from given slice to simulate reading if sys.dataSlice != nil { - slc := unsafe.Slice((*byte)(unsafe.Pointer(sys.smbus.data)), sys.sliceSize) + slc := unsafe.Slice((*byte)(sys.smbus.data), sys.sliceSize) if sys.smbus.protocol == I2C_SMBUS_BLOCK_DATA || sys.smbus.protocol == I2C_SMBUS_I2C_BLOCK_DATA { copy(slc[1:], sys.dataSlice) } else { @@ -54,7 +54,7 @@ func (sys *mockSyscall) syscall(trap uintptr, f File, signal uintptr, payload un // call mock implementation if sys.Impl != nil { - return sys.Impl(trap, f.Fd(), signal, uintptr(unsafe.Pointer(payload))) + return sys.Impl(trap, f.Fd(), signal, uintptr(payload)) } return 0, 0, 0 } @@ -69,6 +69,6 @@ func (sys *mockSyscall) retrieveSliceSize() uint8 { return 2 default: // for I2C_SMBUS_BLOCK_DATA, I2C_SMBUS_I2C_BLOCK_DATA - return *(*byte)(unsafe.Pointer(sys.smbus.data)) + 1 // first data element contains data size + return *(*byte)(sys.smbus.data) + 1 // first data element contains data size } } diff --git a/system/system.go b/system/system.go index 824d43865..708885265 100644 --- a/system/system.go +++ b/system/system.go @@ -113,7 +113,8 @@ func (a *Accesser) UseMockSpi() *MockSpiAccess { // NewDigitalPin returns a new system digital pin, according to the given pin number. func (a *Accesser) NewDigitalPin(chip string, pin int, - o ...func(gobot.DigitalPinOptioner) bool) gobot.DigitalPinner { + o ...func(gobot.DigitalPinOptioner) bool, +) gobot.DigitalPinner { return a.digitalPinAccess.createPin(chip, pin, o...) } diff --git a/system/system_options.go b/system/system_options.go index 302e4462e..049d888c7 100644 --- a/system/system_options.go +++ b/system/system_options.go @@ -40,7 +40,6 @@ func (a *Accesser) setDigitalPinToGpiodAccess() { if systemDebug { fmt.Println("gpiod driver not supported, fallback to sysfs") } - } func (a *Accesser) setSpiToGpioAccess(p gobot.DigitalPinnerProvider, sclkPin, nssPin, mosiPin, misoPin string) { diff --git a/system/system_test.go b/system/system_test.go index 9f2c7243a..2e4e26363 100644 --- a/system/system_test.go +++ b/system/system_test.go @@ -44,7 +44,7 @@ func TestNewAccesser_NewSpiDevice(t *testing.T) { } func TestNewAccesser_IsSysfsDigitalPinAccess(t *testing.T) { - var tests = map[string]struct { + tests := map[string]struct { gpiodAccesser bool wantSys bool }{